1

I'm making a small 2-D 2-body orbit simulator. With the starting positions being (0,0) and (1,0), I'd expect the two bodies to go back and forth between the two positions, but instead they go rocketing off into space.

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    

I'd expect the x1, x2 to almost 'bounce' between 0 and 1, but instead I get x1 accelerating off to infinity and x2 accelerating to negative infinity.

tgs123
  • 23
  • 3
  • too lazy to go through your code especailly if I see `sin,cos` in gravity integration code which is weird... most likely your problem is that after your bodies get too close the gravity force will go to infinity accelerating them in the other way ... in next iteration the bodies are already too far so gravity is not strong enough to slow your bodies back to zero in a finite space/time ... and all this hapens in first few frames you don't see ... – Spektre Oct 02 '19 at 09:57
  • 2
    You might also have problems with precision ... see [Is it possible to make realistic n-body solar system simulation in matter of size and mass?](https://stackoverflow.com/a/28020934/2521214) for some additional ideas for your project. And you should definately use vector math instead of goniometrics which contribute to the singularities a lot too... no need for `atan2, sin cos` in here – Spektre Oct 02 '19 at 10:01

0 Answers0