我试图制作一个python函数来模拟Jacobi线性系统对Ax = b的求解,以实现近似误差的最大容限和最大迭代次数。 我的代码如下
import numpy as np
import numpy.linalg as nla
def jacobi_iterative(A, b, tolerance, max_it): # a_ii!= 0 for all i
n = A.shape[0]
x = np.zeros(np.shape(b))
err = 1.0
it_num = 0
while it_num < max_it:
for i in range(n):
x_k = x.copy()
temp_i_row = A[i, :].copy()
temp_i_row[i] = 0.0
x_k[i] = (-1) * (1 / A[i][i]) * (np.dot(temp_i_row, x_k) + b[i])
err = nla.norm(x_k - x, np.inf) / nla.norm(x_k, np.inf)
if err < tolerance:
x = x_k
it_num += 1
break
else:
x = x_k
it_num += 1
return x, err, it_num
但我不确定它是否能正常工作