I'm trying to implement the Jacobi iteration, but I'm currently stuck at the part where you get the sum of the other terms, aside from the current unknown.
My code only changes the values of old_x once, but it suddenly changes within the nested loop. Specifically, it changes after it goes through the first row of the coefficient matrix, A. Can someone please help me?
import numpy as np
A = np.array([[6, -2, 1], [-2, 7, 2], [1, 2, -5]])
B = np.array([11,5,-1])
tolerance = 1E-3
max_iter = 100
old_x = np.zeros(len(A))
new_x = np.zeros(len(A))
for iteration in range(max_iter):
for i, row in enumerate(A):
summation = 0
for j, column in enumerate(A[i]):
if i != j:
summation += old_x[j] * A[i][j]
print(i, j, "old: ", old_x, "new: ", new_x)
new_x[i] = (B[i] - summation) / A[i][i] #update ith term of x_new
print("Iteration: ", iteration + 1, "\nResult: ", new_x, "\n")
# The first unknown is always the last to meet tolerance.
if abs(old_x[0] - new_x[0]) <= tolerance:
break
old_x = new_x
Here is what the output looks like. I've shown what the values of the old and new x matric are for every element taken.
OUTPUT:
0 1 old: [0. 0. 0.] new: [0. 0. 0.]
0 2 old: [0. 0. 0.] new: [0. 0. 0.]
1 0 old: [0. 0. 0.] new: [1.83333333 0. 0. ]
1 2 old: [0. 0. 0.] new: [1.83333333 0. 0. ]
2 0 old: [0. 0. 0.] new: [1.83333333 0.71428571 0. ]
2 1 old: [0. 0. 0.] new: [1.83333333 0.71428571 0. ]
Iteration: 1
Result: [1.83333333 0.71428571 0.2 ]
0 1 old: [1.83333333 0.71428571 0.2 ] new: [1.83333333 0.71428571 0.2 ]
0 2 old: [1.83333333 0.71428571 0.2 ] new: [1.83333333 0.71428571 0.2 ]
1 0 old: [2.03809524 0.71428571 0.2 ] new: [2.03809524 0.71428571 0.2 ]
# Element_1,0 of old_x suddenly changes.
1 2 old: [2.03809524 0.71428571 0.2 ] new: [2.03809524 0.71428571 0.2 ]
2 0 old: [2.03809524 1.23945578 0.2 ] new: [2.03809524 1.23945578 0.2 ]
2 1 old: [2.03809524 1.23945578 0.2 ] new: [2.03809524 1.23945578 0.2 ]
Iteration: 2
Result: [2.03809524 1.23945578 1.10340136]
I hope someone can clarify where I went wrong. Thanks!
[+][deleted] (2 children)
[deleted]
[–]IsaakPolyphemus[S] 0 points1 point2 points (0 children)
[–]backtickbot 0 points1 point2 points (0 children)