在 matplotlib 中绘制行星(彗星)运动和开始

Plotting planet(comet) movement arund start in matplotlib

我正在尝试在 matplotlib 中创建轨迹图以显示行星(彗星或任何有质量的物体)如何围绕恒星(太阳)移动。在我的上下文中,假设太阳在位置 (0, 0)。不幸的是,我的计算或代码或两者都有问题,因此我无法得到正确的最终结果。

下面的代码产生了这个 这显然是错误的。我试过 google 和代码,但仍然无法实现预期的情节。 预期的结果应该是

这些是我使用的公式。

import matplotlib.pyplot as plt
from math import cos, sin, hypot
# constants
G = 6.67
dt = 0.005
# planet
planet_m = 5.97
planet_x = 1
planet_y = 0
# star
star_m = 1.98
star_x = 0
star_y = 0
# velocities
vx = 0
vy = 8
# 
dx = 0
dy = 0
F = 0

t = 0
fxl = []
fyl = []
for i in range(1, 50):
    t += i * dt
    dx += (star_x-planet_x)
    dy += (star_y-planet_y)
    d = hypot(dx, dy)# the same as sqrt(dx**2 + dy**2)
    F += G * planet_x * star_m / (d**2)

    fx = cos(dx) * -F
    fy = sin(dy) * -F
    vx += fx / planet_m * t
    vy += fy / planet_m * t
    planet_x += vx * dt
    planet_y += vy * dt
    fyl.append(fx)
    fxl.append(fy)
    print(f'Position: {planet_x} {planet_y}')
    print(f'Velocities: {vx} {vy}')


plt.plot(star_x, star_y, 'yo', fxl, fyl, '-')
plt.grid()
plt.show()

好吧,我认为您的代码中发生了很多奇怪的事情。我试图以最小的方式修复它,但仍有很大的改进空间:

import matplotlib.pyplot as plt
from math import cos, sin, hypot
# constants
G = 6.67
dt = 0.0001
# planet
planet_m = 5.97
planet_x = 1
planet_y = 0
# star
star_m = 1.98
star_x = 0
star_y = 0
# velocities
vx = 0
vy = 1

pos_x = []
pos_y = []
for i in range(1, 100000):
    dx = (star_x-planet_x)
    dy = (star_y-planet_y)
    d = hypot(dx, dy)
    F = G * star_m / (d**2)

    fx = F * dx / d
    fy = F * dy / d
    vx += fx / planet_m * dt
    vy += fy / planet_m * dt

    planet_x += vx * dt
    planet_y += vy * dt
    pos_x.append(planet_x)
    pos_y.append(planet_y)

plt.plot(star_x, star_y, 'yo', pos_x, pos_y, '-')
plt.show()