Fix minor typo and add matrix dimension check (#6367)

* Fix minor typo in comment

* Add matrix dimension check

* Add descriptive comment
This commit is contained in:
Yannick Brenning 2022-09-24 18:46:03 +02:00 committed by GitHub
parent 5754bd09ff
commit 91c671ebab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -27,14 +27,21 @@ def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]:
[[0.25, -0.5], [-0.3, 1.0]] [[0.25, -0.5], [-0.3, 1.0]]
""" """
D = Decimal # An abbreviation to be conciseness D = Decimal # An abbreviation for conciseness
# Check if the provided matrix has 2 rows and 2 columns, since this implementation only works for 2x2 matrices
if len(matrix) != 2 or len(matrix[0]) != 2 or len(matrix[1]) != 2:
raise ValueError("Please provide a matrix of size 2x2.")
# Calculate the determinant of the matrix # Calculate the determinant of the matrix
determinant = D(matrix[0][0]) * D(matrix[1][1]) - D(matrix[1][0]) * D(matrix[0][1]) determinant = D(matrix[0][0]) * D(matrix[1][1]) - D(matrix[1][0]) * D(matrix[0][1])
if determinant == 0: if determinant == 0:
raise ValueError("This matrix has no inverse.") raise ValueError("This matrix has no inverse.")
# Creates a copy of the matrix with swapped positions of the elements # Creates a copy of the matrix with swapped positions of the elements
swapped_matrix = [[0.0, 0.0], [0.0, 0.0]] swapped_matrix = [[0.0, 0.0], [0.0, 0.0]]
swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0] swapped_matrix[0][0], swapped_matrix[1][1] = matrix[1][1], matrix[0][0]
swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1] swapped_matrix[1][0], swapped_matrix[0][1] = -matrix[1][0], -matrix[0][1]
# Calculate the inverse of the matrix # Calculate the inverse of the matrix
return [[float(D(n) / determinant) or 0.0 for n in row] for row in swapped_matrix] return [[float(D(n) / determinant) or 0.0 for n in row] for row in swapped_matrix]