forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix_inversion.py
36 lines (27 loc) · 940 Bytes
/
matrix_inversion.py
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
import numpy as np
def invert_matrix(matrix: list[list[float]]) -> list[list[float]]:
"""
Returns the inverse of a square matrix using NumPy.
Parameters:
matrix (list[list[float]]): A square matrix.
Returns:
list[list[float]]: Inverted matrix if invertible, else raises error.
>>> invert_matrix([[4.0, 7.0], [2.0, 6.0]])
[[0.6000000000000001, -0.7000000000000001], [-0.2, 0.4]]
>>> invert_matrix([[1.0, 2.0], [0.0, 0.0]])
Traceback (most recent call last):
...
ValueError: Matrix is not invertible
"""
np_matrix = np.array(matrix)
try:
inv_matrix = np.linalg.inv(np_matrix)
except np.linalg.LinAlgError:
raise ValueError("Matrix is not invertible")
return inv_matrix.tolist()
if __name__ == "__main__":
mat = [[4.0, 7.0], [2.0, 6.0]]
print("Original Matrix:")
print(mat)
print("Inverted Matrix:")
print(invert_matrix(mat))