欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python追赶法解方程组

程序员文章站 2022-04-01 10:26:04
...
A=[]            #定义一个列表存储系数矩阵
L=[]
U=[]
Y=[]
a=-1
b=4
c=-1
S = a           #   S----γ
T=[]            #   T----β
R=[]            #   R----α
Answer_X=[]
N=5
X=['x1','x2','x3','x4','x5']
f=[100,200,200,200,100]
def agmA():
    for i in range(N):
        A.append([])
        for j in range(N):
            if i==j:
                A[i].append(b)
            elif i+1==j:
                A[i].append(c)
            elif i==j+1:
                A[i].append(a)
            else:
                A[i].append(0)
def LU(a,b,c):
    R.append(b)
    T.append(c/R[0])
    for i in range(N-1):
        R.append(b-a*T[i])
        T.append(c/R[i+1])
    R.append(b-a*T[i])
def agmLU():
    LU(a,b,c)
    for i in range(N):
        L.append([])
        for j in range(N):
            if i==j:
                L[i].append(R[i])
            elif i==j+1:
                L[i].append(S)
            else:
                L[i].append(0)
    for i in range(N):
        U.append([])
        for j in range(N):
            if  i==j:
                U[i].append(1)
            elif i+1==j:
                U[i].append(T[i])
            else:
                U[i].append(0)
def CAL_Y():
    Y.append(f[0]/R[0])
    for i in range(N-1):
        y=(f[i+1]-S*Y[i])/R[i+1]
        Y.append(y)
def CAL_X():
    RE_X=[]
    RE_X.append(Y[N-1])
    for i in range(N-1):
        RE_X.append(Y[N-i-2]-T[N-i-2]*RE_X[i])
    for i in range(N):
        Answer_X.append(RE_X[N-i-1])
def print_Answer():
    # print("系数矩阵为:")
    # for i in range(N):
    #     for j in range(N):
    #         print(A[i][j])
    #     print("\n")
    print("运算结果为:")
    for i in range(N):
        print("{}={}".format(X[i], Answer_X[i]))
agmA()
agmLU()
CAL_Y()
CAL_X()
print_Answer()
# print(A)
# print(L)
# print(U)
# print("S={}".format(S))
# print("R={}".format(R))
# print("T={}".format(T))
# print("Y={}".format(Y))
# print("X={}".format(Answer_X))