Advertisement
myloyo

№5 с нормальным методом Гаусса

Nov 21st, 2024
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def gauss(A):
  4.     A = np.array(A, dtype=float)
  5.     n, m = A.shape
  6.  
  7.     def print_matrix(matrix):
  8.         print(np.array_str(matrix, precision=5, suppress_small=True))
  9.  
  10.     print("Расширенная матрица СЛАУ:")
  11.     print_matrix(A)
  12.     print()
  13.  
  14.     for i in range(n):
  15.         max_row = i + np.argmax(np.abs(A[i:, i]))
  16.         A[[i, max_row]] = A[[max_row, i]]
  17.  
  18.         div = A[i, i]
  19.         A[i] /= div
  20.  
  21.         for j in range(i + 1, n):
  22.             factor = A[j, i]
  23.             A[j] -= factor * A[i]
  24.  
  25.     print("Прямой ход метода Гаусса:")
  26.     print_matrix(A)
  27.     print()
  28.  
  29.     # Обратный ход
  30.     for j in range(n - 1, -1, -1):
  31.         for i in range(j - 1, -1, -1):
  32.             d = A[i, j] / A[j, j]
  33.             A[i, j:] -= A[j, j:] * d
  34.  
  35.     print("Обратный ход метода Гаусса:")
  36.     print_matrix(A)
  37.     print()
  38.  
  39.     s = [round(A[i, -1] / A[i, i], 4) for i in range(n)]
  40.     print("Решение СЛАУ:")
  41.     print(*s)
  42.  
  43.  
  44. n = 5
  45. v = 8
  46. A = [
  47.     [(v + i) / 100 if i != j else v + i for j in range(n)]
  48.     for i in range(n)
  49. ]
  50. V = [v + i for i in range(n)]
  51. B = [sum(A[i][j] * V[j] for j in range(n)) for i in range(n)]
  52. res_matrix = [A[i] + [B[i]] for i in range(n)]
  53.  
  54. gauss(res_matrix)
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement