Quan Nguyen《Advanced Python Programming》粒子模拟代码运行异常求助
粒子圆周运动模拟代码运行问题
问题背景
我正在阅读Quan Nguyen所著的《Advanced Python Programming》第二版,书中的粒子圆周运动模拟代码无法正常运行。使用Windows 11系统、Python 3.8.12版本,在VSCode中运行无任何反应,JupyterLab运行时出现警告。
原代码
# %load simul.py from matplotlib import pyplot as plt from matplotlib import animation from random import uniform import timeit import os os.system('cls' if os.name == 'nt' else 'clear') class Particle: __slots__ = ("x", "y", "ang_speed") def __init__(self, x, y, ang_speed): self.x = x self.y = y self.ang_speed = ang_speed class ParticleSimulator: def __init__(self, particles): self.particles = particles def evolve(self, dt): timestep = 0.00001 nsteps = int(dt / timestep) for i in range(nsteps): for p in self.particles: norm = (p.x ** 2 + p.y ** 2) ** 0.5 v_x = (-p.y) / norm v_y = p.x / norm d_x = timestep * p.ang_speed * v_x d_y = timestep * p.ang_speed * v_y p.x += d_x p.y += d_y def visualize(simulator): X = [p.x for p in simulator.particles] Y = [p.y for p in simulator.particles] fig = plt.figure() ax = plt.subplot(111, aspect="equal") (line,) = ax.plot(X, Y, "ro") # Axis limits plt.xlim(-1, 1) plt.ylim(-1, 1) # It will be run when the animation starts def init(): line.set_data([], []) return (line,) def animate(i): # We let the particle evolve for 0.1 time units simulator.evolve(0.01) X = [p.x for p in simulator.particles] Y = [p.y for p in simulator.particles] line.set_data(X, Y) return (line,) # Call the animate function each 10 ms anim = animation.FuncAnimation(fig, animate, init_func=init, blit=True, interval=10) plt.show() def test_visualize(): particles = [ Particle(0.3, 0.5, +1), Particle(0.0, -0.5, -1), Particle(-0.1, -0.4, +3), ] simulator = ParticleSimulator(particles) visualize(simulator) if __name__ == "__main__": test_visualize()
JupyterLab中的警告信息
C:\Users\ephra\AppData\Local\Temp\ipykernel_18360\3786700959.py:71: UserWarning: frames=None which we can infer the length of, did not pass an explicit *save_count* and passed cache_frame_data=True. To avoid a possibly unbounded cache, frame data caching has been disabled. To suppress this warning either pass `cache_frame_data=False` or `save_count=MAX_FRAMES`. anim = animation.FuncAnimation(fig, animate, init_func=init, blit=True, interval=10)
问题解决方法
1. VSCode无反应问题
VSCode中动画窗口无法弹出,通常是matplotlib后端配置问题。可以在代码开头添加以下代码指定交互式后端:
import matplotlib # 选择系统支持的后端,比如TkAgg或QtAgg matplotlib.use('TkAgg')
如果系统缺少对应后端依赖(比如Tkinter),需要先安装相关组件。另外,也可以在VSCode的Python扩展设置中,将Matplotlib后端设置为"Interactive"。
2. JupyterLab警告问题
警告是因为FuncAnimation未指定save_count或cache_frame_data参数,新版本matplotlib为避免无限缓存触发提示。修改FuncAnimation调用,添加任意一个参数即可消除警告:
# 方式一:指定save_count anim = animation.FuncAnimation(fig, animate, init_func=init, blit=True, interval=10, save_count=100) # 方式二:关闭缓存 anim = animation.FuncAnimation(fig, animate, init_func=init, blit=True, interval=10, cache_frame_data=False)
额外优化
原代码中evolve函数的嵌套循环效率较低,可通过向量化运算优化,但这不是导致运行失败的原因,仅影响动画流畅度。
内容的提问来源于stack exchange,提问作者ezyman
相关产品推荐
相关产品推荐

