Create Your Own N-body Simulation (With Python)

Philip Mocz
The Startup
Published in
4 min readSep 13, 2020

--

For today’s recreational coding exercise, we will look at the gravitational N-body problem. We will create a simulation of a dynamical system of particles interacting with each other gravitationally. Such a system may describe the orbits of planets in the Solar System or stars in our Galaxy.

You may find the accompanying Python code on github. (And if you prefer to use Matlab, please see my Matlab version of the article)

But first, below is a gif of what running our simulation looks like:

N-body simulation

Force Calculation

We will assume a system of N point particles, indexed by i=1,…,N. Each particle has a:

  • mass mᵢ,
  • position rᵢ = [ xᵢ, yᵢ, zᵢ ] ,
  • velocity v = [ vx, vyᵢ, vzᵢ ]

Each particle feels the gravitational attraction of all the other particles according to Newton’s law of universal gravitation (the famous ‘inverse square-law’). That is, each particle feels an acceleration:

where G=6.67×10^-11 m³/kg/s² is the Gravitational constant.

We can write a Python function to perform the calculation on an input N×3 matrix of positions:

--

--

Philip Mocz
The Startup

Computational Physicist. Sharing intro tutorials on creating your own computer simulations! Harvard ’12 (A.B), ’17 (PhD). Connect with me @PMocz