Building a leapfrog integrator#

Malena Rice (Yale University)

Description: Write a simple N-body integrator in Python using the leapfrog formulation.

Intended Audience: Intermediate undergraduate

tags: N-body integration,functions, modeling

Requirements: numpy, matplotlib

Last Updated: August 22, 2025

Learning Objectives

  1. Implement a simple physical model in Python from scratch.

  2. Demonstrate the importance of resolution settings in numerical simulations.

  3. Visualize the outputs of a model to provide intuition for a system’s behavior.

Introduction#

In this exercise, you will build a Python function that can solve the N-body problem in 2D as a function of time. The acceleration between two bodies in the N-body problem, decomposed into x- and y-components, is given as

\[a_x = \frac{Gm(dx)}{r^3}\]

$\(a_y = \frac{Gm(dy)}{r^3}\)$.

Taking the first step of your N-body integrator#

We will initialize our system with the Sun at coordinate (0,0) and with the Earth at coordinate (0, 1), with distance coordinates given in AU and with the Earth moving in the positive x-direction.

To run our code, we will need to set some initial conditions. To keep the center of mass static in the 2-body problem, we need to conserve momentum between our two bodies:

\[m_1 v_1 + m_2 v_2 = 0\]

The general “kick-drift-kick” form of a leapfrog integrator is formulated as follows:

\[v_{i+1/2} = v_i + a_i \frac{\Delta t}{2}\]
\[x_{i+1} = x_i + v_{i + 1/2} \Delta t \]
\[v_{i+1} = v_{i+1/2} + a_{i+1}\frac{\Delta t}{2} \]

This set of three functions corresponds to one “step” forward in the leapfrog integration routine.

Integrating an orbit#

At this point, you have most of the setup for your numerical integration. The last point that you need to implement is a tracker: a way to save your values when you take more than one time step.

Everything should now be in place to run your leapfrog integrator. In the next exercise, we will run the integrator and visualize its outputs to demonstrate that the integrator is functioning properly.

Sufficiently high resolution in numerical simulations is critical to ensure that the relevant physical processes are captured. In this final exercise, we will show how our integrator’s outputs depend upon the timestep selected.