Skip to content

Commit 344e158

Browse files
committed
Improved gaussian elimination by adding an explanation about it and then checking for a zero pivot and perform partial pivoting if necessary in the gaussian_elimination function
1 parent fcf82a1 commit 344e158

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

linear_algebra/gaussian_elimination.py

+22-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
"""
22
Gaussian elimination method for solving a system of linear equations.
33
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.
413
"""
514

15+
616
import numpy as np
717
from numpy import float64
818
from numpy.typing import NDArray
@@ -65,12 +75,20 @@ def gaussian_elimination(
6575
augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)
6676
augmented_mat = augmented_mat.astype("float64")
6777

68-
# scale the matrix leaving it triangular
78+
# Gaussian elimination with partial pivoting to create an upper triangular matrix
6979
for row in range(rows - 1):
7080
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.")
7492

7593
x = retroactive_resolution(
7694
augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]

0 commit comments

Comments
 (0)