This project implements and compares three classical numerical integrators for ordinary differential equations (ODEs). Each method is implemented in both Python (using JAX for JIT compilation) and C++, and applied to a different test problem chosen to highlight the method's strengths and limitations.
| Method | Equation | Exact solution |
|---|---|---|
| Predictor-Corrector (Euler-Trapezoidal) | ||
| Leapfrog (Störmer–Verlet) | ||
| Runge-Kutta 4 (RK4) |
Results and plots are in results.ipynb.
- uv — Python package and project manager
- Python 3.12+
uv syncThis creates a virtual environment and installs all dependencies (jax, matplotlib, ipykernel, ipython).
uv run jupyter notebook results.ipynbOr open it in VS Code with the Jupyter extension — select the .venv kernel created by uv.
uv run python simple_harmonic_oscillator_predictor_corrector.py
uv run python leap_frog_method.py
uv run python simple_ode_RK4.pyg++ -O2 -o sho simple_harmonic_oscillator_predictor_corrector.cpp && ./sho
g++ -O2 -o leapfrog leap_frog_method.cpp && ./leapfrog
g++ -O2 -o rk4 simple_ode_RK4.cpp && ./rk4The simple harmonic oscillator
with
Given
Predict (explicit Euler):
Correct (trapezoidal rule):
-
2nd-order accurate: global error
$\mathcal{O}(h^2)$ . -
Not symplectic: the total energy
$E = \frac{1}{2}(x^2 + v^2)$ drifts over long integrations. A spiral in the phase portrait ($v$ vs$x$ ) reveals this drift — a perfect integrator traces a closed circle.
Scalar ODE
The leapfrog advances the solution using a half-step:
-
2nd-order accurate: global error
$\mathcal{O}(h^2)$ . - Symplectic and time-reversible: conserves a modified energy exactly, so there is no secular drift — ideal for long-time Hamiltonian integration.
Scalar ODE
Each step computes four slope estimates:
and advances with the weighted average:
-
4th-order accurate: local truncation error
$\mathcal{O}(h^5)$ , global error$\mathcal{O}(h^4)$ . - Not symplectic: unsuitable for very long Hamiltonian integrations, but highly accurate for short-to-medium intervals.
-
(a) Integrate with
$h_1 = 0.2$ . -
(b) Integrate with
$h_2 = 0.1$ (halved step) and compare accuracy. -
(c, d) Compute an adaptive step size
$h_0$ via a Richardson-style estimate. Since RK4 error scales as$h^4$ , the step needed to achieve tolerance$\varepsilon = 10^{-7}$ is:
Part (d) confirms