Files
CalWay_Python/228-13.py
2025-06-14 13:26:03 +08:00

58 lines
1.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#模 范数
def Norm(x,v):
if len(x[0]) == 1:
if v == 1:
return sum([abs(i[0]) for i in x])
elif v == 2:
return (sum([i[0]**2 for i in x]))**0.5
elif v == float("inf"):
return max([abs(i[0]) for i in x])
else:
if v == 1:
return max([sum([abs(x[i][j]) for i in range(len(x))]) for j in range(len(x[0]))])
elif v == float("inf"):
return max([sum([abs(i) for i in x[j]]) for j in range(len(x))])
return None
#SOR方法 逐次超松弛迭代
def SOR(A,b,x,w,err,N):
count = 0
n = len(A)
while True:
count += 1
for i in range(n):
sum1 = sum(A[i][j] * x[j] for j in range(i))
sum2 = sum(A[i][j] * x[j] for j in range(i, n))
x[i] += w*(b[i] - sum1 - sum2) / A[i][i]
r = [[b[i] - sum(A[i][j] * x[j] for j in range(len(A[0])))] for i in range(n)]
err_now = Norm(r, float("inf"))
x_t = [round(i,5) for i in x]
print(f"{count}次迭代, 误差 = {err_now:.5}, x = {x_t}")
if err_now < err:
return x, count, 1
if count > N:
return None,count, 0
#把矩阵改成题干的矩阵b改成题干结果err精度要求修改##########################
if __name__ == "__main__":
A = [
[4,-1,0,-1,0,0],
[-1,4,-1,0,-1,0],
[0,-1,4,0,0,-1],
[-1,0,0,4,-1,0],
[0,-1,0,-1,4,-1],
[0,0,-1,0,-1,4]
]
b = [2,3,2,2,1,2]
x = [0,0, 0, 0, 0, 0]
err = 1e-5
#w换成题干要求的值###########################
w = 1
x1,k,sta = SOR(A, b, x, w, err, 100)
print(f"w = {w}, 解为: {x1}, 迭代次数: {k}, 状态: {'收敛' if sta == 1 else '未收敛'}")
w = 1.1
x = [0, 0, 0, 0, 0, 0]
x2,k,sta = SOR(A, b, x, w, err, 100)
print(f"w = {w}, 解为: {x2}, 迭代次数: {k}, 状态: {'收敛' if sta == 1 else '未收敛'}")