The cheaper integrator that beat RK4 at orbit 3,188

Contents
Step a four-body solar system forward 4,096 times with classic fourth-order Runge-Kutta and the total energy holds to 0.00041%. Step the exact same system with Velocity-Verlet and the error reaches 0.03052% — seventy-four times worse, even though RK4 did four times as many force evaluations to get there. Keep running. At step 335,064, on revolution 3,188 of the inner planet, RK4 crosses Velocity-Verlet’s flat 0.031% ceiling and never catches it again.
Part 1 of the N-Body in Go series: building a 3D gravitational simulator from scratch in Go, starting with the integrator, scaled units, and the two-way trap of gravitational softening.
This series walks through shaia/n-body, a pure-Go 3D gravitational N-body library, scientific CLI, and decoupled raylib 3D viewer. Every number in this post comes from running Go against commit e010086 on one machine; the measurements live in data/nbody_part1.json, and a self-contained Go program at the end reproduces the core table with zero dependencies.
Across five parts we will follow the whole system from the equations of motion up to a live 60 FPS window:
- This part — symplectic integration, dimensionless units, and gravitational softening.
- Part 2 — the 3D Barnes-Hut octree, the
IsLeaf()bug that dropped seven octants, and why the O(N log N) tree loses to O(N²) at N = 1,000. - Part 3 — lock-free goroutine parallelism that stays bitwise identical to serial code across any worker count, and where Amdahl’s Law steps in.
- Part 4 — hearing 3:2, 2:1, and 4:2:1 orbital resonances with a progressive Hann-windowed FFT, and why a circular orbit makes no sound at all.
- Part 5 — isolating CGO/raylib behind
internal/renderand handing immutable snapshots across goroutines with a singleatomic.Pointer.
How to read this. Where you see a Predict prompt inside a figure, stop and pick an answer before opening it; the result that surprised me most was not how badly Explicit Euler fails, but how little it takes to fix it. All three figures are interactive and draw only numbers produced by Go code against the repository. Boxes marked “safe to skip” carry the derivations; the main prose never depends on them.
What you need to know already: comfortable reading Go, and first-year calculus (derivatives as rates of change, vectors, and Newton’s law of gravity). Symplectic maps, phase-space area, shadow Hamiltonians, and Plummer softening are all built from scratch where they first matter.
1. One force law, four integrators
Every gravitational N-body simulator begins with the same coupled system of ordinary differential equations. Given point masses with positions , velocities , and masses , the net acceleration on body is the sum of pairwise attractions from every other body :
Set and you recover Newton’s inverse-square law exactly; we will keep (gravitational softening) fixed for the first three sections and dissect what it buys and breaks in Section 5. In internal/force/naive.go, the exact all-pairs force computer visits each unordered pair once and applies Newton’s third law so total linear momentum is conserved by construction:
func (n Naive) Accelerations(bodies []body.Body, out []vector.Vec3) {
clear(out)
eps2 := n.Eps * n.Eps
for i := range bodies {
for j := i + 1; j < len(bodies); j++ {
d := bodies[j].Position.Sub(bodies[i].Position)
invDist3 := softenedInvDist3(d.LenSq(), eps2)
out[i] = out[i].Add(d.Scale(n.G * bodies[j].Mass * invDist3))
out[j] = out[j].Add(d.Scale(-n.G * bodies[i].Mass * invDist3))
}
}
}
That function answers one question: given where every body sits right now, what is every body’s acceleration? Advancing the simulation from time to is the job of the integrator.
To test four integrators on equal footing, let us use the repository’s default SolarSystem() preset (internal/scenario/solar_system.go): a central star of mass at the origin and three small planets on eccentric () orbits in the plane:
- Inner (3:2): semi-major axis , mass , Keplerian period (perihelion , aphelion ).
- Outer (3:2): semi-major axis , mass , period .
- Distant: semi-major axis , mass , non-resonant reference planet.
Because the system is isolated and gravity is conservative, two invariants should never change: total mechanical energy (kinetic plus softened gravitational potential energy, here ) and total angular momentum . We step the system 4,096 times at the repository’s pinned defaults (, , ), which spans — roughly 39 revolutions of the inner planet, the exact window the FFT resonance detector in Part 4 needs.
Here are the four integrators we pit against each other:
- Explicit Euler (first-order, 1 force evaluation per step): update position using the old velocity, then update velocity using the old acceleration.
- Symplectic Euler (first-order, 1 force evaluation per step): swap those two lines — update velocity first, then move position with the new velocity.
- Velocity-Verlet (second-order, 1 force evaluation per step — what
internal/integrator/verlet.goactually runs): half-kick velocity, full-drift position, recompute forces at the new position, second half-kick velocity. - Classic RK4 (fourth-order, 4 force evaluations per step): the textbook workhorse of scientific computing, evaluating accelerations at the start, twice at the midpoint, and once at the end of every step.
Before looking at the measured trajectories, take the prediction in the figure below.
Four integrators on the same 3:2 solar system
Measured from SolarSystem() at dt = 0.01, ε = 0.05. Same force law, same initial state.
Before you look: Explicit Euler updates position from old velocity, then updates velocity from acceleration. If you swap those two lines — update velocity first, then position — keeping the exact same dt = 0.01 and the exact same 1 force call per step, what happens to the orbit over 39 revolutions?
Inner (3:2) orbit, first 5 revolutions (XZ)
Total system energy drift ΔE / |E₀| over 4,096 steps
Every point is taken directly from data/nbody_part1.json (measured against github.com/shaia/n-body commit e010086). The dashed ellipse in the left pane is the ideal Keplerian orbit (a = 3.0357, e = 0.12). Notice how Explicit Euler leaves the viewport on its fifth revolution, while Symplectic Euler and Velocity-Verlet stay locked on the ellipse with zero angular-momentum drift.
Look at the numbers from that 4,096-step run:
| Integrator | Force calls / step | Max |ΔE / E₀| | Drift at step 4,096 | Angular-momentum drift | Inner r range (Kepler: 2.67–3.40) |
|---|---|---|---|---|---|
| Explicit Euler | 1 | 73.37140% | +73.37140% | 72.42056% | 2.67 – 22.97 |
| Symplectic Euler | 1 | 0.78955% | −0.34902% | 0.00000% | 2.65 – 3.44 |
| Velocity-Verlet | 1 | 0.03052% | +0.00331% | 0.00000% | 2.67 – 3.41 |
| Classic RK4 | 4 | 0.00041% | −0.00041% | 0.00011% | 2.67 – 3.40 |
Explicit Euler is a catastrophe. Within five revolutions the inner planet has already spiralled off the chart; by step 4,096 it has drifted out to , nearly seven times past its true aphelion, with +73.37% fake energy injected into the system. Even if you cut fourfold to (16,384 steps), Explicit Euler still injects +56.28% energy over the same time span.
Now compare the first two rows. Symplectic Euler is the exact same arithmetic as Explicit Euler — same single force evaluation, same first-order local truncation error — except the two assignment statements sit in the opposite order. That two-line swap collapses peak energy error by nearly two orders of magnitude (from 73.37% to 0.79%) and drops angular-momentum drift from 72.42% to 0.00000% (machine precision).
Splitting the velocity kick in half around the drift gives Velocity-Verlet, still at 1 force evaluation per step, which cuts the peak energy oscillation another 25× to 0.03052% while keeping angular-momentum drift at 0.00000%.
And yet, looking only at 4,096 steps, Classic RK4 appears to win by a mile: 0.00041% energy drift is 74 times smaller than Velocity-Verlet’s 0.03052%. Notice one quiet warning sign in the table, though: for Explicit Euler and RK4, max drift equals final drift, and angular momentum is drifting away from zero. For Symplectic Euler and Velocity-Verlet, final drift is smaller than peak drift, and angular-momentum drift is zero to five decimal places.
2. Why swapping two lines changes everything
The geometry behind Explicit Euler’s failure is simple enough to draw on a napkin. A planet in orbit moves along a curved path that bends inward toward the star. Explicit Euler steps straight along the tangent line at the current position:
Every tangent to a convex curve lies strictly outside the curve. At every step, Explicit Euler pushes the planet slightly farther from the star than the real orbit goes, where gravity is slightly weaker, while carrying the old higher speed outward. Energy climbs monotonically every single step, and nothing ever gives it back.
Now swap the two lines:
This is Symplectic Euler (also called semi-implicit Euler). Look at what changed: you bend the velocity vector inward first, then step along the already-bent velocity. That sounds like a minor bookkeeping tweak, but in phase space — the six-dimensional space of positions and momenta — it changes the topology of the map completely.
By Liouville’s theorem, exact Hamiltonian mechanics preserves volume in phase space: take any small blob of initial conditions and evolve them under Newton’s laws, and the blob stretches and shears into filaments, but its total volume never shrinks and never grows. An integrator that preserves this same phase-space volume (more precisely, the symplectic two-form ) is called a symplectic integrator.
Explicit Euler is not symplectic — on a harmonic oscillator it expands phase-space area by a factor of on every single step, pumping energy in exponentially. Classic RK4 is not symplectic either — on a harmonic oscillator it shrinks phase-space area slightly on every step, acting like a tiny invisible drag force that bleeds orbital energy and angular momentum away forever.
Symplectic Euler is symplectic, and so is Velocity-Verlet (internal/integrator/verlet.go):
func (vv VelocityVerlet) StepInto(bodies []body.Body, dt float64, fc force.ForceComputer, accels []vector.Vec3) {
if len(bodies) == 0 {
return
}
halfDT := 0.5 * dt
for i := range bodies {
bodies[i].Velocity = bodies[i].Velocity.Add(bodies[i].Acceleration.Scale(halfDT))
bodies[i].Position = bodies[i].Position.Add(bodies[i].Velocity.Scale(dt))
}
if len(accels) < len(bodies) {
accels = make([]vector.Vec3, len(bodies))
}
accels = accels[:len(bodies)]
fc.Accelerations(bodies, accels)
for i := range bodies {
bodies[i].Acceleration = accels[i]
bodies[i].Velocity = bodies[i].Velocity.Add(accels[i].Scale(halfDT))
}
}
Look closely at two details in those nineteen lines:
- One force evaluation per step, not two. Because the final half-kick stores
accels[i]back intobodies[i].Acceleration, the next step’s opening half-kick reuses the force computed at the end of the previous step. The only prerequisite is seedingbodies[i].Accelerationonce before step 1 — whichsimulation.Newdoes right before publishing the initial snapshot. - Zero heap allocations in the stepping loop.
StepIntowrites accelerations into a caller-owned scratch slice (s.accels, allocated once insimulation.New), avoiding a fresh[]vector.Vec3allocation on every physics tick.Stepis just a convenience wrapper aroundStepInto. - Time-reversibility and second-order accuracy. Notice the symmetric structure: half-kick, full-drift, half-kick. Reverse every velocity and run a step backward, and you land back at the exact starting state (up to floating-point rounding). That symmetry kills all odd powers of in the local error, lifting Symplectic Euler’s to Velocity-Verlet’s without adding a single extra force evaluation.
3. The crossover at orbit 3,188
If Velocity-Verlet’s energy error is bounded and RK4’s is not, then no matter how small RK4’s per-step drain is, there must be a step where RK4 crosses Velocity-Verlet and falls behind permanently. The only honest question is: when? Is it ten million orbits away, where nobody cares, or close enough to matter in a real simulation?
Let us measure it. Take the exact same SolarSystem() preset at , and run Symplectic Euler, Velocity-Verlet, and Classic RK4 out to 400,000 steps — 3,806 revolutions of the inner planet.
When 1-eval Velocity-Verlet overtakes 4-eval RK4
Switch between the 400,000-step long horizon at dt = 0.01 and the step-size sweep over T = 40.96.
Look at the two curves in the “Long horizon” view:
| Step | Inner orbits | Velocity-Verlet max |ΔE / E₀| | Classic RK4 ΔE / E₀ | Symplectic Euler max |ΔE / E₀| |
|---|---|---|---|---|
| 4,096 | 39.0 | 0.03052% | −0.00041% | 0.78955% |
| 40,000 | 380.6 | 0.03116% | −0.00401% | 0.80753% |
| 160,000 | 1,522.5 | 0.03125% | −0.01552% | 0.80814% |
| 335,064 | 3,188.3 | 0.03125% | −0.03125% | 0.80814% |
| 400,000 | 3,806.2 | 0.03125% | −0.03753% | 0.80814% |
Over a 100× increase in simulation length (from 4,096 to 400,000 steps), Velocity-Verlet’s worst energy excursion rises by 0.00073 percentage points — from 0.03052% to 0.03125% — as planetary alignments slowly precess into slightly deeper perihelia. Classic RK4’s error grows like a ruler: multiply the step count by 10 and the energy lost multiplies by 10 (−0.00041% → −0.00401% → −0.03753%).
At step 335,064 (3,188.3 orbits), RK4 crosses 0.03125% and loses the lead for good — after doing 1,340,256 force evaluations against Velocity-Verlet’s 335,064. And remember why this matters for github.com/shaia/n-body specifically: in interactive MAX mode or -headless runs, a 4-body solar system runs at hundreds of thousands of steps per second, crossing 335,000 steps in under two seconds. Worse, RK4’s secular energy drain slowly shrinks every orbit’s semi-major axis, shifting orbital frequencies over long integrations — the exact thing our FFT resonance detector in Part 4 relies on staying rock-steady.
Now switch the figure above to Step-size scaling (dt = 0.0025 → 0.08 over fixed simulation time ):
| Δt | Steps | Explicit Euler max | Symplectic Euler max | Velocity-Verlet max | Classic RK4 max |
|---|---|---|---|---|---|
| 0.0025 | 16,384 | 56.2833% | 0.1541% | 0.00190% | 0.000000% |
| 0.0050 | 8,192 | 65.1529% | 0.3349% | 0.00759% | 0.000013% |
| 0.0100 | 4,096 | 73.3714% | 0.7896% | 0.03052% | 0.000413% |
| 0.0200 | 2,048 | 82.0549% | 2.1103% | 0.12484% | 0.013157% |
| 0.0400 | 1,024 | 95.2713% | 6.5733% | 0.52992% | 0.436960% |
| 0.0800 | 512 | 118.0125% | 24.1976% | 2.49620% | 2,307.0240% |
Two clean signatures jump out of that sweep:
- Exact second-order scaling for Velocity-Verlet. Halve from
0.01to0.005, and peak energy error drops from0.03052%to0.00759%— a ratio of 4.02×. Halve it again to0.0025, and it drops to0.00190%— a ratio of 4.00×. Because you pay 1 force evaluation per step instead of RK4’s 4, running Velocity-Verlet at still costs half of RK4 and already brings the permanent energy envelope down to 0.0076%. - RK4’s cliff at . Classic RK4 scales as while it is inside its stability region (
0.000013%→0.000413%→0.013157%→0.43696%, roughly 32× per doubling at fixed total time because the number of steps halves while local error grows 32×). Push one more step to0.08, and RK4 flies off the cliff to 2,307% energy error while Velocity-Verlet is still holding a quiet 2.50%.
4. Scaled units: why G = 1.0
Open internal/vector/vector.go and the very first constant is:
const G = 1.0
Not . Why throw away SI units?
In SI, the Sun’s mass is , Earth’s orbital radius is , and a year is . Multiply and you are sitting near ; compute and you are near ; square a small softening radius or add a tiny planet’s perturbation onto a massive star’s potential energy, and you burn exponent range and risk underflow/overflow whenever a test uses extreme ratios. Even when IEEE-754 float64 survives the exponents (it spans ), every magic constant in the program — dt, eps, camera zoom, minNodeSizeFraction, FFT frequency bounds — turns into unreadable scientific notation that has to be retuned for every scenario.
Because Newtonian gravity has no built-in length or mass scale, we are free to pick characteristic units of length , mass , and time such that
In those dimensionless units, , and every scenario in github.com/shaia/n-body lives in clean, order-1 coordinates:
SolarSystem()(internal/scenario/solar_system.go): , planets at , , and , initial velocities , inner orbital period scaled time units (about 105 steps at ), total energy .examples/laplace_421.json: Jupiter at with Io, Europa, and Ganymede in a 4:2:1 Laplace resonance chain at radii , , and . Runningnbody.New+sim.Run(4096)produces energy drift+0.002263%and locks all three resonance pairs (2:1, 2:1, and 4:1).RandomCluster(1000, 42): 1,000 bodies with masses in , initial velocities in , and positions inside .
One design consequence is worth flagging early: pinning , , and a 4,096-sample ring buffer fixes the FFT frequency bin spacing at . SolarSystem()’s inner semi-major axis 3.0357 is not a random number — it was solved backwards from Kepler’s third law so that the inner planet lands squarely on FFT bin 39 and its 3:2 partner on FFT bin 26. We will come back to that coupling in Part 4.
5. Gravitational softening: the two-way trap
Now let us drop the assumption we quietly carried through Sections 1–4: that is just a harmless safety guard against division by zero.
Unsoftened Newtonian gravity has a singularity as two bodies approach . With a fixed timestep , two bodies that pass arbitrarily close experience an arbitrarily huge acceleration, take a giant velocity kick over a single step, and rocket apart with thousands of percent of invented kinetic energy. The standard fix in N-body codes is Plummer softening: replace the separation squared with everywhere, turning each point mass into a tiny smooth sphere of core radius :
Notice two properties of that force law. At large distances (), it approaches Newtonian gravity cleanly with a relative error of . As , instead of blowing up, the force drops smoothly back to zero, peaking at with a strict upper bound:
So softening caps the force — problem solved? Not quite. Softening pulls in two opposite directions, and measuring github.com/shaia/n-body’s own presets exposes both traps immediately.
Softening ε pulls in two opposite directions
Too large breaks the Solar 3:2 resonance; too small breaks CollidingGalaxies at dt = 0.01.
Solar 3:2 frequency error vs ε (2% lock ceiling)
CollidingGalaxies energy drift vs ε (dt = 0.01)
Left: measured Inner (3:2) / Outer (3:2) FFT frequency ratio error after 4,096 steps of SolarSystem(); the dashed line is the detector's 2% lock tolerance. Right: measured final |ΔE / E₀| (log scale) over T = 6.0 of CollidingGalaxies(80, 42) at dt = 0.01. No single ε works for both at the same fixed timestep.
Trap 1: make too large and you break Kepler’s orbits
By Bertrand’s theorem, among all central-force laws in three dimensions, only two produce closed orbits for every bound initial condition: the inverse-square law () and the linear spring (). Plummer softening is neither. The moment , every eccentric orbit stops closing and begins to precess — specifically, retrograde (the perihelion walks backward on every revolution). Worse, because the softening correction scales as , an inner planet feels a stronger weakening of gravity than an outer planet, so its orbital period lengthens more than the outer planet’s and the frequency ratio drifts away from its integer lock.
Here is what nbody.Simulator actually measures on SolarSystem() over 4,096 steps as we dial from up to :
| Softening ε | Inner/Outer FFT ratio | Error vs 3:2 | Perihelion precession | 3:2 resonance locked (< 2%)? |
|---|---|---|---|---|
| 0.000001 | 1.49994 | 0.0042% | −0.31° / orbit | yes |
| 0.05 (default) | 1.49952 | 0.0319% | −0.50° / orbit | yes |
| 0.20 | 1.49316 | 0.4559% | −2.68° / orbit | yes |
| 0.35 | 1.48085 | 1.2768% | −6.99° / orbit | yes |
| 0.50 | 1.46134 | 2.5771% | −13.09° / orbit | no (broken) |
| 1.00 | 1.35627 | 9.5823% | −36.45° / orbit | no (broken) |
At the repository’s default , the ratio is — just 0.032% off exact 3:2, well inside the resonance detector’s 2% tolerance. (Notice the tiny −0.31°/orbit baseline even at : that is the finite- phase error plus mutual planetary perturbation.) By , however, retrograde precession hits −13.09° per orbit and the period ratio has sagged to 1.46134 (2.58% off), breaking the 3:2 lock completely.
Trap 2: make too small for and the core explodes anyway
Now look at the right pane of the figure above — and this is a genuine finding about the repository’s own defaults.
In CollidingGalaxies (internal/scenario/galaxies.go), each galaxy has a massive central core of surrounded by orbiting disk stars, aimed on a grazing merger trajectory. When a star (or the other core!) plunges through the softened core of a mass, the Plummer potential near behaves like a harmonic spring of angular frequency
Velocity-Verlet on a harmonic oscillator is linearly stable only when . Plug in CollidingGalaxies’s core mass and the global defaults , :
For the two cores passing each other (), it is even worse: . Because SolarSystem() never lets a planet come closer than , works beautifully there. On CollidingGalaxies(80, 42) over , where bodies actually enter the core, here is what happens:
| Softening ε | Δt | ω·Δt (core) | Peak acceleration | Max |ΔE / E₀| | Final ΔE / E₀ |
|---|---|---|---|---|---|
| 0.00 | 0.010 | ∞ | 10,778 | 133,313% | +133,312% |
| 0.05 (default) | 0.010 | 15.49 | 16,739 | 79,059% | +79,058% |
| 0.20 | 0.010 | 1.94 | 2,884 | 11,913% | +11,911% |
| 0.50 | 0.010 | 0.49 | 543 | 84.41% | −84.41% |
| 1.00 | 0.010 | 0.17 | 220 | 3.69% | +0.0029% |
| 0.05 | 0.001 | 1.55 (pair: 2.19) | 45,259 | 1,928% | +1,928% |
Look at that last row too: even cutting tenfold to 0.001 at still leaves the two-core pair at , spiking peak acceleration to 45,259 (right up against the theoretical cap ) and energy drift to +1,928%. Only when sits comfortably below 1 — here at , giving — does Velocity-Verlet snap back to its symplectic promise: a temporary 3.69% bump during the closest core encounter that unwinds to +0.0029% once the cores separate.
The lesson is sharp: softening and timestep are not independent knobs. A single global pair cannot serve both a precision resonant solar system (which needs to keep the 3:2 lock) and a galaxy merger (which needs at , or a much smaller , to keep ).
Trap 3: mismatching between force and energy
One smaller engineering invariant belongs right next to this. In internal/simulation/simulation.go, computeEnergy() evaluates gravitational potential energy with the exact same eps as the force solver:
d := bj.Position.Sub(bi.Position)
dist := math.Sqrt(d.LenSq() + eps2)
pe -= vector.G * bi.Mass * bj.Mass / dist
It is tempting to think “softening is only a numerical trick for forces; energy should still be .” Try it and your energy telemetry will lie to you. The softened force is the exact negative gradient of the softened potential , not . In a two-body grazing flyby (two unit masses at impact parameter , , ), the true softened energy stays within 4.53% during closest approach and returns to −0.0016% afterward; measure the exact same trajectory with an unsoftened potential and the telemetry reports a 10,465% phantom energy explosion! That is why nbody.New calls sim.SetSoftening(norm.Softening) immediately and rejects Softening <= 0 with ErrInvalidSoftening.
6. Try it yourself
Everything in Sections 1–3 reduces to one self-contained Go file using only fmt and math. Copy it into integrators.go and run go run integrators.go — no clone, no external packages, under a second on a laptop:
package main
import (
"fmt"
"math"
)
type vec3 struct{ x, y, z float64 }
func (a vec3) add(b vec3) vec3 { return vec3{a.x + b.x, a.y + b.y, a.z + b.z} }
func (a vec3) sub(b vec3) vec3 { return vec3{a.x - b.x, a.y - b.y, a.z - b.z} }
func (a vec3) scale(s float64) vec3 { return vec3{a.x * s, a.y * s, a.z * s} }
func (a vec3) lenSq() float64 { return a.x*a.x + a.y*a.y + a.z*a.z }
func (a vec3) cross(b vec3) vec3 {
return vec3{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x}
}
type body struct {
m float64
p, v, a vec3
}
func solarSystem() []body {
const M = 1000.0
aIn := 3.0357
aOut := aIn * math.Pow(3.0/2.0, 2.0/3.0)
planets := []struct{ a, e, m float64 }{
{aIn, 0.12, 0.005},
{aOut, 0.12, 0.005},
{7.5183, 0.12, 0.004},
}
bs := []body{{m: M}}
for _, pl := range planets {
vp := math.Sqrt(M / pl.a * (1 + pl.e) / (1 - pl.e))
bs = append(bs, body{m: pl.m, p: vec3{x: pl.a * (1 - pl.e)}, v: vec3{z: vp}})
}
return bs
}
func accels(bs []body, eps float64, out []vec3) {
clear(out)
eps2 := eps * eps
for i := range bs {
for j := i + 1; j < len(bs); j++ {
d := bs[j].p.sub(bs[i].p)
r2 := d.lenSq() + eps2
inv3 := 1.0 / (math.Sqrt(r2) * r2)
out[i] = out[i].add(d.scale(bs[j].m * inv3))
out[j] = out[j].add(d.scale(-bs[i].m * inv3))
}
}
}
func energy(bs []body, eps float64) float64 {
var ke, pe float64
eps2 := eps * eps
for i := range bs {
ke += 0.5 * bs[i].m * bs[i].v.lenSq()
for j := i + 1; j < len(bs); j++ {
d := bs[j].p.sub(bs[i].p)
pe -= bs[i].m * bs[j].m / math.Sqrt(d.lenSq()+eps2)
}
}
return ke + pe
}
func angMom(bs []body) vec3 {
var L vec3
for _, b := range bs {
L = L.add(b.p.cross(b.v).scale(b.m))
}
return L
}
func step(kind string, bs []body, dt, eps float64, acc []vec3) {
switch kind {
case "explicit-euler":
accels(bs, eps, acc)
for i := range bs {
bs[i].p = bs[i].p.add(bs[i].v.scale(dt))
bs[i].v = bs[i].v.add(acc[i].scale(dt))
}
case "symplectic-euler":
accels(bs, eps, acc)
for i := range bs {
bs[i].v = bs[i].v.add(acc[i].scale(dt))
bs[i].p = bs[i].p.add(bs[i].v.scale(dt))
}
case "velocity-verlet":
for i := range bs {
bs[i].v = bs[i].v.add(bs[i].a.scale(0.5 * dt))
bs[i].p = bs[i].p.add(bs[i].v.scale(dt))
}
accels(bs, eps, acc)
for i := range bs {
bs[i].a = acc[i]
bs[i].v = bs[i].v.add(acc[i].scale(0.5 * dt))
}
case "rk4":
n := len(bs)
o := append([]body(nil), bs...)
t := make([]body, n)
k1v, k2v, k3v, k4v := make([]vec3, n), make([]vec3, n), make([]vec3, n), make([]vec3, n)
k1x, k2x, k3x, k4x := make([]vec3, n), make([]vec3, n), make([]vec3, n), make([]vec3, n)
accels(o, eps, k1v)
for i := range n {
k1x[i] = o[i].v
t[i] = body{m: o[i].m, p: o[i].p.add(k1x[i].scale(0.5 * dt)), v: o[i].v.add(k1v[i].scale(0.5 * dt))}
}
accels(t, eps, k2v)
for i := range n {
k2x[i] = t[i].v
t[i] = body{m: o[i].m, p: o[i].p.add(k2x[i].scale(0.5 * dt)), v: o[i].v.add(k2v[i].scale(0.5 * dt))}
}
accels(t, eps, k3v)
for i := range n {
k3x[i] = t[i].v
t[i] = body{m: o[i].m, p: o[i].p.add(k3x[i].scale(dt)), v: o[i].v.add(k3v[i].scale(dt))}
}
accels(t, eps, k4v)
for i := range n {
k4x[i] = t[i].v
bs[i].p = o[i].p.add(k1x[i].add(k2x[i].scale(2)).add(k3x[i].scale(2)).add(k4x[i]).scale(dt / 6))
bs[i].v = o[i].v.add(k1v[i].add(k2v[i].scale(2)).add(k3v[i].scale(2)).add(k4v[i]).scale(dt / 6))
}
}
}
func main() {
const dt, eps = 0.01, 0.05
for _, kind := range []string{"explicit-euler", "symplectic-euler", "velocity-verlet", "rk4"} {
bs := solarSystem()
acc := make([]vec3, len(bs))
accels(bs, eps, acc)
for i := range bs {
bs[i].a = acc[i]
}
e0, L0 := energy(bs, eps), angMom(bs)
maxE := 0.0
for range 4096 {
step(kind, bs, dt, eps, acc)
if d := math.Abs((energy(bs, eps) - e0) / math.Abs(e0) * 100); d > maxE {
maxE = d
}
}
finE := (energy(bs, eps) - e0) / math.Abs(e0) * 100
dL := math.Sqrt(angMom(bs).sub(L0).lenSq()/L0.lenSq()) * 100
fmt.Printf("%-16s 4096 steps: max|dE/E0|=%8.5f%% final=%+9.5f%% dL/L0=%.5f%%\n", kind, maxE, finE, dL)
}
vv, rk := solarSystem(), solarSystem()
acc := make([]vec3, len(vv))
accels(vv, eps, acc)
for i := range vv {
vv[i].a = acc[i]
}
e0 := energy(vv, eps)
vvMax, cross := 0.0, 0
for s := 1; s <= 400000; s++ {
step("velocity-verlet", vv, dt, eps, acc)
step("rk4", rk, dt, eps, acc)
if d := math.Abs((energy(vv, eps) - e0) / math.Abs(e0) * 100); d > vvMax {
vvMax = d
}
rkE := math.Abs((energy(rk, eps) - e0) / math.Abs(e0) * 100)
if cross == 0 && rkE > vvMax && s > 1000 {
cross = s
}
}
rkFin := (energy(rk, eps) - e0) / math.Abs(e0) * 100
innerT := 2 * math.Pi * math.Sqrt(math.Pow(3.0357, 3)/1000.0)
fmt.Printf("crossover at step %d (%.1f orbits); at 400k: verlet max=%.5f%% rk4=%+.5f%%\n",
cross, float64(cross)*dt/innerT, vvMax, rkFin)
}
$ go run integrators.go
explicit-euler 4096 steps: max|dE/E0|=73.37140% final=+73.37140% dL/L0=72.42056%
symplectic-euler 4096 steps: max|dE/E0|= 0.78955% final= -0.34902% dL/L0=0.00000%
velocity-verlet 4096 steps: max|dE/E0|= 0.03052% final= +0.00331% dL/L0=0.00000%
rk4 4096 steps: max|dE/E0|= 0.00041% final= -0.00041% dL/L0=0.00011%
crossover at step 335064 (3188.3 orbits); at 400k: verlet max=0.03125% rk4=-0.03753%
Every single number matches the full library run to the last printed digit.
7. What comes next
Our integrator is settled: one force evaluation per step, zero heap allocations on the hot path, zero angular-momentum drift, and an energy envelope that still holds at 0.031% after nearly four thousand orbits.
The bottleneck is now the single line sitting in the middle of StepInto:
fc.Accelerations(bodies, accels)
For four planets, Naive evaluates six pairs per step. For 1,000 stars, it evaluates 499,500 pairs; for 2,000 stars, nearly two million. In Part 2, we replace that double loop with a 3D Barnes-Hut octree — and immediately run into two surprises: a subtle one-line IsLeaf() bug from the original design plan that quietly dropped seven of eight octants, and the uncomfortable fact that at N = 1,000, our brand-new serial octree is actually slower than the naive loop it was built to replace.
Corrections to the repository’s design notes
Checking every claim in PLAN.md against the actual code turned up two places where the original design notes drifted from what was built:
- The bounding box of
RandomCluster.PLAN.md(DL-015) justifieseps = 0.05as “a few percent of the inter-body spacing in an order-1 bounded cube.” Ininternal/scenario/scenario.go,Defaults()actually setsBounds: 100.0(a cube with mean inter-body spacing around 20, soeps = 0.05is roughly 0.25% of the spacing there). InRandomCluster(250, 42), bodies stay more than 5.4 units apart for the first 400 steps, so softening makes essentially zero difference over short cluster runs. - Global softening on
CollidingGalaxies.presets.gohandsCollidingGalaxiesthe sameDefaultOptions()(dt = 0.01,eps = 0.05) used bySolarSystem(). Because each galaxy core carries mass300, that pair puts the core at (and21.9for the core–core encounter), well past Velocity-Verlet’s stability limit of 2 — which is why energy drifts by+79,058%during the merger unlessepsis raised toward1.0ordtis cut below0.0005.
A note on the evidence
Observed. All numbers in this post and in data/nbody_part1.json were measured on 27 November 2026 against shaia/n-body commit e010086 using go1.27.4 windows/amd64 (24 logical CPUs). All pure-Go package tests (internal/body, internal/config, internal/force, internal/integrator, internal/octree, internal/resonance, internal/scenario, internal/simulation, internal/vector, and the root package nbody) passed before measuring. The standalone reducer in Section 6 was extracted directly from the markdown and executed with go run; its output is pasted verbatim.
Analytical, not merely empirical. The softening acceleration peak , the Jacobian determinant , and the harmonic-core stability limit are exact algebraic results; the measured peak accelerations (36.94 vs theoretical 38.49 at , 9.62 vs 9.6225 at , and 45,259 vs 46,188 in CollidingGalaxies) agree with them directly.
What differs from a production astrophysical code. github.com/shaia/n-body uses a single global fixed timestep and a single global softening across every body in a scenario. Production galactic N-body codes (such as GADGET) assign per-particle or block-hierarchical adaptive timesteps and scenario-specific softening lengths so close encounters stay inside without slowing the whole system down.
What I would still change. Give CollidingGalaxies its own default softening (Softening: 1.0 in presets.go, or a smaller DT) rather than inheriting SolarSystem()’s eps = 0.05, so every built-in preset conserves energy out of the box without breaking the 3:2 solar resonance.
The cheaper integrator that beat RK4 at orbit 3,188