I have created the following code. Everything is correct besides my output statement. On the end of the x: array there is a 79 which stands for the number of iterations. I am trying to make a statement which uses
print("The number of iterations is", )
I tried to put iter_ct in there but it gave me an error. Looking for some help with making this adjustment, thanks! import numpy as np from pprint import pprint from numpy import array, zeros, diag, diagflat, dot
def jacobi(A,b,N=100,x=None):
"""Solves the equation Ax=b via the Jacobi iterative method."""
# Create an initial guess if needed
if x is None:
x = zeros(len(A[0]))
# Create a vector of the diagonal elements of A
# and subtract them from A
D = diag(A)
R = A - diagflat(D)
x_old = x
error = 1.0 # Dummy value
iter_ct = 0
while error > 10 ** (-15):
x = (b - dot(R, x_old)) / D
error = np.linalg.norm(x - x_old)
iter_ct += 1
x_old = x
return x, iter_ct
A = np.array([[3.0, 1.0, 0., 0., 0., 0., 0., 0., 0., 0.],[1.0, 3.0, 1.0, 0., 0., 0., 0., 0., 0., 0.], [0., 1.0, 3.0, 1.0, 0., 0., 0., 0., 0., 0.], [0., 0, 1.0, 3.0, 1.0, 0., 0., 0., 0., 0.], [0., 0., 0., 1.0, 3.0, 1.0, 0., 0., 0., 0.], [0., 0., 0., 0., 1.0, 3.0, 1.0, 0., 0., 0.], [0., 0., 0., 0., 0., 1.0, 3.0, 1.0, 0., 0.], [0., 0., 0., 0., 0., 0., 1.0, 3.0, 1.0, 0.], [0., 0., 0., 0., 0., 0., 0., 1.0, 3.0, 1.0], [0., 0., 0., 0., 0., 0., 0., 0., 1.0, 3.0]])
b = np.array([1.0,1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
guess = np.array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
sol, iter = jacobi(A,b,N=100,x=guess)
print ("A:")
pprint(A)
print ("b:")
pprint(b)
print ("x:")
pprint(sol)
print("It took",sol[1], "iterations.")
This is the current output I am getting now. Notice the 79 on the end of the x: array
A:
array([[3., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[1., 3., 1., 0., 0., 0., 0., 0., 0., 0.],
[0., 1., 3., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 1., 3., 1., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 3., 1., 0., 0., 0., 0.],
[0., 0., 0., 0., 1., 3., 1., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 3., 1., 0., 0.],
[0., 0., 0., 0., 0., 0., 1., 3., 1., 0.],
[0., 0., 0., 0., 0., 0., 0., 1., 3., 1.],
[0., 0., 0., 0., 0., 0., 0., 0., 1., 3.]])
b:
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
x:
(array([0.27638191, 0.17085427, 0.21105528, 0.1959799 , 0.20100503,
0.20100503, 0.1959799 , 0.21105528, 0.17085427, 0.27638191]),
79)