Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- def print_matrix(matrix):
- print(np.array_str(matrix, precision=5, suppress_small=True))
- def gauss(A):
- A = np.array(A, dtype=float)
- n, m = A.shape
- # Прямой ход
- for i in range(n):
- max_row = i + np.argmax(np.abs(A[i:, i]))
- A[[i, max_row]] = A[[max_row, i]]
- div = A[i, i]
- A[i] /= div
- for j in range(i + 1, n):
- factor = A[j, i]
- A[j] -= factor * A[i]
- print(f"\nМатрица после прямого хода:")
- print_matrix(A)
- # Обратный ход
- for j in range(n - 1, -1, -1):
- for i in range(j - 1, -1, -1):
- d = A[i, j] / A[j, j]
- A[i, j:] -= A[j, j:] * d
- print("Обратный ход метода Гаусса:")
- print_matrix(A)
- print()
- s = [round(A[i, -1] / A[i, i], 4) for i in range(n)]
- print("Решение СЛАУ:")
- print(*s)
- return A
- def determinant(A):
- A = np.array(A, dtype=float)
- n = A.shape[0]
- det = 1
- for j in range(n):
- if A[j, j] == 0:
- return 0 # Если на диагонали 0, то матрица вырождена
- det *= A[j, j]
- for i in range(j + 1, n):
- if A[i, j] != 0:
- d = A[i, j] / A[j, j]
- A[i, j:] -= A[j, j:] * d
- return det
- def inverse_matrix(A):
- n = len(A)
- A = np.array(A, dtype=float)
- inv_A = np.hstack([A, np.eye(n)])
- res_A = gauss(inv_A)
- return res_A[:, n:]
- A = np.array([
- [7, 0, 1, 2],
- [5, 4, 3, 8],
- [1, 2, 3, 4],
- [5, 2, 2, 5]])
- det = determinant(A)
- print(f"\nОпределитель: {det:0.4f}")
- inv_A = inverse_matrix(A)
- print("\nОбратная матрица:")
- for row in inv_A:
- print(" ".join([f"{x:0.4f}" for x in row]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement