Physics · Python · NumPy · Numerical Methods

N-Body Simulator

A N-Body Simulator, using naive, Barnes-Hut, and improved Barnes-Hut methods, built with Numpy and Matplotlib. Fully exposed simulation settings (softening, BH parameter, number of bodies), and crucial metrics (total energy, number of forces)

Method: Barnes-Hut Status: Complete for now
Interactive Notebook on Github, hosted by Binder

What it does

This is another simulation, this time incorporating a bit more of my previous competitive programming history. The Barnes-Hut algorithm is quite easy to understand - effectively deciding if a mass distribution ought to be represented by its monopole moment or not, making it an interesting and reasonably accessible application of treecoding. Additionally, this kind of simulation takes quite a bit of tuning in terms of softening and opening parameter.

Results

I generally test with a 100-body system, which does strain my system quite a bit. Python's significant overhead for recursion unfortunately means that only at the n=800 or so bound does the Barnes-Hut method actually become more efficient than naive simulation. Additionally, due to the density with which my masses are generally spread, the Barnes-Hut algorithm is less suited - close approaches means energy loss, and denser distributions means more nodes have to be opened, decreasing its efficiency. However, sparse distributions are probably uninteresting to watch.

Animation of a 100-body system with naive simulation

Naive Simulation

A baseline to test our Barnes-Hut on. The total energy doesn't noticeably change at all, which is the sanity check for a good simulation. Total forces is 4 * (n-1)^2, thus scaling quadratically with the number of bodies.

Animation of the same seed with basic Barnes-Hut

Base Barnes-Hut

Base Barnes-Hut works great in the far-field approximation, but when close approaches happen, bad fluctuations in energy occur. Note the acceleration in the change in energy as the bodies move closer. Also note the number of forces is significantly less than the naive simulation. Faster sim, but worse accuracy - unacceptably so in this case of many close approaches.

Animation of the improved Barnes-Hut

Modified Barnes-Hut

Changes can be made to basic Barnes-Hut to allow it to handle situations such as these better, like revising the node opening condition. The energy loss is much better and over long periods stabilizes to a few percent of the initial, but the number of forces is greater than that of the basic Barnes-Hut, though less than that of the naive simulation.

The derivation and code

The full notebook with the derivations in LaTeX, and the actual simulation code is embedded below.

Open the notebook in a new tab →

← Back to all projects