Skip to content

Commit a1633f7

Browse files
authored
Add Gauss-Seidel method implementation
Implement Gauss-Seidel method for solving linear systems.
1 parent 3cea941 commit a1633f7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
def gauss_seidel(a: list[list[float]], b: list[float], tol: float = 1e-10, max_iter: int = 1000) -> list[float]:
2+
"""
3+
Solve the linear system Ax = b using the Gauss-Seidel iterative method.
4+
5+
Args:
6+
a (list[list[float]]): Coefficient matrix (n x n)
7+
b (list[float]): Right-hand side vector (n)
8+
tol (float): Convergence tolerance
9+
max_iter (int): Maximum number of iterations
10+
11+
Returns:
12+
list[float]: Approximate solution vector
13+
14+
Example:
15+
>>> A = [[4,1,2],[3,5,1],[1,1,3]]
16+
>>> b = [4,7,3]
17+
>>> gauss_seidel(A, b)
18+
[0.5, 1.0, 0.5]
19+
"""
20+
n = len(a)
21+
x = [0.0] * n
22+
for _ in range(max_iter):
23+
x_new = x.copy()
24+
for i in range(n):
25+
s1 = sum(a[i][j] * x_new[j] for j in range(i))
26+
s2 = sum(a[i][j] * x[j] for j in range(i + 1, n))
27+
x_new[i] = (b[i] - s1 - s2) / a[i][i]
28+
if all(abs(x_new[i] - x[i]) < tol for i in range(n)):
29+
return x_new
30+
x = x_new
31+
return x

0 commit comments

Comments
 (0)