Sitemap

Member-only story

Python in Astrophysics: Creating an N-Body Simulation

11 min readMar 30, 2025
Photo: Rhett Allain. Finding the gravitational force between two objects.

How do you know what happens when two galaxies collide? There are a few options here. The first is to just look into the sky and find different galaxies that are at some point of the collision process. Another option would be to just wait and watch (but you will be waiting for a very long time). Finally, you could model a collision.

Modeling the interaction between two galaxies is no small feat. Each galaxy can contain more than a billion stars and all of these stars have gravitational interactions with other stars. But still, the idea isn’t too bad. I just need to use the gravitational forces between all the stars (in both galaxies) to find out how the stars move.

This is what we call the n-body problem. It’s not just used for galaxies — but you can use it for any system containing lots of elements that all interact with each other (including particles in a gas).

I’m going to build this in python (and so can you) but let me make an important point. This is an educational exercise. This is not a professional n-body simulator. I’m going to do this from the most basic principles and try to use very little programming tricks.

The Three Body Problem

Before getting too deep — let’s just think about the case of three masses interacting (it’s…

--

--

Rhett Allain
Rhett Allain

Written by Rhett Allain

Physics faculty, science blogger of all things geek. Technical Consultant for CBS MacGyver and MythBusters. WIRED blogger.

Responses (2)