simulation - 试图制作一个简单的二维 2 体轨道模拟器,但一切都在飞向太空?
问题描述
我正在制作一个小型二维二维轨道模拟器。起始位置为 (0,0) 和 (1,0),我希望这两个物体在这两个位置之间来回移动,但它们会飞向太空。
import numpy
import pandas
import matplotlib.pyplot as plt
import math
# variables right here
m1 = 1
m2 = 1
x1 = 0
y1 = 0
x2 = 1
y2 = 0
vx1 = 0
vy1 = 0
vx2 = 0
vy2 = 0
t = 0
dt = 0.01
G = 10
ax1 = 0
ay1 = 0
ax2 = 0
ay2 = 0
r2 = 0
#a = Gm/r^2
#a = Gm/((x2-x1)^2 + (y2-y1)^2)
#tan theta = (y2-y1)/(x2-x1)
#theta = arctan(dy/dx)
#ax = a cos arctan dy/dx
#ay = a sin arctan dy/dx
for t in range(0, 100):
# just the r^2 calculation so I don't have to add it a bunch of times
r2 = (x2 - x1)**2 + (y2 - y1)**2
# quick calculation of theta, just for debugging
theta = math.atan((y2 - y1) / (x2 - x1))
# calculate the accelerations
if x1 > x2:
ax1 = -1 * math.cos(numpy.arctan2(y2 - y1, x2 - x1)) * G * m2 / r2
else:
ax1 = 1 * math.cos(numpy.arctan2(y2 - y1, x2 - x1)) * G * m2 / r2
if y1 > y2:
ay1 = -1 * math.sin(numpy.arctan2(y2 - y1, x2 - x1)) * G * m2 / r2
else:
ay1 = 1 * math.sin(numpy.arctan2(y2 - y1, x2 - x1)) * G * m2 / r2
if x1 > x2:
ax2 = 1 * math.cos(numpy.arctan2(y2 - y1, x2 - x1)) * G * m1 / r2
else:
ax2 = -1 * math.cos(numpy.arctan2(y2 - y1, x2 - x1)) * G * m1 / r2
if y1 > y2:
ay2 = 1 * math.sin(numpy.arctan2(y2 - y1, x2 - x1)) * G * m1 / r2
else:
ay2 = -1 * math.sin(numpy.arctan2(y2 - y1, x2 - x1)) * G * m1 / r2
# now change the velocities
vx1 = vx1 + (ax1 * dt)
vy1 = vy1 + (ay1 * dt)
vx2 = vx2 + (ax2 * dt)
vy2 = vy2 + (ay2 * dt)
# now the positions
x1 = x1 + (vx1 * dt)
y1 = y1 + (vy1 * dt)
x2 = x2 + (vx2 * dt)
y2 = y2 + (vy2 * dt)
# change t
t = t + dt
print x1, x2
我希望 x1、x2 在 0 和 1 之间几乎“反弹”,但相反,我让 x1 加速到无穷大,而 x2 加速到负无穷大。
解决方案
推荐阅读
- python - 在新函数中调用前一个函数
- html - 我应该使用哪些工具来获得网站所有权?
- python - 根据外生数组值更改数据帧行
- python - 如何在 Pycharm 上成功加载 matplotlib
- python - 在目录中创建文件
- flutter - Flutter:在日历上自定义颜色
- javascript - 如何在 PHP/Javascript 中转义双引号、双引号内、单引号内?
- android - Coroutinescope 启动但数据未更新
- android - 协程解释
- android-studio - Android Studio 无法找到 adb & 只能使用 skd gphone x86 作为 AVD