Python量子谐振子动画异常:仅显示势能无动画效果
量子谐振子波函数动画问题排查与修复
核心问题与修复步骤
1. 动画更新元素未正确返回
你的animate函数更新了波函数曲线line2,但返回值仅包含势能曲线line1。当blit=True时,Matplotlib只会刷新返回列表中的元素,导致波函数曲线永远不会被渲染。
修复:修改animate的返回值,包含两个曲线对象:
def animate(i): line2.set_data(x_0 , wf_list[i]) return line1, line2
2. 波函数数据格式不符合要求
从wf_list示例来看,每个时刻的波函数是500个单元素数组组成的列表,且为复数类型。而你需要绘制的是$|\Psi|^2$(概率密度),需先处理数据:
- 降维:用
np.squeeze()把单元素数组转换成标量 - 计算概率密度:取复数的模的平方
np.abs(wf)**2
修复:在animate函数中添加数据处理逻辑:
def animate(i): # 处理波函数:降维 + 计算概率密度 wf = np.squeeze(wf_list[i]) prob_density = np.abs(wf)**2 line2.set_data(x_0, prob_density) return line1, line2
3. 重复导入动画模块
代码中重复导入了matplotlib.animation,删除其中一行即可:
# 保留其中一行即可,删除重复的导入语句 from matplotlib import animation # import matplotlib.animation as animation
4. 缺少动画显示语句
如果是脚本运行,最后必须添加plt.show()才能弹出窗口显示动画:
plt.show()
5. 初始化函数优化(可选)
初始化时可以给line2设置空数据,让初始状态更合理:
def init(): line1.set_data(x_0, x_0**2) line2.set_data([], []) return line1, line2
修复后的完整代码
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation x_0 = np.linspace(-10, 10, 500) fig = plt.figure() ax1 = plt.subplot(1, 1, 1) ax1.set_xlim(-10, 10) ax1.set_ylim(0, 6) ax1.set_xlabel('x') ax1.set_ylabel('$|\Psi|^2$') line1, = ax1.plot([], [], 'r-', label='势能') line2, = ax1.plot([], [], 'b-', label='概率密度') ax1.legend() def init(): line1.set_data(x_0, x_0**2) line2.set_data([], []) return line1, line2 def animate(i): wf = np.squeeze(wf_list[i]) prob_density = np.abs(wf)**2 line2.set_data(x_0, prob_density) return line1, line2 # interval设为10更合适,1的话动画速度过快 ani = animation.FuncAnimation(fig, animate, frames=len(wf_list), init_func=init, blit=True, interval=10) plt.show()
内容的提问来源于stack exchange,提问作者rail
相关产品推荐
相关产品推荐

