实现Python简单实现jacobi迭代
程序员文章站
2022-03-08 13:24:15
def Jacobi(mx,mr,n=100,c=0.0001): if len(mx) == len(mr): # mx为系数矩阵,mr x = [] for i in range(len(mr)): x.append([0]) # x矩阵初始化 count = 0 # 迭代次数的计算 while count < n: nx = [] #保存单次迭代后的值的集合...
def Jacobi(mx,mr,n=100,c=0.0001):
if len(mx) == len(mr): # mx为系数矩阵,mr
x = []
for i in range(len(mr)):
x.append([0]) # x矩阵初始化
count = 0 # 迭代次数的计算
while count < n:
nx = [] #保存单次迭代后的值的集合
for i in range(len(x)): # 迭代计算
nxi = mr[i][0]
for j in range(len(x)):
if j != i:
nxi += (-mx[i][j])*x[j][0]
nxi = nxi/mx[i][i]
nx.append([nxi])
lc = [] # 存储两次迭代结果之间的误差的集合
for i in range(len(x)):
lc.append(abs(x[i][0]-nx[i][0]))
if max(lc) < c:
return nx # 当误差满足要求时 返回计算结果
x = nx
count = count + 1
return False # 若达到设定的迭代结果仍不满足精度要求 则方程无解
else:
return False
# 例子
mx = [[8, -3, 2], [4, 11, -1], [6, 3, 12]]
mr = [[20], [33], [36]]
print(Jacobi(mx, mr, 100, 0.00001))
本文地址:https://blog.csdn.net/Youngist/article/details/107297302