波函数Python的Crank Nicolson方法

时间:2019-12-05 01:35:32

标签: python matrix numerical-methods

我正在尝试使用crank nicolson方法在假想时间(时间步长乘以假想单位)传播高斯波包。我为实现这一目的而编写的代码如下所示:

import matplotlib.pyplot as plt #this allows you to plot, and changes the name to plt
import numpy as np #this allows you to do math, and changes the name to np
import math
import scipy.linalg as la

def V(x):
#    k = 1
#    v = k*x**4
    v = 0.25*(x-3)**2+0.15*(x-3)**4
    return v

def Psi(x):
    psi = np.exp(-2*(x-3)**2)
    return psi

#Function for computing integral using trapezoid method 
def TrapInt(y, h):
    trap = [(float(y[ii]) + float(y[ii+1])) for ii in range(0, len(y)-1)]
    return float(h)/2*sum(trap)    

N = 1000
L = 3;
h = 0.01
x = np.arange(0,6,h);
t = np.linspace(0,L,300);
t = 1j*t;
dt = t[1] - t[0]
dx = x[1] - x[0]

A = 1j*dt/(2*dx**2)

pot = V(x)

Q = np.zeros([len(x),len(x)],dtype = complex)
P = np.zeros([len(x),len(x)],dtype = complex)

wave = np.zeros([len(x),len(t)],dtype = complex)
wave[:,0] = Psi(x)

B = (1- 2*A - 1j*dt*pot)

for ii in range(0,len(x)-1):
    Q[ii][ii] = -(B[ii])
    P[ii][ii] = (B[ii])
    Q[ii][ii+1] = (2-A)
    P[ii][ii+1] = A
    if ii >= 1:
        Q[ii][ii-1] = -A
        P[ii][ii-1] = A
plt.plot(wave[:,0])
for ii in range(0,len(t)-1):
    one = np.matmul(P,wave[:,ii])
    wave[:,ii+1] = np.matmul(la.inv(Q),one)

在执行crank nicolson方法的过程中,我似乎找不到任何数学错误;但是,每当我尝试运行此命令时,都会出现错误,指出Q为奇数(无反函数)。我不确定为什么会这样。任何帮助表示赞赏。谢谢

1 个答案:

答案 0 :(得分:1)

您永远不会分配给_method。在某些情况下,零行会产生奇异矩阵。

此外,请勿重复反转矩阵。可能根本不反转它,而是存储它的一些分解信息,以便有效地计算 Q -1 x