Golang Simulation of the N-Body Problem

Here is a small toy program I used to start learning the Go language. It simulates orbital motion of small bodies around a large central body. It uses the pixel 2D game library to visualize the simulation. The program has three modes:

  1. Random mode where you can generate a bunch of random planetoids around a central body in circular orbits
  2. Random mode with planetoids all of which have moonlets
  3. Simulation of the inner solar system

This program is a toy only. I made no effort to ensure total system energy is preserved and the integration method used is step wise addition at 1 second intervals. In an effort to make the sim scale a bit better, the acceleration on each of the bodies in the sim is calculated in a goroutine. My hope was to turn the O(n^2) performance into something a bit better. Thanks to the raw speed of the Go language, this sim runs pretty fast. It can simulate 1 week of world time for 41 bodies in a few seconds (YMMV).

To try this out, check out the code from the git repo at N-Body Problem Simulation Code Repository . Then follow these steps:

  1. cd ./nbody-go
  2. Install pre-requisites for faiface/pixel go 2D graphics library -- I've run this on Mac OS X and Linux, tried to run it on a Raspberry Pi 4, but the library support is lacking.
  3. go build
  4. ./nbody-go random -d 512x512

See the README on github.

	nbody-go [-hPC -d<dimensions> -s=<spt> -p=<pf> -r=<df> -M=<magFact> -n=<numBodies> -m=<numMoons>] MODE
Run N-Body simulation in mode MODE
  MODE        mode of the simulation, one of random, moons, solar
  -h --help
	-d=<dimensions>, --dimensions=<dimensions>  dimensions of screen in pixels [default: 1024x1024]
	-P        Start paused
	-C        Use plain white circle as planet graphic instead of random ones in moons and random MODE
	-s=<spt>  Seconds of world time to calculate per UI tick
	-p=<pf>   Perturbation factor for random world generation [default: 0.2]
	-r=<df>   Distance factor for random world generation [default: 1.0]
	-M=<magFact>   For high DPI screens, scale up window by this amount [default: 1.0]
	-n=<numBodies>, --number=<numBodies>  Number of bodies to start [default: 60]
	-m=<numMoons>, --moons=<numMoons>     Number of moons per body [default: 3]