You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何制作微分方程求解结果动画?动画不显示问题排查求助

代码问题排查与修复

存在的问题:

  • 语法错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 03:39:02