This repository was archived by the owner on Jun 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSandbox30.py
More file actions
52 lines (40 loc) · 1.28 KB
/
Sandbox30.py
File metadata and controls
52 lines (40 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import numpy as np
import sympy as sp
def calculate_cofactors(matrix):
n = len(matrix)
cofactor_matrix = np.zeros_like(matrix)
for i in range(n):
for j in range(n):
minor_matrix = np.delete(np.delete(matrix, i, axis = 0), j, axis = 1)
cofactor_matrix[i, j] = (-1) ** (i + j) * np.linalg.det(minor_matrix)
return cofactor_matrix
def calculate_inverse(matrix):
determinant = np.linalg.det(matrix)
if determinant == 0:
raise ValueError("Matrix is singular, inverse does not exist")
cofactor_matrix = calculate_cofactors(matrix)
adjugate_matrix = cofactor_matrix.T
inverse_matrix = adjugate_matrix / determinant
return inverse_matrix
def main():
# Replace this with your actual matrix
input_matrix = np.array([
[3, -4, 1, 2],
[-2, -5, 0, -3],
[4, 1, -1, 2],
[1, 3, 0, -5]
])
determinant = np.linalg.det(input_matrix)
cofactor_matrix = calculate_cofactors(input_matrix)
inverse_matrix = calculate_inverse(input_matrix)
print("Input Matrix:")
print(input_matrix)
print("\nDeterminant:", determinant)
print("\nCofactor Matrix:")
print(cofactor_matrix)
print("\nInverse Matrix (as rational numbers):")
for row in inverse_matrix:
rational_row = [sp.Rational(num).limit_denominator() for num in row]
print(rational_row)
if __name__ == "__main__":
main()