首页 > 解决方案 > 如何在 Python 中求解一个几乎是三对角矩阵?家庭作业

问题描述

这是我要解决的矩阵

我应该找到不同的温度节点。

    import numpy as np
 
## Tri Diagonal Matrix Algorithm(a.k.a Thomas algorithm) solver
def TDMAsolver(a, b, c, d):
 
    nf = len(d) # number of equations
    ac, bc, cc, dc = (x.astype(float) for x in (a, b, c, d)) # copy arrays & cast to floats
    for it in range(1, nf):
        mc = ac[it-1]/bc[it-1]
        bc[it] = bc[it] - mc*cc[it-1]
        dc[it] = dc[it] - mc*dc[it-1]
 
    xc = bc
    xc[-1] = dc[-1]/bc[-1]
 
    for il in range(nf-2, -1, -1):
        xc[il] = (dc[il]-cc[il]*xc[il+1])/bc[il]
 
    return xc
 
a = np.array([1,1,1,1,-62500])
b = np.array([1,-0.136,-0.136,-0.136,-0.136,77500]) # main diagonal
c = np.array([0,1,1,1,1])
d = np.array([1600,78.9,78.9,78.9,78.9,12300000]) # right side of equation
 
x = TDMAsolver(a,b,c,d) # pass in same order
 
print(x)
 
A = np.diag(b,0) + np.diag(a,-1) + np.diag(c,1)
x = np.linalg.solve(A,d)
print(x)

这就是我所拥有的。

[ 1600. 871.54649514 -1402.56967666  -983.39597117
  1347.72782458  1245.58695531]

这是我的输出

   ([[1600.        ],
   [1099.27474358],
   [ 920.27399177],
   [ 856.78887848],
   [ 835.68455321],
   [ 832.64883323]])

我有点想要的输出。

标签: pythonarraysnumpy

解决方案


推荐阅读