import numpy as np
# solve system of linear equation using 
# Gauss-Seidel method using
# a predefined threshold eps=0.01
#  8*x1+3*x2-3*x3=14
# -2*x1-8*x2+5*x3=5
#  3*x1+5*x2+10*x3=-8
# first check if the coefficient matrix is 
# diagonally dominant or not.
a = [[8, 3, -3], [-2, -8, 5], [3, 5, 10]]
# Find diagonal coefficients
diag = np.diag(np.abs(a))
# Find row sum without diagonal
off_diag = np.sum(np.abs(a), axis=1) - diag
if np.all(diag > off_diag):
    print("matrix is diagonally dominant")
else:
    print("NOT diagonally dominant")

x1 = 0.0
x2 = 0.0
x3 = 0.0
epsilon = 0.01
converged = False
x_old = np.array([x1, x2, x3])
print("Iteration results")
print("k,   x1,      x2,     x3 ")
for k in range(1, 50):
    x1 = (14-3*x2+3*x3)/8
    x2 = (5+2*x1-5*x3)/(-8)
    x3 = (-8-3*x1-5*x2)/(-5)
    x = np.array([x1, x2, x3])
    # check if it is smaller than threshold
    dx = np.sqrt(np.dot(x-x_old, x-x_old))
    print("%d, %.4f, %.4f, %.4f"%(k, x1, x2, x3))
    if dx < epsilon:
        converged = True
        print("Converged!")
        break
    # assign the latest x value to the old value
    x_old = x
    if not converged:
        print("Not converged, increase the # of iterations")

Result:

matrix is diagonally dominant
Iteration results
k,   x1,      x2,     x3 
1, 1.7500, -1.0625, 1.5875
Not converged, increase the # of iterations
2, 2.7437, -0.3188, 2.9275
Not converged, increase the # of iterations
3, 2.9673, 0.4629, 3.8433
Not converged, increase the # of iterations
4, 3.0177, 1.0226, 4.4332
Not converged, increase the # of iterations
5, 3.0290, 1.3885, 4.8059
Not converged, increase the # of iterations
6, 3.0315, 1.6208, 5.0397
Not converged, increase the # of iterations
7, 3.0321, 1.7668, 5.1861
Not converged, increase the # of iterations
8, 3.0322, 1.8582, 5.2776
Not converged, increase the # of iterations
9, 3.0322, 1.9154, 5.3348
Not converged, increase the # of iterations
10, 3.0323, 1.9512, 5.3705
Not converged, increase the # of iterations
11, 3.0323, 1.9735, 5.3929
Not converged, increase the # of iterations
12, 3.0323, 1.9875, 5.4068
Not converged, increase the # of iterations
13, 3.0323, 1.9962, 5.4156
Not converged, increase the # of iterations
14, 3.0323, 2.0017, 5.4210
Converged!

Discover more from Tips and Hints for Aerospace Engineers

Subscribe now to keep reading and get access to the full archive.

Continue reading