Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions linear_algebra/gaussian_elimination.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
"""
Gaussian elimination method for solving a system of linear equations.
Gaussian elimination - https://en.wikipedia.org/wiki/Gaussian_elimination

This function performs Gaussian elimination on the coefficient matrix to transform it into an upper triangular form.

Check failure on line 5 in linear_algebra/gaussian_elimination.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

linear_algebra/gaussian_elimination.py:5:89: E501 Line too long (116 > 88)

Parameters:
coefficients (NDArray[float64]): The square matrix representing the system's coefficients.

Check failure on line 8 in linear_algebra/gaussian_elimination.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

linear_algebra/gaussian_elimination.py:8:89: E501 Line too long (94 > 88)
vector (NDArray[float64]): The vector of constants representing the right-hand side of the system of equations.

Check failure on line 9 in linear_algebra/gaussian_elimination.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

linear_algebra/gaussian_elimination.py:9:89: E501 Line too long (115 > 88)

Returns:
NDArray[float64]: The solution vector containing the values of the unknown variables.

Check failure on line 12 in linear_algebra/gaussian_elimination.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

linear_algebra/gaussian_elimination.py:12:89: E501 Line too long (89 > 88)
"""

import numpy as np
Expand Down Expand Up @@ -65,12 +74,20 @@
augmented_mat: NDArray[float64] = np.concatenate((coefficients, vector), axis=1)
augmented_mat = augmented_mat.astype("float64")

# scale the matrix leaving it triangular
# Gaussian elimination with partial pivoting to create an upper triangular matrix
for row in range(rows - 1):
pivot = augmented_mat[row, row]
for col in range(row + 1, columns):
factor = augmented_mat[col, row] / pivot
augmented_mat[col, :] -= factor * augmented_mat[row, :]

# Check for a zero pivot and perform partial pivoting if necessary
if pivot == 0:
for i in range(row + 1, rows):
if augmented_mat[i, row] != 0:
# Swap rows to move non-zero pivot to the current row
augmented_mat[[row, i]] = augmented_mat[[i, row]]
pivot = augmented_mat[row, row]
break
else:
raise ValueError("The matrix is singular and cannot be solved.")

x = retroactive_resolution(
augmented_mat[:, 0:columns], augmented_mat[:, columns : columns + 1]
Expand Down
Loading