Files
CalWay_Python/按方法整理/矩阵-追赶法.py
2025-06-16 22:51:11 +08:00

42 lines
1004 B
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.

import math
# 追赶法求解
def ZGsolve(A,b):
n = len(b)
beta = [0]*n
for i in range(n):
if i == 0:
beta[i] = A[i][2] / A[i][1]
else:
beta[i] = A[i][2] / (A[i][1] - A[i][0]*beta[i-1])
print("beta:")
print(beta[:-1])
for i in range(n):
if i == 0:
b[i] = b[i] / A[i][1]
else:
b[i] = (b[i] - A[i][0]*b[i-1]) / (A[i][1] - A[i][0]*beta[i-1])
print("y:")
print(b)
for i in range(n-2,-1,-1):
b[i] = b[i] - beta[i]*b[i+1]
return b
if __name__ == "__main__":
##########################################################################
#把A,b换成题干的数值###########################################
# 储存追赶法A矩阵
A = [
[0,4,-1],
[-1,4,-1],
[-1,4,-1],
[-1,4,-1],
[-1,4,0]
]
# A第一行前面有个0最后一行后面有个0
b = [100,200,200,200,100]
print("x:")
print(ZGsolve(A,b))