如何制作微分方程求解结果动画?动画不显示问题排查求助
代码问题排查与修复
存在的问题:
- 语法错误:
nat_frec = float(1/(cap*1)行缺少右括号,会直接抛出语法异常无法运行 - 函数名引用错误:自定义的微分方程函数名为
ode,但调用odeint时传入了不存在的变量EDO,运行会报名称错误 - 函数调用问题:定义的函数名为
animation,但注释中的调用语句写的是拼写错误的animacion,且调用语句被注释没有实际执行,自然不会输出任何内容 - 逻辑隐患:
animate的入参名i和外层函数的形参i重名,虽然不会直接报错,但容易引发逻辑混乱,建议修改
修正后可运行的代码:
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint from matplotlib.animation import FuncAnimation def animation(res, cap, l, init_current, fem): neper_frec = float(res / l) # 补全右括号修复语法错误 nat_frec = float(1/(cap*1)) initial_charge = float(cap*fem) interval = np.linspace(0, 10, 600) def ode(y, t): charge, current = y dydt = [current, -neper_frec*current - nat_frec*charge] return dydt y0 = [initial_charge, init_current] # 传入正确的微分方程函数名 sol = odeint(ode, y0, interval) fig, ax = plt.subplots() ax.set(xlim=(0, 10), ylim=(-initial_charge, initial_charge)) line, = ax.plot([], []) y = sol[:, 0] # 修改帧参数名避免重名 def animate(frame): line.set_data(interval[:frame], y[:frame]) return line, anim = FuncAnimation(fig, animate, frames = len(interval) + 1, interval = 20, blit = True) plt.show() # 取消注释、调用正确的函数名 animation(1.4, 1/600, 1.7, 0.5, 8)
内容的提问来源于stack exchange,提问作者Daniel Lopez
相关产品推荐
相关产品推荐

