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]])
| 2 | |
| 3 | |
| 4 | def 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 | |
| 31 | if __name__ == "__main__": |