matplotlib 在保存动画时抛出 ZeroDivisionError

matplotlib throwing ZeroDivisionError when saving an animation

我有以下 Python 脚本(删除了一些不相关的位):

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

#constants
xRange = 50
dx = 0.1
tMax = 50
dt = 0.1
c=1

#init
Nx = int(xRange/dx)
Nt = int(tMax/dt)
t=0
uVals = np.zeros( (Nt, Nx) )
xVals = np.arange(int(-xRange/2), int(xRange/2), dx)

#code that calculates uVals, as a function of x and t

fig, ax = plt.subplots()
line, = ax.plot(xVals, uVals[0])

def animate(i):
    line.set_ydata(uVals[i])
    return line,

ani = animation.FuncAnimation(
    fig, animate, interval=int(dx/1000), blit=True, frames=Nt, save_count=50)
ani.save("temp.mp4")
plt.show()

当我 运行 没有 ani.save() 这段代码时,它会显示预期的动画(PDE 的模拟)。但是,当我尝试使用 ani.save("temp.mp4") 保存动画时,出现以下错误:

line 45, in <module>
    ani.save("temp.mp4")
  File "C:\Python36\lib\site-packages\matplotlib\animation.py", line 1077, in save
    fps = 1000. / self._interval
ZeroDivisionError: float division by zero

我不知道为什么会这样,也找不到关于这个问题的任何信息。有人能帮忙吗?

您的间隔为零。 int(dx/1000)=0dx<1。也许 int(np.ceil(dx/1000)) 进行四舍五入以避免设置零间隔?我不确定你的意图是什么。