|
| 1 | +from decimal import Decimal |
| 2 | +from typing import List |
| 3 | + |
| 4 | + |
| 5 | +def inverse_of_matrix(matrix: List[List[float]]) -> List[List[float]]: |
| 6 | + """ |
| 7 | + A matrix multiplied with its inverse gives the identity matrix. |
| 8 | + This function finds the inverse of a 2x2 matrix. |
| 9 | + If the determinant of a matrix is 0, its inverse does not exist. |
| 10 | +
|
| 11 | + Sources for fixing inaccurate float arithmetic: |
| 12 | + https://stackoverflow.com/questions/6563058/how-do-i-use-accurate-float-arithmetic-in-python |
| 13 | + https://docs.python.org/3/library/decimal.html |
| 14 | +
|
| 15 | + >>> inverse_of_matrix([[2, 5], [2, 0]]) |
| 16 | + [[0.0, 0.5], [0.2, -0.2]] |
| 17 | + >>> inverse_of_matrix([[2.5, 5], [1, 2]]) |
| 18 | + Traceback (most recent call last): |
| 19 | + ... |
| 20 | + ValueError: This matrix has no inverse. |
| 21 | + >>> inverse_of_matrix([[12, -16], [-9, 0]]) |
| 22 | + [[0.0, -0.1111111111111111], [-0.0625, -0.08333333333333333]] |
| 23 | + >>> inverse_of_matrix([[12, 3], [16, 8]]) |
| 24 | + [[0.16666666666666666, -0.0625], [-0.3333333333333333, 0.25]] |
| 25 | + >>> inverse_of_matrix([[10, 5], [3, 2.5]]) |
| 26 | + [[0.25, -0.5], [-0.3, 1.0]] |
| 27 | + """ |
| 28 | + |
| 29 | + D = Decimal # An abbreviation to be conciseness |
| 30 | + # Calculate the determinant of the matrix |
| 31 | + determinant = D(matrix[0][0]) * D(matrix[1][1]) - D(matrix[1][0]) * D(matrix[0][1]) |
| 32 | + if determinant == 0: |
| 33 | + raise ValueError("This matrix has no inverse.") |
| 34 | + # Creates a copy of the matrix with swapped positions of the elements |
| 35 | + swapped_matrix = [[0.0, 0.0], [0.0, 0.0]] |
| 36 | + swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0] |
| 37 | + swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1] |
| 38 | + # Calculate the inverse of the matrix |
| 39 | + return [[float(D(n) / determinant) or 0.0 for n in row] for row in swapped_matrix] |
0 commit comments