请修改以下代码使之输出正确的波函数随x的变化曲线图像import numpy as np import matplotlib.pyplot as plt def square_poten_well(x, N): L = 2 V0 = -1 mat_V = np.zeros((N, N)) for i, xx in enumerate(x): if abs(xx) <= L/2: mat_V[i, i] = V0 return mat_V def phi(k, x, N): return [np.exp(1.0j*k*x[i]) for i in range(N)] def Green_func(k, x, xp, N): G = np.ones((N, N), dtype=complex) for i in range(N): G[i, :] = [-1.0j / k * np.exp(1.0j*k*np.abs(x[i]-xp[j])) for j in range(N)] return G def change_of_var(node, weight, a, b, N): nop = [(b-a) * node[i] / 2.0 + (a+b) / 2.0 for i in range(N)] wp = [(b-a) / 2.0 * weight[i] for i in range(N)] return nop, wp # 计算波函数 def calc_wave_func(k, x, N): mat_V = square_poten_well(x, N) G = Green_func(k, x, x, N) G_inv = np.linalg.inv(G - mat_V) phi_k = phi(k, x, N) return np.dot(G_inv, phi_k) N = 298 a = -1.5 b = 1.5 k_vec = np.arange(0.5, 6.0) x, w = np.polynomial.legendre.leggauss(N) x = (b-a)/2.0*x + (b+a)/2.0 w = (b-a)/2.0*w # 绘制波函数变化图像 fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(12, 8)) for i, k in enumerate(k_vec): wave_func = np.abs(np.array(calc_wave_func(k, x, N))) ax = axes[i//3, i%3] ax.plot(x, wave_func) ax.set_title(f'Wave function for k={k:.1f}') ax.set_xlabel('x') ax.set_ylabel('|psi(x)|') plt.tight_layout() plt.show():
时间: 2023-11-25 21:06:54 浏览: 116
python 对任意数据和曲线进行拟合并求出函数表达式的三种解决方案
可以将代码修改为以下形式:
```python
import numpy as np
import matplotlib.pyplot as plt
def square_poten_well(x, N):
L = 2
V0 = -1
mat_V = np.zeros((N, N))
for i, xx in enumerate(x):
if abs(xx) <= L/2:
mat_V[i, i] = V0
return mat_V
def phi(k, x, N):
return [np.exp(1.0j*k*x[i]) for i in range(N)]
def Green_func(k, x, xp, N):
G = np.ones((N, N), dtype=complex)
for i in range(N):
G[i, :] = [-1.0j / k * np.exp(1.0j*k*np.abs(x[i]-xp[j])) for j in range(N)]
return G
def change_of_var(node, weight, a, b, N):
nop = [(b-a) * node[i] / 2.0 + (a+b) / 2.0 for i in range(N)]
wp = [(b-a) / 2.0 * weight[i] for i in range(N)]
return nop, wp
# 计算波函数
def calc_wave_func(k, x, N):
mat_V = square_poten_well(x, N)
G = Green_func(k, x, x, N)
G_inv = np.linalg.inv(G - mat_V)
phi_k = phi(k, x, N)
return np.dot(G_inv, phi_k)
N = 298
a = -1.5
b = 1.5
k_vec = np.arange(0.5, 6.0)
x, w = np.polynomial.legendre.leggauss(N)
x = (b-a)/2.0*x + (b+a)/2.0
w = (b-a)/2.0*w
# 绘制波函数变化图像
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(12, 8))
for i, k in enumerate(k_vec):
wave_func = np.abs(np.array(calc_wave_func(k, x, N)))
ax = axes[i//3, i%3]
ax.plot(x, wave_func)
ax.set_title(f'Wave function for k={k:.1f}')
ax.set_xlabel('x')
ax.set_ylabel('|psi(x)|')
plt.tight_layout()
plt.show()
```
这里主要是将最后的冒号去掉,并且确保代码中没有语法错误。另外,还可以调整一下 `figsize` 的大小,使得图像更清晰。
阅读全文