Some Background on N-body Simulations (warning: math!)
Within a gravity simulation composed of bodies, the magnitude of the force acting on each body , is determined by Newton’s law of universal gravitation:
where is the gravitational constant, is the mass of body , is the mass of body , and is the distance vector from to .
In the case of gravity simulations, the forces due to gravity get exceedingly large as bodies get closer to each other (due to the inverse-square law nature of the gravitational force), and hence bodies tend to rapidly accelerate and zoom off when they seemingly “collide”. To compensate for this, a softening length has been applied in the gravity calculation to prevent bodies from zipping off into the abyss when they get near each-other. Also, has been set to 1 for simplicity in NBodyJS.
We can then use Newton’s second law to solve for the acceleration, and then numerically integrate it to get the positions and velocities of all bodies. In Kotlin, the code to compute the acceleration due to gravity looks like this:
To compute the positions and velocities of all of the bodies, NBodyJS utilizes the Velocity Verlet method of numerical integration. Verlet integration is a second-order method, which offers more stability than simpler, first order solutions such as Euler’s method, yet at no significant additional computational cost.
For the algorithm to work, first you need to specify the initial conditions of the simulation; namely the initial positions and velocities of all the bodies at some start time . Then, the Velocity Verlet algorithm consists of the following steps:
- Calculate the acceleration of each body due to gravity (or whatever force(s) you want) at time , using Newton’s laws.
Calculate the position of each body at time (where is a small time step), using the approximation
- Calculate the acceleration , again using Newton’s laws and the forces in play.
Calculate the velocity using the approximation
In Kotlin, the integration code is extremely simple:
This algorithm is executed every time you take a time step, . Since every body exerts a force on every other body, computing the accelerations is done in time.
There are more efficient, yet similarly accurate algorithms out there, so feel free to implement your own version if you feel like experimenting! Also, note that this method can be used to integrate Newton’s laws for nearly any force(s), not just gravity!
Subscribe via RSS