Python N-body Orbit Simulation

ELI15 Gravitational Theory

We’ll start with the difference between weight and mass. Mass is a measure of the matter that makes up an object, and weight is how much force it feels from gravity. So your weight on the Moon and on Earth are different, but your mass is the same. That’s because the Moon has less gravity dragging you down man.

For a more in depth explanation, I would recommend wikipedia’s page on Orbital Mechanics, or playing Kerbal Space Program

The Program

If you like to skip ahead, the complete code can be found here.

Single Body Calculation

In the theory section, we talked about how this whole thing hinges around calculating the accleration of a single body as a summed acceleration from all other bodies. In python, this can be implemented as follows:

Update velocity and position

With the acceleration known, the next step is to calculate the updated velocity. This is done for all bodies before changing the positions, as we want to keep the time steps synchronized.

Simulating orbits

While we’re running the simulation, the real valuable information we’re finding is the x,y,z locations of our bodies. So to run the simulation, we simply repeat the calculations outlined above for a desired number of steps, and save a history of locations.

Visualizing locations

From this history, here is the simplest visualization I could come up with:

Running a simulation

Output from running the simulation, detailing the motion of The Sun, Venus, Earth, and Mars.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ben Eagan

Ben Eagan

I’m a Software Engineer who practices Human Centred Computing. I’m also a new dad, husband, coffee roaster, mountain biker, who can’t be constrained to 160 char