Menu Close

Gauss-Seidel Method | Python

The Gauss-Seidel method is an iterative method for solving a linear system of equations, typically represented by the matrix equation Ax = b, where A is a matrix of coefficients, x is a vector of unknowns, and b is a vector of constants.

In Python, you can implement the Gauss-Seidel method using a for loop to iterate over the elements of the matrix and update the values of the unknowns based on the equations.

The below code defines a function gauss_seidel that takes as input a matrix of coefficients A, a vector of constants b, an initial guess for the solution x0, a tolerance epsilon, and a maximum number of iterations max_iterations.

The function uses a for loop to iterate over the elements of the matrix and update the values of the unknowns based on the equations.

The function stops iterating when the difference between successive approximations is less than the specified tolerance epsilon or when the maximum number of iterations is reached.

 

Gauss-Seidel Method in Python

				
					import numpy as np

def gauss_seidel(A, b, x0, epsilon, max_iterations):
    n = len(A)
    x = x0.copy()
    
    #Gauss-Seidal Method [By Bottom Science]
    
    for i in range(max_iterations):
        x_new = np.zeros(n)
        for j in range(n):
            s1 = np.dot(A[j, :j], x_new[:j])
            s2 = np.dot(A[j, j + 1:], x[j + 1:])
            x_new[j] = (b[j] - s1 - s2) / A[j, j]
        if np.allclose(x, x_new, rtol=epsilon):
            return x_new
        x = x_new
    return x

A = np.array([[10, -1, 2, 0],
              [-1, 11, -1, 3],
              [2, -1, 10, -1],
              [0, 3, -1, 8]])
b = np.array([6, 25, -11, 15])
x0 = np.zeros(4)
eps = 1e-5
max_iter = 100

x = gauss_seidel(A, b, x0, eps, max_iter)
print(x)

#OUTPUT - [ 1.00000067  2.00000002 -1.00000021  0.99999996]
				
			

More Related Stuff