将月球绕着地球运动以gif形式输出,python代码
时间: 2023-12-24 16:04:54 浏览: 20
以下是Python代码,生成月球绕地球运动的GIF图像:
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 圆周率
pi = np.pi
# 地球半径
R_earth = 6371
# 月球轨道半径
R_moon = 384400
# 初始相位
phi = 0
# 创建图形
fig, ax = plt.subplots()
# 设置坐标轴范围
ax.set_xlim((-R_moon*1.5, R_moon*1.5))
ax.set_ylim((-R_moon*1.5, R_moon*1.5))
# 绘制地球
earth = plt.Circle((0, 0), R_earth, color='blue')
ax.add_artist(earth)
# 绘制月球
moon, = ax.plot([], [], 'ro')
moon.set_markersize(5)
# 动画函数
def animate(i):
global phi
phi += 0.05
x = R_moon * np.cos(phi)
y = R_moon * np.sin(phi)
moon.set_data(x, y)
return moon,
# 创建动画
ani = animation.FuncAnimation(fig, animate, frames=360, interval=50, blit=True)
# 保存动画为GIF图像
ani.save('moon_earth.gif', writer='pillow')
```
运行代码后,会在当前目录下生成一个名为`moon_earth.gif`的GIF图像文件,显示月球绕地球运动的动态效果。