Skip to content
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,7 @@
* [Bisection](maths/numerical_analysis/bisection.py)
* [Bisection 2](maths/numerical_analysis/bisection_2.py)
* [Brent Method](maths/numerical_analysis/brent_method.py)
* [Gauss Seidel Method](maths/numerical_analysis/gauss_seidel_method.py)
* [Integration By Simpson Approx](maths/numerical_analysis/integration_by_simpson_approx.py)
* [Intersection](maths/numerical_analysis/intersection.py)
* [Nevilles Method](maths/numerical_analysis/nevilles_method.py)
Expand Down
43 changes: 43 additions & 0 deletions maths/numerical_analysis/gauss_seidel_method.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
def gauss_seidel(
coefficients: list[list[float]],
rhs: list[float],
tol: float = 1e-10,
max_iter: int = 1000,
) -> list[float]:
"""
Solve the linear system Ax = b using the Gauss-Seidel iterative method.

Args:
coefficients (list[list[float]]): Coefficient matrix (n x n)
rhs (list[float]): Right-hand side vector (n)
tol (float): Convergence tolerance
max_iter (int): Maximum number of iterations

Returns:
list[float]: Approximate solution vector

Example:
>>> A = [[4, 1, 2], [3, 5, 1], [1, 1, 3]]
>>> b = [4, 7, 3]
>>> gauss_seidel(A, b)
[0.5, 1.0, 0.5]

Wikipedia:
https://en.wikipedia.org/wiki/Gauss%E2%80%93Seidel_method
"""
n = len(coefficients)
x = [0.0 for _ in range(n)]

for _ in range(max_iter):
x_new = x.copy()
for i in range(n):
sum_before = sum(coefficients[i][j] * x_new[j] for j in range(i))
sum_after = sum(coefficients[i][j] * x[j] for j in range(i + 1, n))
x_new[i] = (rhs[i] - sum_before - sum_after) / coefficients[i][i]

if all(abs(x_new[i] - x[i]) < tol for i in range(n)):
return [round(val, 10) for val in x_new]

x = x_new

return [round(val, 10) for val in x]