09 Jun 2023

Simulating the Three-Body Problem in Python

I then introduced a third sphere, and to my astonishment, the situation changed completely. Like I said, any geometric figure turns into numbers in the depths of my mind. The sphereless, one-sphere, and two-sphere universes all showed up as a single equation or a few equations, like a few lonesome leaves in late fall. But this third sphere gave “emptiness” life. The three spheres, given initial movements, went through complex, seemingly never-repeating movements. The descriptive equations rained down in a thunderstorm without end.

(Taken from The Three-Body Problem by Cixin Liu)

I created a program to simulate the three-body problem - a problem of taking the initial positions and velocities of three point masses and calculating their motion. No solution exists for this problem, which is why the pattern that comes out of simulating this problem at random positions and velocities is different every time.

Simulation

The Simulation

The equation for the force between two masses (m1 and m2) due to gravity is given by:

$F = G × \frac{m_{1}m_{2}}{R^{2}}$

Knowing the masses of the object, we can calculate the acceleration of the object.

$F = m × a$

We can then calculate the velocity of the object.

$v = u + a × t$ where t is a small interval of time and u is the previous value of velocity.

I’ve stored the values of force, velocity and position as 3x1 numpy arrays to allow me to use vector math. To run the simulation, I used pygame.

The Result

You can play around with the simulation too by running main.py with Python as long as you have numpy and pygame installed.

That’s all for now.

You can find the code here.