Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. import numpy as np
  2. import time
  3.  
  4. def scaling(A, Y):
  5.     n=len(A)
  6.     for i in range(0, n):
  7.         max = abs(Y[i])
  8.         for j in range(0, n):
  9.             if abs(A[i][j]) > max:
  10.                 max = abs(A[i][j])
  11.         Y[i] = Y[i]/max
  12.         for j in range(0, n):
  13.             A[i][j] = A[i][j]/max
  14.     return A, Y
  15.  
  16. def row_echelon_form(A, Y): #A*X=Y
  17.     n = len(A)
  18.     for i in range(0, n):
  19.         #search for maximum in column i
  20.         max = abs(A[i][i])
  21.         max_row = i
  22.         for j in range(i+1, n):
  23.             if abs(A[j][i]) > max:
  24.                 max = abs(A[j][i])
  25.                 max_row = j
  26.         if(max > 0):
  27.             #swap rows
  28.             A[[i, max_row]] = A[[max_row, i]]
  29.             Y[i], Y[max_row] = Y[max_row], Y[i]
  30.  
  31.             #make 0 in column i
  32.             for j in range(i+1, n):
  33.                 c = -(A[j][i]/A[i][i])
  34.                 A[j][i] = 0
  35.                 Y[j] = Y[j] + (c*Y[i])
  36.                 for k in range(i+1, n):
  37.                     A[j][k] = A[j][k] + (c*A[i][k])
  38.             #up
  39.             for j in range(0, i):
  40.                 c = -(A[j][i]/A[i][i])
  41.                 Y[j] = Y[j] + (c*Y[i])
  42.                 for k in range(i+1, n):
  43.                     A[j][k] = A[j][k] + (c*A[i][k])
  44.  
  45.    
  46.     return A, Y
  47.  
  48. def solve_triangle_lin(A, Y):
  49.     n=len(A)
  50.     X = np.zeros(n)
  51.     X[n-1] = Y[n-1]/A[n-1][n-1]
  52.     for i in range(n-2, -1, -1):
  53.         X[i] = Y[i]/A[i][i]
  54.  
  55.     return X
  56.  
  57. if __name__ == "__main__":
  58.     random_matrix = 100 * np.random.random_sample((5, 5))
  59.     random_Y = 100 * np.random.random_sample(5)
  60.     start_time_np = time.process_time()
  61.     print(np.linalg.solve(random_matrix, random_Y))
  62.     end_time_np = time.process_time()
  63.     print(random_matrix)
  64.     print(random_Y)
  65.     A, Y = scaling(random_matrix, random_Y)
  66.     A, Y = row_echelon_form(A, Y)
  67.     print(A)
  68.     print(Y)
  69.     print(solve_triangle_lin(A, Y))
  70.     end_time = time.process_time()
  71.     print("czas np.linalg: " + str(end_time_np - start_time_np))
  72.     print("czas mojego algorytmu: " + str(end_time - end_time_np))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement