1
0

lab3: det Gauss

This commit is contained in:
Suiranoil
2024-03-19 23:28:20 +03:00
parent 00024e4ed1
commit 6ed61aeab9

View File

@@ -0,0 +1,68 @@
import numpy as np
def det(matrix: np.matrix):
if matrix.shape[0] != matrix.shape[1]:
return None
if matrix.shape[0] == 1:
return matrix[0, 0]
return _det(matrix)
def _det(matrix: np.matrix):
matrix, swaps = triangle(np.copy(matrix))
if matrix is None:
return 0.0
n = matrix.shape[0]
determinant = (-1) ** swaps
for i in range(n):
determinant *= matrix[i, i]
return determinant
def triangle(matrix: np.matrix):
swaps = 0
n = matrix.shape[0]
for i in range(n):
if matrix[i, i] == 0:
if not swap_first_non_zero(matrix, i):
return None, swaps
swaps += 1
for j in range(i + 1, n):
matrix[j, :] = matrix[j, :] - matrix[i, :] * (matrix[j, i] / matrix[i, i])
return matrix, swaps
def swap_first_non_zero(matrix, i):
n = matrix.shape[0]
for j in range(i + 1, n):
if matrix[j, i] != 0:
matrix[[i, j], :] = matrix[[j, i], :]
return True
return False
A = np.matrix(
[
[4.3, -12.1, 23.2, -14.1],
[2.4, -4.4, 3.5, 5.5],
[5.4, 8.3, -7.4, 12.7],
[6.3, -7.6, 1.34, 3.7],
],
dtype=np.float64,
)
print(det(A))
print(np.linalg.det(A))
print(A)
B = np.matrix([[-14.4, 6.6, 9.4, 7.3]], dtype=np.float64).T
# X = np.linalg.inv(A) * B