A matrix multiplied with its inverse gives the identity matrix. This function finds the inverse of a 2x2 and 3x3 matrix. If the determinant of a matrix is 0, its inverse does not exist. Sources for fixing inaccurate float arithmetic: https://stackoverflow.com/questions/65
(matrix: list[list[float]])
| 6 | |
| 7 | |
| 8 | def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]: |
| 9 | """ |
| 10 | A matrix multiplied with its inverse gives the identity matrix. |
| 11 | This function finds the inverse of a 2x2 and 3x3 matrix. |
| 12 | If the determinant of a matrix is 0, its inverse does not exist. |
| 13 | |
| 14 | Sources for fixing inaccurate float arithmetic: |
| 15 | https://stackoverflow.com/questions/6563058/how-do-i-use-accurate-float-arithmetic-in-python |
| 16 | https://docs.python.org/3/library/decimal.html |
| 17 | |
| 18 | Doctests for 2x2 |
| 19 | >>> inverse_of_matrix([[2, 5], [2, 0]]) |
| 20 | [[0.0, 0.5], [0.2, -0.2]] |
| 21 | >>> inverse_of_matrix([[2.5, 5], [1, 2]]) |
| 22 | Traceback (most recent call last): |
| 23 | ... |
| 24 | ValueError: This matrix has no inverse. |
| 25 | >>> inverse_of_matrix([[12, -16], [-9, 0]]) |
| 26 | [[0.0, -0.1111111111111111], [-0.0625, -0.08333333333333333]] |
| 27 | >>> inverse_of_matrix([[12, 3], [16, 8]]) |
| 28 | [[0.16666666666666666, -0.0625], [-0.3333333333333333, 0.25]] |
| 29 | >>> inverse_of_matrix([[10, 5], [3, 2.5]]) |
| 30 | [[0.25, -0.5], [-0.3, 1.0]] |
| 31 | |
| 32 | Doctests for 3x3 |
| 33 | >>> inverse_of_matrix([[2, 5, 7], [2, 0, 1], [1, 2, 3]]) |
| 34 | [[2.0, 5.0, -4.0], [1.0, 1.0, -1.0], [-5.0, -12.0, 10.0]] |
| 35 | >>> inverse_of_matrix([[1, 2, 2], [1, 2, 2], [3, 2, -1]]) |
| 36 | Traceback (most recent call last): |
| 37 | ... |
| 38 | ValueError: This matrix has no inverse. |
| 39 | |
| 40 | >>> inverse_of_matrix([[],[]]) |
| 41 | Traceback (most recent call last): |
| 42 | ... |
| 43 | ValueError: Please provide a matrix of size 2x2 or 3x3. |
| 44 | |
| 45 | >>> inverse_of_matrix([[1, 2], [3, 4], [5, 6]]) |
| 46 | Traceback (most recent call last): |
| 47 | ... |
| 48 | ValueError: Please provide a matrix of size 2x2 or 3x3. |
| 49 | |
| 50 | >>> inverse_of_matrix([[1, 2, 1], [0,3, 4]]) |
| 51 | Traceback (most recent call last): |
| 52 | ... |
| 53 | ValueError: Please provide a matrix of size 2x2 or 3x3. |
| 54 | |
| 55 | >>> inverse_of_matrix([[1, 2, 3], [7, 8, 9], [7, 8, 9]]) |
| 56 | Traceback (most recent call last): |
| 57 | ... |
| 58 | ValueError: This matrix has no inverse. |
| 59 | |
| 60 | >>> inverse_of_matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) |
| 61 | [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] |
| 62 | """ |
| 63 | |
| 64 | d = Decimal |
| 65 |
nothing calls this directly
no outgoing calls
no test coverage detected