Problem 10: Gauss-Seidelmethod: Import As
Problem 10: Gauss-Seidelmethod: Import As
ITERATION_LIMIT = 1000
print("System of equations:")
for i in range(A.shape[0]):
row = ["{0:3g}*x{1}".format(A[i, j], j + 1) for j in range(A.shape[1])]
print("[{0}] = [{1:3g}]".format(" + ".join(row), b[i]))
x = np.zeros_like(b)
for it_count in range(1, ITERATION_LIMIT):
x_new = np.zeros_like(x)
print("Iteration {0}: {1}".format(it_count, x))
for i in range(A.shape[0]):
s1 = np.dot(A[i, :i], x_new[:i])
s2 = np.dot(A[i, i + 1:], x[i + 1:])
x_new[i] = (b[i] - s1 - s2) / A[i, i]
if np.allclose(x, x_new, rtol=1e-8):
break
x = x_new
print("Solution: {0}".format(x))
error = np.dot(A, x) - b
print("Error: {0}".format(error))
System of equations:
[ 4*x1 + -1*x2 + -1*x3] = [ 3]
[ -2*x1 + 6*x2 + 1*x3] = [ 9]
[ -1*x1 + 1*x2 + 7*x3] = [ -6]
Iteration 1: [0. 0. 0.]
Iteration 2: [ 0.75 1.75 -1. ]
Iteration 3: [ 0.9375 1.97916667 -1.00595238]
Iteration 4: [ 0.99330357 1.99875992 -1.00077948]
Iteration 5: [ 0.99949511 1.99996162 -1.00006664]
Iteration 6: [ 0.99997374 2.00000236 -1.00000409]
Iteration 7: [ 0.99999957 2.00000054 -1.00000014]
Iteration 8: [ 1.0000001 2.00000006 -0.99999999]
Iteration 9: [ 1.00000002 2. -1. ]
Solution: [ 1.00000002 2. -1. ]
Error: [ 5.66606548e-08 -4.54956961e-09 0.00000000e+00]
In [ ]:
localhost:8891/nbconvert/html/Problem10Gauss-SeidelMethod.ipynb?download=false 1/1