From 683a8268ee3c6bc1d3f027675fa7bfd6bc3fc036 Mon Sep 17 00:00:00 2001 From: Namu Date: Mon, 20 Oct 2025 11:40:04 +0200 Subject: [PATCH] Fix: Correct gauss-seidel --- ex3.py | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/ex3.py b/ex3.py index 7f81c10..1c191bb 100644 --- a/ex3.py +++ b/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):