import rebound
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# 创建模拟实例
sim = rebound.Simulation()
sim.add(m = 1.0) # 添加太阳,质量设为1.0(单位为太阳质量)
# 添加行星
planets = [
('Mercury', 0.387, 0.206, 0.000333),
('Venus', 0.723, 0.007, 0.002447),
('Earth', 1.000, 0.017, 0.003003),
('Mars', 1.524, 0.094, 0.000935),
('Jupiter', 5.203, 0.049, 0.954),
('Saturn', 9.539, 0.056, 0.286),
('Uranus', 19.18, 0.046, 0.0437),
('Neptune', 30.06, 0.010, 0.0517)
]
# 找到距离太阳最远的行星
farthest_planet_index = np.argmax([a for _, a, _, _ in planets])
farthest_planet = planets[farthest_planet_index][0]
for name, a, e, m in planets:
sim.add(m = m, a = a, e = e)
# 模拟时间设置,进一步增加模拟时间和步数
tmax = 100.0
N = 100
times = np.linspace(0, tmax, N)
# 存储位置数据
x = np.zeros((len(planets)+1, N))
y = np.zeros((len(planets)+1, N))
for i, t in enumerate(times):
sim.integrate(t)
for j, part in enumerate(sim.particles):
x[j, i] = part.x
y[j, i] = part.y
# 创建图形和坐标轴,将范围修改为[-400, 400]
fig, ax = plt.subplots()
ax.set_xlim(-40, 40)
ax.set_ylim(-40, 40)
ax.set_aspect('equal', 'box')
ax.scatter(x[0, 0], y[0, 0], color = 'yellow', s = 200, label = 'Sun')
lines = []
for i in range(1, len(planets)+1):
line, = ax.plot([], [], label = planets[i - 1][0])
lines.append(line)
def init():
for line in lines:
line.set_data([], [])
return lines
def update(frame):
for i, line in enumerate(lines):
line.set_data(x[i + 1, :frame + 1], y[i + 1, :frame + 1])
return lines
ani = FuncAnimation(fig, update, frames = N,
init_func = init, blit = True, interval = 10)
plt.legend()
plt.show()