Fix: Correct gauss-seidel
This commit is contained in:
26
ex3.py
26
ex3.py
@@ -39,28 +39,18 @@ def jacobi(A, b, epsilon=1e-6, max_iter=100_000):
|
||||
return x_new
|
||||
|
||||
|
||||
def gauss_seidel(A, b):
|
||||
x0 = np.array([0, 0, 0])
|
||||
|
||||
def gauss_seidel(A, b, epsilon=1e-6, max_iter=100_000):
|
||||
D = np.diag(np.diag(A))
|
||||
L = np.tril(A, k=-1)
|
||||
U = np.triu(A, k=1)
|
||||
epsilon = 1e-6
|
||||
max_iter = 100_000
|
||||
|
||||
# Pré-calcul de l'inverse de (D - L) pour éviter de le recalculer à chaque itération
|
||||
inv_D_minus_L = np.linalg.inv(D - L)
|
||||
|
||||
x = x0
|
||||
|
||||
x = np.zeros_like(b, dtype=float)
|
||||
for _ in range(max_iter):
|
||||
x_new = inv_D_minus_L @ (-U @ x) + inv_D_minus_L @ b
|
||||
|
||||
if np.linalg.norm(x_new - x, ord=2) < epsilon:
|
||||
return x_new
|
||||
x = x_new
|
||||
|
||||
raise RuntimeError('Gauss-Seidel')
|
||||
x_old = x.copy()
|
||||
# Résolution de (D - L) x = U x_old + b
|
||||
x = np.linalg.solve(D - L, -U @ x_old + b)
|
||||
if np.linalg.norm(x - x_old, ord=2) < epsilon:
|
||||
return x
|
||||
raise RuntimeError('Gauss-Seidel : convergence non atteinte')
|
||||
|
||||
|
||||
def relaxation(A, b, omega=1.0, epsilon=1e-6, max_iter=100_000):
|
||||
|
||||
Reference in New Issue
Block a user