在下面的函数中,如果我使用
np.linalg.inv
当Nx
,Nt
变大时,函数似乎要花很长时间。在我的头脑中,我知道我应该使用稀疏矩阵,它在scipy中(我以前从未使用过),但是我真的很难将M
转换为稀疏矩阵,找到它的逆矩阵,然后将它转换回for循环的numpy数组。在
如果有人能帮忙,我会非常感激的!谢谢!在
def BTCS(phiOld, c, Nx, Nt):
#Initiate phi for the for loop
phi = phiOld.copy()
#Crate the matrix M for the BTCS scheme
M = np.zeros((Nx, Nx))
for i in range(Nx):
M[i,(i-1)%Nx] = -c/2
M[i,i] = 1
M[i,(i+1)%Nx] = c/2
#Take the inverse of M so as to have phi(n+1) = M^(-1) * phi(n)
M_inv = np.linalg.inv(M)
#Loop over all time steps
for it in range(Nt):
#Loop over space (excluding end points)
for ix in range(1,Nx-1):
phi[ix] = M_inv.dot(phiOld)[ix]
#Compute boundary values using periodic boundary conditions
phi[0] = M_inv.dot(phiOld)[0]
phi[Nx-1] = phi[0]
#Update old time value
phiOld = phi.copy()
return phi
目前没有回答
相关问题 更多 >
编程相关推荐