|
1 | 1 | """
|
2 | 2 | Gaussian elimination method for solving a system of linear equations.
|
3 | 3 | Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination
|
| 4 | +
|
| 5 | +This function performs Gaussian elimination on the coefficient matrix to transform it into an upper triangular form. |
| 6 | +
|
| 7 | +Parameters: |
| 8 | + coefficients (NDArray[float64]): The square matrix representing the system's coefficients. |
| 9 | + vector (NDArray[float64]): The vector of constants representing the right-hand side of the system of equations. |
| 10 | +
|
| 11 | +Returns: |
| 12 | + NDArray[float64]: The solution vector containing the values of the unknown variables. |
4 | 13 | """
|
5 | 14 |
|
| 15 | + |
6 | 16 | import numpy as np
|
7 | 17 | from numpy import float64
|
8 | 18 | from numpy.typing import NDArray
|
@@ -65,12 +75,20 @@ def gaussian_elimination(
|
65 | 75 | augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)
|
66 | 76 | augmented_mat = augmented_mat.astype("float64")
|
67 | 77 |
|
68 |
| - # scale the matrix leaving it triangular |
| 78 | + # Gaussian elimination with partial pivoting to create an upper triangular matrix |
69 | 79 | for row in range(rows - 1):
|
70 | 80 | pivot = augmented_mat[row, row]
|
71 |
| - for col in range(row + 1, columns): |
72 |
| - factor = augmented_mat[col, row] / pivot |
73 |
| - augmented_mat[col, :] -= factor * augmented_mat[row, :] |
| 81 | + |
| 82 | + # Check for a zero pivot and perform partial pivoting if necessary |
| 83 | + if pivot == 0: |
| 84 | + for i in range(row + 1, rows): |
| 85 | + if augmented_mat[i, row] != 0: |
| 86 | + # Swap rows to move non-zero pivot to the current row |
| 87 | + augmented_mat[[row, i]] = augmented_mat[[i, row]] |
| 88 | + pivot = augmented_mat[row, row] |
| 89 | + break |
| 90 | + else: |
| 91 | + raise ValueError("The matrix is singular and cannot be solved.") |
74 | 92 |
|
75 | 93 | x = retroactive_resolution(
|
76 | 94 | augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]
|
|
0 commit comments