Gravity Simulator

This is a gravity simulator I have written in python using the library VPython/Glowscript. This project was inspired by an exercise my math teacher gave us where we were supposed to simulate the moon’s orbit around the earth in excel using differential equations.

Luckily there exists better tools for this, like python in conjunction with VPython where you get both vectors and graphics. So no need for splitting the vectors in an X-part and an Y-part, that is really convenient actually. My first intention was to just write the earth-moon simulation but then I thought: “Why not do the entire solar system instead”. And so I did, the Sun, the eight planets and Pluto (you will forever be a planet to me) all dancing together in a cosmic dance. Futhermore, I chose to use the Euler method for integration because it is easy to implement and it is the one most people are familiar with. This simulation won’t be near accurate enough to simulate the actual solar system anyway (for example relativity is not accounted for and the timestep is too big) so the inaccuracy doesn’t bother me. I just want to see some planets dance… and throw in a black hole later. I have also chosen to use other units then the SI-units: distance is measured in AU (average distance between earth and the sun), time is measured in days and mass in solar masses. This is because then the computer doesn’t have to handle such large numbers and hence it consumes less memory. A consequence of this is that G, the gravitational constant changes it’s values from the familiar 6.67e-11 to 2.959e-04. The size of the planets are scaled up by a factor of 1000 to make them visible. Otherwise are all the distances correct. The initial positions and velocities are real data from June 2018 from here. Watch it and have fun!

The source code can be found on Glowscript here (click “View this program” to see the source code)

The simulation with a black hole can be found here (click “Run this program” in the upper left corner to start it)

A tutorial on how to code this yourself will be coming in the future. I the meanwhile if you’re interested, I have written comments in the code that may be helpful.

Remember, you can always count on your best friend, the calculator!

A heads up: running this simulation can drain quite a lot of power so if you’re on a laptop, I recommend that you have your charger plugged in while running this.

Controls:

  • Zoom: scroll
  • Pan: Hold SHIFT and drag with left mouse button
  • Rotate: Hold and drag right mouse button

Thanks to @marsater for ideas and feedback for this project.