使用Matplotlib FuncAnimation实现原子模型电子旋转:斜向电子运动异常求助
问题原因与解决方法
你的斜向电子无法沿轨道循环的核心问题是旋转计算逻辑错误:你给斜向电子写了自定义的偏移叠加公式,而非使用统一的圆周运动公式,导致电子偏离了半径为shell2的圆周轨道。所有电子的圆周运动都应该基于原点为中心的极坐标转直角坐标逻辑实现,这样才能保证它们在同一轨道同步旋转。
修改后的完整代码
import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() ax.set_aspect(1) plt.grid(False) plt.axis('off') # 轨道半径 shell_radius = 14.5 # 设置坐标轴范围,确保轨道完整显示 ax.set_xlim(-shell_radius - 1, shell_radius + 1) ax.set_ylim(-shell_radius - 1, shell_radius + 1) # 绘制电子轨道(圆周) theta = np.linspace(0, 2*np.pi, 100) ax.plot(shell_radius*np.cos(theta), shell_radius*np.sin(theta), color='k') # 定义8个电子的初始角度(单位:度),按东、西、北、南、东北、西北、西南、东南顺序 initial_angles_deg = [0, 180, 90, 270, 45, 135, 225, 315] # 转成弧度 initial_angles_rad = np.radians(initial_angles_deg) # 初始化所有电子的绘图对象 electrons = [] colors = ['r', 'k', 'k', 'r', 'r', 'k', 'k', 'r'] # 对应电子的颜色 for angle, color in zip(initial_angles_rad, colors): x = shell_radius * np.cos(angle) y = shell_radius * np.sin(angle) electron, = ax.plot(x, y, marker='.', markersize=20, color=color) electrons.append(electron) def update(rotation_angle): # 遍历每个电子,更新其位置:初始角度 + 旋转角度 for electron, init_angle in zip(electrons, initial_angles_rad): current_angle = init_angle + rotation_angle x = shell_radius * np.cos(current_angle) y = shell_radius * np.sin(current_angle) electron.set_data(x, y) return electrons # 生成动画,帧为0到2π的弧度,共100帧 anim = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 100), repeat=True) plt.show()
关键改动与解释
- 统一圆周运动公式:所有电子的位置都通过
shell_radius * cos(初始角度 + 旋转角度)和shell_radius * sin(初始角度 + 旋转角度)计算,这是标准的极坐标转直角坐标公式,确保电子始终在半径为shell_radius的圆周上运动。 - 初始角度标准化:直接用
np.radians()将角度从度转成弧度,替代手动计算45*0.0174533,代码更直观且不易出错。 - 批量管理电子:用列表存储所有电子的绘图对象和初始角度,避免重复代码,后续新增/修改电子更方便。
- 修正坐标轴范围:一开始设置的
-4到4远小于轨道半径14.5,导致轨道和电子被裁剪,现在直接基于轨道半径设置范围,确保完整显示。 - 移除冗余代码:删除了未使用的
createList函数和多余的变量定义,简化代码结构。
内容的提问来源于stack exchange,提问作者Devinder Arora
相关产品推荐
相关产品推荐

