import numpy as np

def gauss_seidel(A, b, x0, tol, max_iter):
    # Vérifier si la matrice est diagonalement dominante
    if not np.all(np.abs(np.diag(A)) > np.sum(np.abs(A), axis=1) - np.abs(np.diag(A))):
        print("La matrice n'est pas diagonalement dominante. La convergence peut ne pas être garantie.")

    # Initialisation
    x = x0.copy()
    iter = 0
    error = tol + 1

    # Itération de Gauss-Seidel
    while error > tol and iter < max_iter:
        x_old = x.copy()
        for i in range(len(b)):
            x[i] = (b[i] - np.dot(A[i,:i], x[:i]) - np.dot(A[i,i+1:], x[i+1:])) / A[i,i]
        iter += 1
        error = np.max(np.abs(x - x_old))

    # Vérification de la convergence
    if iter == max_iter and error > tol:
        print("La méthode de Gauss-Seidel peut ne pas avoir convergé.")

    return x, iter

# Exemple d'utilisation
A = np.array([[5, 1, 2, -1], 
              [0,  4, 1, -1],
              [-1,  1,  5, 1],
              [1,  2,  0,  6]])
b = np.array([7, -2, 2, -7])
x0 = np.zeros_like(b)
tol = 1e-3
max_iter = 6

x, iter = gauss_seidel(A, b, x0, tol, max_iter)
print("Solution:")
print(x)
print("Nombre d'itérations:", iter)

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: