Solve the linear system of equations Ax = b (A = "matrix", b = "vector") for x using Gaussian elimination and back substitution. We assume that A is an invertible square matrix and that b is a column vector of the same height. >>> solve([[1, 0], [0, 1]], [[1],[2]]) [[1.0], [
(matrix: Matrix, vector: Matrix)
| 50 | |
| 51 | |
| 52 | def solve(matrix: Matrix, vector: Matrix) -> Matrix: |
| 53 | """ |
| 54 | Solve the linear system of equations Ax = b (A = "matrix", b = "vector") |
| 55 | for x using Gaussian elimination and back substitution. We assume that A |
| 56 | is an invertible square matrix and that b is a column vector of the |
| 57 | same height. |
| 58 | >>> solve([[1, 0], [0, 1]], [[1],[2]]) |
| 59 | [[1.0], [2.0]] |
| 60 | >>> solve([[2, 1, -1],[-3, -1, 2],[-2, 1, 2]],[[8], [-11],[-3]]) |
| 61 | [[2.0], [3.0], [-1.0]] |
| 62 | """ |
| 63 | size: int = len(matrix) |
| 64 | augmented: Matrix = [[0 for _ in range(size + 1)] for _ in range(size)] |
| 65 | row: int |
| 66 | row2: int |
| 67 | col: int |
| 68 | col2: int |
| 69 | pivot_row: int |
| 70 | ratio: float |
| 71 | |
| 72 | for row in range(size): |
| 73 | for col in range(size): |
| 74 | augmented[row][col] = matrix[row][col] |
| 75 | |
| 76 | augmented[row][size] = vector[row][0] |
| 77 | |
| 78 | row = 0 |
| 79 | col = 0 |
| 80 | while row < size and col < size: |
| 81 | # pivoting |
| 82 | pivot_row = max((abs(augmented[row2][col]), row2) for row2 in range(col, size))[ |
| 83 | 1 |
| 84 | ] |
| 85 | if augmented[pivot_row][col] == 0: |
| 86 | col += 1 |
| 87 | continue |
| 88 | else: |
| 89 | augmented[row], augmented[pivot_row] = augmented[pivot_row], augmented[row] |
| 90 | |
| 91 | for row2 in range(row + 1, size): |
| 92 | ratio = augmented[row2][col] / augmented[row][col] |
| 93 | augmented[row2][col] = 0 |
| 94 | for col2 in range(col + 1, size + 1): |
| 95 | augmented[row2][col2] -= augmented[row][col2] * ratio |
| 96 | |
| 97 | row += 1 |
| 98 | col += 1 |
| 99 | |
| 100 | # back substitution |
| 101 | for col in range(1, size): |
| 102 | for row in range(col): |
| 103 | ratio = augmented[row][col] / augmented[col][col] |
| 104 | for col2 in range(col, size + 1): |
| 105 | augmented[row][col2] -= augmented[col][col2] * ratio |
| 106 | |
| 107 | # round to get rid of numbers like 2.000000000000004 |
| 108 | return [ |
| 109 | [round(augmented[row][size] / augmented[row][row], 10)] for row in range(size) |