我正在尝试制作地球绕太阳轨道的动画。
该代码在不引入matplotlib动画功能并显示围绕太阳的地球路径的情况下效果很好,但是当尝试对其进行动画处理时,该代码变得混乱并最终输出错误,我搜索了一些示例,但没有找到适合我的示例。< / p>
import numpy as np
import matplotlib.pyplot as plt
# Storing Coordinate Data
x_11list = []
x_12list = []
x_21list = []
x_22list = []
# Constants
G = 6.67408e-11 # m^3 kg^-1 s^-2
t = 0.0 # s
dt = 0.01*24*60*60 # s
# Sun Parameters
# mass
m_1 = 1.989e30 # kg
# position
x_11 = 0
x_12 = 0
x_13 = 0
# velocity
v_11 = 0
v_12 = 0
v_13 = 0
# Earth Parameters
# mass
m_2 = 5.972e24 # kg
# position
x_21 = 1.5e11 # m
x_22 = 0
x_23 = 0
# velocity
v_21 = 0
v_22 = 30000 # m/s
v_23 = 0
while t < 377*24*60*60:
# Distance
r_12 = np.sqrt((x_21-x_11)**2 + (x_22-x_12)**2 + (v_23-v_13)**2) # m
# Newton's Second Law of Motion
# Force 12
Fx_11 = (G*m_1*m_2*(x_21-x_11))/r_12**3
Fx_12 = (G*m_1*m_2*(x_22-x_12))/r_12**3
Fx_13 = (G*m_1*m_2*(x_23-x_13))/r_12**3
# Force 21
Fx_21 = -(G*m_1*m_2*(x_21-x_11))/r_12**3
Fx_22 = -(G*m_1*m_2*(x_22-x_12))/r_12**3
Fx_23 = -(G*m_1*m_2*(x_23-x_13))/r_12**3
# Euler Method
# Sun
v_11 += (Fx_11*dt)/m_1
v_12 += (Fx_12*dt)/m_1
v_13 += (Fx_13*dt)/m_1
x_11 += v_11*dt
x_12 += v_12*dt
x_13 += v_13*dt
# Earth
v_21 += (Fx_21*dt)/m_2
v_22 += (Fx_22*dt)/m_2
v_23 += (Fx_23*dt)/m_2
x_21 += v_21*dt
x_22 += v_22*dt
x_23 += v_23*dt
t += dt
x_11list.append(x_11)
x_12list.append(x_12)
x_21list.append(x_21)
x_22list.append(x_22)
# Vizualisation
plt.figure(figsize=(10,10))
plt.plot(x_11list, x_12list, linewidth=2.0, label="Sun", color="darkorange")
plt.plot(x_21list, x_22list, linewidth=2.0, label="Earth", color="royalblue")
plt.xlabel(r"$x(m)$")
plt.ylabel(r"$y(m)$")
plt.title("Numerical Simulation of Newton's Law of Universal Gravitation")
plt.legend()
plt.grid(True)
plt.show()
输出:
答案 0 :(得分:0)
您可以使用celluloid,但是代价之一是计算效率低下。
首先要导入赛璐oid并构造相机。
from celluloid import Camera
fig = plt.figure(figsize=(10, 10))
camera = Camera(fig)
plt.xlabel(r"$x(m)$")
plt.ylabel(r"$y(m)$")
plt.title("Numerical Simulation of Newton's Law of Universal Gravitation")
只需在for循环和“捕捉”图片的底部绘制散点图即可。
plt.scatter(x_11, x_12, s=300, color='darkorange')
plt.scatter(x_21, x_22, s=200, color='royalblue')
camera.snap()
for循环完成后,保存动画。
camera.animate().save('orbit.mp4')
请注意,您可能需要增加dt
,否则将花费很长时间。我将其保留为添加图例的练习。