brospresident

Untitled

Oct 20th, 2021
690
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2.  
  3. rng = np.random.default_rng(0)  #generator
  4. #----------- Input --------------
  5. n = 5 # dimensiunea matricei
  6. A = rng.integers(1,11, size = (n,n))
  7. A = np.triu(A,-1)
  8. A = A.astype('float')
  9. b =  rng.integers(-10,11, size = (n,1)).astype('float')
  10.  
  11. #-------------------------------------
  12. print('-----------A------------')
  13. print(A)
  14. print('-----------b------------')
  15. print(b)
  16.  
  17. def EGPP(A: np.ndarray):
  18.     n = len(A)
  19.     p = np.zeros(n, dtype = int)
  20.  
  21.     for k in range(n - 1):
  22.         p[k] = k
  23.         for i in range(k, n):
  24.             if abs(A[i][k]) is max(abs(A[k : n][k])):
  25.                 p[k] = i
  26.  
  27.         for j in range(k, n):
  28.             temp = A[k][j]
  29.             A[k][j] = A[p[k]][j]
  30.             A[p[k], j] = temp
  31.  
  32.         for i in range(k + 1, n):
  33.             A[i][k] = A[i][k] / A[k][k]
  34.  
  35.         for i in range(k + 1, n):
  36.             for j in range(k + 1, n):
  37.                 A[i][j] = A[i][j] - A[i][k] * A[k][j]
  38.         return A, p
  39.  
  40. def S_SUP_TR(U: np.ndarray, b: np.ndarray):
  41.     n = len(U)
  42.     x = np.zeros(n, dtype = float)
  43.  
  44.     for i in range(n - 1, -1, -1):
  45.         s = b[i]
  46.         for j in range(i + 1, n):
  47.              s = s - U[i][j] * x[j]
  48.         x[i] = s / U[i][i]
  49.  
  50.     return x
  51.  
  52. def Solver(A: np.ndarray, b: np.ndarray):
  53.     x = np.zeros(n, dtype = float)
  54.     U, p = EGPP(A)
  55.     for k in range(n - 1):
  56.         b[k], b[p[k]] = b[p[k]], b[k]
  57.         for i in range(k + 1, n):
  58.             b[i] = b[i] - A[i][k] * b[k]
  59.     x = S_SUP_TR(U, b)
  60.  
  61.     return x
  62.  
  63. print("Result")
  64. result = Solver(A, b)
  65. print(result)
  66.  
  67. if result is np.linalg.inv(A) * b:
  68.     print("E corect")
  69. else:
  70.     print("E gresit")
RAW Paste Data