MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / invert_matrix

Function invert_matrix

linear_algebra/matrix_inversion.py:4–28  ·  view source on GitHub ↗

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.700000000000

(matrix: list[list[float]])

Source from the content-addressed store, hash-verified

2
3
4def invert_matrix(matrix: list[list[float]]) -> list[list[float]]:
5 """
6 Returns the inverse of a square matrix using NumPy.
7
8 Parameters:
9 matrix (list[list[float]]): A square matrix.
10
11 Returns:
12 list[list[float]]: Inverted matrix if invertible, else raises error.
13
14 >>> invert_matrix([[4.0, 7.0], [2.0, 6.0]])
15 [[0.6000000000000001, -0.7000000000000001], [-0.2, 0.4]]
16 >>> invert_matrix([[1.0, 2.0], [0.0, 0.0]])
17 Traceback (most recent call last):
18 ...
19 ValueError: Matrix is not invertible
20 """
21 np_matrix = np.array(matrix)
22
23 try:
24 inv_matrix = np.linalg.inv(np_matrix)
25 except np.linalg.LinAlgError:
26 raise ValueError("Matrix is not invertible")
27
28 return inv_matrix.tolist()
29
30
31if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected