I'm trying to write some code to carry out the Jacobi method for solving linear equations (I realise my method is not the most efficient way to do this but I am trying to figure out why it's not working).
I have tried to debug the problem and noticed the following issue. The code finishes after 2 iterations because on the second iteration on line 32 when xnew[i] is assigned a new value, the same value is also assigned to x[i], even though x[i] is not referenced. Why is this happening on the second iteration and not the first time the for loop is run and is there a way to fix this?
Thanks in advance
import numpy as np
A = np.array(
[[0.93, 0.24, 0],
[0.04, 0.54, 0.26],
[1, 1, 1]])
b = np.array([[6.0], [2.0], [10.0]])
n , m = np.shape(A)
x = np.zeros(shape=(n,1))
xnew = np.zeros(shape=(n,1))
iterlimit = 100
tol = 0.0000001
for iteration in range(iterlimit):
convergence = True
for i in range(n):
sum=0
for j in range(n):
if j != i:
sum = sum + (A[i,j] * x[j])
#on second iteration (iteration =1) below line begins to
#assign x[i] the same values as it assigns xnew[i] causing the
#convergence check below to not run and results in a premature break
xnew[i] = 1/A[i,i] * (b[i] - sum)
if abs(xnew[i]-x[i]) > tol:
convergence = False
if convergence:
break
x = xnew
print("Iteration:", iteration+1)
print("Solution:")
print(np.matrix(xnew))