The O(N log N) tree that lost to O(N²) at N = 1,000

Contents
At 1,000 bodies and the standard opening angle of 0.5, a 3D Barnes-Hut octree evaluates 191.3 gravitational interactions per body while the naive all-pairs loop evaluates 499.5 pairs per body — 2.6 times fewer force calculations. Time them on one CPU core and the naive loop finishes in 1.29 milliseconds while the octree takes 2.17 milliseconds. The asymptotic winner loses by 41% at the project’s own default problem size, still trails at 2,000 bodies, and does not pull ahead until nearly 3,000.
Part 2 of the N-Body in Go series: building a 3D Barnes-Hut octree from scratch, measuring where O(N log N) really overtakes O(N²), and auditing two silent bugs from the original design plan.
In Part 1 we settled the integrator (VelocityVerlet, one force pass per step, zero heap allocations in the stepping loop) and the softening law. Everything now hinges on one interface call inside StepInto:
type ForceComputer interface {
Accelerations(bodies []body.Body, out []vector.Vec3)
}
This post examines the first two implementations of that interface in shaia/n-body commit e010086: Naive (internal/force/naive.go) and serial BarnesHut (internal/force/barneshut.go), backed by the 3D spatial tree in internal/octree/octree.go. Every timing and error number below lives in data/nbody_part2.json, produced by running nbody.Benchmark and an instrumented mirror of the tree on one machine.
How to read this. Take the Predict prompt in the first figure before expanding it; the gap between operation count and wall time is the spine of this post. The second figure lets you drag over a real 2D projection of 48 bodies and watch cells collapse or open; the third plots the full 3D speed-versus-error trade-off at and . Boxes marked “safe to skip” carry the deeper analysis.
What you need to know already: basic Go (structs, slices, pointers) and Big-O notation. Octrees, centre-of-mass multipoles, and the Barnes-Hut opening-angle test are built from scratch below.
1. The O(N²) wall — and why it is harder to beat than textbooks admit
Naive.Accelerations is twelve lines of arithmetic over a flat slice:
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))
}
}
}
Because gravity obeys Newton’s third law, each unordered pair is visited once — interactions in total, or pairs per body. Every memory read streams sequentially across one contiguous []body.Body array, there are zero heap allocations, and there is one math.Sqrt per pair.
At small that loop is absurdly fast. At large the quadratic wall arrives ruthlessly: doubling quadruples the work, so 8,000 bodies already require 31,996,000 pairwise evaluations per step. Yet Naive is never deleted from the repository. Behind the shared ForceComputer interface (DL-001), it remains our exact correctness oracle: any fast approximate solver must match Naive to float64 tolerance when its approximation parameter is turned off, and stay inside a measured relative-error bound when turned on.
The classic way past is the Barnes-Hut algorithm (Josh Barnes and Piet Hut, Nature 1986). Instead of computing gravity from every distant star individually, group distant stars into a bounding cube and treat the entire cube as a single pseudo-body carrying the cluster’s total mass at its centre of mass. That cuts the asymptotic work from to .
Before looking at the benchmark sweep across , make your call on the default cluster.
Where O(N log N) actually overtakes O(N²)
Median step time on RandomCluster(N, 42) at θ = 0.5, ε = 0.05.
Before you look: at N = 1,000 and θ = 0.5, Serial Barnes-Hut evaluates 191.3 forces per body, while Naive evaluates 499.5 pairs per body — 2.6× fewer interactions. On one CPU core, which solver finishes the step first?
Here is the full measured table on RandomCluster(N, 42) at , (medians of five nbody.Benchmark runs):
| N | Naive O(N²) | Serial BH | Serial vs Naive | Naive pairs/body | BH evals/body | Tree nodes | Build allocs | RMS error |
|---|---|---|---|---|---|---|---|---|
| 100 | 0.013 ms | 0.065 ms | 0.20× | 49.5 | 62.8 | 145 | 290 | 0.729% |
| 250 | 0.082 ms | 0.267 ms | 0.31× | 124.5 | 102.4 | 364 | 728 | 0.738% |
| 500 | 0.314 ms | 0.747 ms | 0.42× | 249.5 | 144.9 | 722 | 1,444 | 0.793% |
| 1,000 | 1.285 ms | 2.167 ms | 0.59× | 499.5 | 191.3 | 1,477 | 2,954 | 0.851% |
| 1,500 | 3.008 ms | 4.115 ms | 0.73× | 749.5 | 221.9 | 2,214 | 4,428 | 0.772% |
| 2,000 | 5.369 ms | 6.483 ms | 0.83× | 999.5 | 242.6 | 2,940 | 5,880 | 0.678% |
| 3,000 | 12.145 ms | 11.892 ms | 1.02× | 1,499.5 | 275.3 | 4,379 | 8,758 | 0.629% |
| 4,000 | 28.278 ms | 22.328 ms | 1.27× | 1,999.5 | 300.6 | 5,863 | 11,726 | 0.575% |
| 6,000 | 69.128 ms | 38.333 ms | 1.80× | 2,999.5 | 338.3 | 8,913 | 17,826 | 0.522% |
| 8,000 | 117.918 ms | 55.458 ms | 2.13× | 3,999.5 | 366.1 | 11,953 | 23,906 | 0.503% |
Look closely at the two columns for — the concrete default body count of RandomCluster (DL-015). Barnes-Hut evaluates 191.3 gravitational interactions per body versus Naive’s 499.5 pairs per body: 2.61 times less physics arithmetic. Yet Naive finishes in 1.285 ms while Serial Barnes-Hut takes 2.167 ms (0.59×). Even at — where Barnes-Hut does 4.1× fewer interactions — Naive still wins (5.37 ms vs 6.48 ms).
The single-core crossover only arrives between and (right around ). Past that point the quadratic slope finally crushes Naive, giving Serial Barnes-Hut 1.27× at 4,000 bodies and 2.13× at 8,000 bodies.
To understand why each tree interaction costs more than four times as much as a naive pair — and to spot two subtle bugs that almost slipped in along the way — let us walk through how the octree is built and traversed.
2. Building the 3D octree from scratch every step
Because the simulation is three-dimensional (DL-012), we partition space with an octree: an axis-aligned cube recursively split along , , and into eight equal child cubes (octants).
Each node in internal/octree/octree.go holds its cubic bounds (centre plus half-side Size), the aggregate mass and centre of mass of everything inside it, either a leaf Bucket of bodies or up to eight child pointers:
type Bounds struct {
Center vector.Vec3
Size float64 // half-side of the cube
}
type Node struct {
Bounds Bounds
Mass float64
CenterOfMass vector.Vec3
Bucket []body.Body
Children [8]*Node
}
Mapping any 3D point p to its child octant 0..7 is a three-bit sign test against the node’s centre — one bit per axis:
func (b Bounds) octant(p vector.Vec3) int {
idx := 0
if p.X >= b.Center.X {
idx |= 1
}
if p.Y >= b.Center.Y {
idx |= 2
}
if p.Z >= b.Center.Z {
idx |= 4
}
return idx
}
Constructing the tree (octree.Build) takes two passes:
- Compute a padded cubic root. Scan all bodies for
[minX, maxX],[minY, maxY],[minZ, maxZ], centre the cube at their midpoint, and take half the longest span multiplied by1.01so no body sits precariously on an outer face. - Insert each body from the root down. As a body passes through every ancestor node
n, we updaten’s running mass and centre of mass incrementally:
When the body reaches a leaf:
- If the leaf is empty, store
n.Bucket = []body.Body{*b}and return. - If the leaf already holds a body, subdivide: clear
n.Bucket, push the existing body down into its child octant, and push the incoming body down into its child octant. - Termination guard (
minNodeSizeFraction = 1e-9): what if two bodies have identical or nearly identical coordinates? Without a floor, subdividing pushes both into the same child octant forever until Go blows the stack. Whenn.Bounds.Size <= minSize(root.Size * 1e-9),insertstops splitting and appends ton.Bucketinstead (TestCoincidentBodiesNoStackOverflowinserts 50 identical bodies at(1, 1, 1)to verify this).
Why rebuild from scratch every step? It is tempting to update the octree incrementally as bodies move. In practice, every body moves on every Velocity-Verlet step, so centres of mass change at every level from leaf to root anyway. Look at our measured Build time in data/nbody_part2.json: at , rebuilding the entire 1,477-node tree from scratch takes 0.150 ms — just 7% of the 2.17 ms serial step! Even at (11,953 nodes), Build is 2.05 ms out of 55.46 ms (3.7%). Keeping Build stateless and full-rebuild also buys something priceless for Part 3: once Build returns, the tree is strictly read-only, so concurrent goroutines can traverse it without a single lock.
3. The opening-angle criterion — and why 3D is harsher than 2D
Once the octree is built, computing the acceleration on a target body target is a single recursive walk (internal/force/barneshut.go):
func (bh BarnesHut) traverse(n *octree.Node, target *body.Body) vector.Vec3 {
if n == nil || n.Mass == 0 {
return vector.Vec3{}
}
var acc vector.Vec3
if n.IsLeaf() {
for _, b := range n.Bucket {
if b.ID == target.ID {
continue
}
acc = acc.Add(bh.softenedAccel(target.Position, b.Position, b.Mass))
}
return acc
}
// Opening-angle criterion s/d < theta using full cell width s = 2*Bounds.Size.
d := n.CenterOfMass.Sub(target.Position)
dist := d.Len()
if dist > 0 && 2*n.Bounds.Size/dist < bh.Theta {
return bh.softenedAccel(target.Position, n.CenterOfMass, n.Mass)
}
for _, child := range n.Children {
acc = acc.Add(bh.traverse(child, target))
}
return acc
}
The whole approximation lives in one inequality:
Here is the full edge width of the cubic cell and is the distance from the target body to the cell’s centre of mass. The ratio is the angular size (in radians) the cell subtends as seen from the target body:
- If , the cell looks small enough from here: collapse the entire subtree into one softened gravity call against
(n.CenterOfMass, n.Mass). - Otherwise, open the cell and recurse into its non-nil children.
- At , is never true (both and are positive), so every internal node opens and every leaf is summed directly. Barnes-Hut degenerates into exact all-pairs gravity (
TestBarnesHutThetaZeroMatchesNaive).
Drag the opening angle below (or click any star to make it the target) to watch cells collapse into teal pseudo-bodies or open into direct green leaves.
Inside one Barnes-Hut traversal (2D slice, 48 bodies)
Drag θ or click any star to make it the target. Far cells collapse into one teal pseudo-body; near cells open into children.
A 2D quadtree illustration built in your browser from the XY projection of the first 48 bodies of RandomCluster(1000, 42) (the 3D octree splits each box into 8 octants instead of 4 quadrants). Notice how toggling the half-side bug (Size/d < θ) immediately collapses nearby cells as if θ had been doubled.
Now let us measure the real 3D speed-versus-accuracy trade-off across on RandomCluster at both and .
The θ trade-off: speed vs relative force error
Measured against the exact Naive oracle on RandomCluster(N, 42). Dashed copper overlays the PLAN.md half-side bug.
Speedup vs Naive O(N²) (1× = break-even)
RMS relative force error vs Naive (log scale)
Every point comes from data/nbody_part2.json. At θ = 0, Barnes-Hut visits every leaf and matches Naive to 0.00000% RMS error. Notice that the half-side bug (Bounds.Size / d < θ) at θ = 0.5 produces the exact same 5.98% error as the fixed code at θ = 1.0.
Look at the measured rows for (Naive reference during this sweep: ~1.9 ms):
| θ | Serial BH | Speedup vs Naive | Visits / body | Evals / body | RMS error | Max error | Half-side bug RMS |
|---|---|---|---|---|---|---|---|
| 0.0 | 19.13 ms | 0.10× | 1,477.0 | 999.0 | 0.00000% | 0.00000% | 0.00000% |
| 0.2 | 11.55 ms | 0.16× | 863.0 | 648.3 | 0.04784% | 0.36773% | 0.44154% |
| 0.3 | 7.37 ms | 0.26× | 546.4 | 431.4 | 0.16950% | 1.71396% | 1.40095% |
| 0.4 | 4.45 ms | 0.43× | 343.7 | 276.5 | 0.44154% | 4.11258% | 2.89170% |
| 0.5 | 2.99 ms | 0.65× | 235.0 | 191.3 | 0.85144% | 9.29859% | 5.97822% |
| 0.7 | 1.73 ms | 1.15× | 121.9 | 100.1 | 2.11525% | 16.60174% | 19.34442% |
| 1.0 | 1.02 ms | 1.99× | 57.3 | 47.0 | 5.97822% | 77.82577% | 62.53326% |
| 1.5 | 0.70 ms | 2.81× | 27.0 | 22.1 | 25.53127% | 283.30379% | 189.78640% |
That table explains why (DL-015) is the classic sweet spot: RMS force error stays under 1% (0.85% at , dropping to 0.58% at ). Push to 1.0 and Serial Barnes-Hut beats Naive by 1.99× at , but RMS force error jumps 7× to 5.98% and the worst body is off by 77.8%! Push to 1.5 and the worst body’s acceleration is off by 283% — pointing in nearly the wrong direction.
4. Four reasons Serial Barnes-Hut pays a 4.4× per-evaluation tax
Now we can answer the mystery from Section 1 with arithmetic instead of guesses.
At (θ = 0.5):
Naive:1.285 msacross499,500pair evaluations = 2.57 ns per pair.Serial Barnes-Hut:2.167 msacross191,300force evaluations = 11.33 ns per force evaluation (4.40× more expensive per evaluation).
Because 191.3 is only 2.61× fewer interactions than 499.5, a 4.40× per-interaction tax guarantees that Serial Barnes-Hut loses (2.61 / 4.40 = 0.59× — matching our measured speedup to two decimal places!). Where does that 4.4× tax come from? Four specific costs in the code:
- No Newton’s third-law symmetry (2× floor).
Naivecomputes the vectordand1 / (r² + eps²)^(3/2)once per pair and updates bothout[i]andout[j]. Barnes-Hut cannot do that: a pseudo-body represents a group of bodies, so each target body walks the tree independently. Look at the row in Section 3: when Barnes-Hut does exact gravity (999evals/body =999,000total, exactly2×Naive’s499,500), it takes 19.13 ms — roughly 15× slower thanNaive! - Pointer-chasing across scattered 152-byte heap nodes.
Naivewalks a flat contiguous[]body.Bodyslice that the hardware prefetcher predicts effortlessly.BarnesHut.traversechases[8]*Nodepointers through 1,477 heap-allocated152-byte structs, touching235.0nodes per body (meaning43.7internal-node visits per body do branching and pointer dereferencing without even producing a force term) and recursing on the call stack at every level. - A redundant
math.Sqrton every accepted internal node. Look back at lines 59–63 ofinternal/force/barneshut.go:d := n.CenterOfMass.Sub(target.Position) dist := d.Len() // sqrt #1 if dist > 0 && 2*n.Bounds.Size/dist < bh.Theta { return bh.softenedAccel(target.Position, n.CenterOfMass, n.Mass) // sqrt #2! }d.Len()callsmath.Sqrt(d.LenSq())just to test the opening angle — and on every single internal node that passes (plus every node that fails and recurses!),softenedAccelrecomputesd := other.Sub(self)and callsmath.Sqrt(d.LenSq() + eps2)a second time! Comparing(2*Size)*(2*Size) < theta*theta*distSqwould eliminate the first square root and division from every internal node in the walk. - Per-step heap allocations and GC pressure. Rebuilding the tree allocates 2,954 heap objects per step at (
23,906at ): one152-byte&Node{}and one[]body.Body{*b}backing slice per leaf. Even thoughBuilditself only takes0.150 msat , those freshly allocated pointers scatter across heap spans and force Go’s garbage collector to scan them between steps.
None of those four taxes breaks the asymptotic curve — as grows, (N - 1)/2 climbs linearly while Barnes-Hut’s evaluations per body crawl logarithmically (191.3 at 1k → 242.6 at 2k → 300.6 at 4k → 366.1 at 8k). Once the interaction-count ratio passes ~4.4× (between and , where 1,499.5 / 275.3 = 5.45×), Serial Barnes-Hut overtakes Naive and never looks back.
5. Two silent bugs caught between PLAN.md and the code
Reading PLAN.md side by side with internal/octree/octree.go and internal/force/barneshut.go turns up two classic spatial-tree bugs that were written into the initial milestone draft (PLAN.md lines 592 and 791) and later fixed in the implementation. Neither causes a crash or a compiler error; both silently corrupt gravity.
Bug 1: IsLeaf() checking only Children[0] == nil
In PLAN.md (Milestone 3, line 592), Node.IsLeaf() was written as:
// Buggy draft from PLAN.md:
func (n *Node) IsLeaf() bool {
return n.Children[0] == nil
}
Why is that fatal? Because childNode allocates children lazily — only for octants that actually receive a body! When a leaf holding one body splits on a second body, the probability that neither body lands in octant 0 (X < cx, Y < cy, Z < cz) is . On more than three-quarters of all splits, Children[0] stays nil while the two bodies sit in octants 1..7.
When a third body arrives at that node, IsLeaf() wrongly returns true, sees len(n.Bucket) == 0, and writes n.Bucket = []body.Body{*b} — turning an internal node back into a leaf and orphaning its entire subtree in octants 1–7! When traverse later walks the tree, it hits if n.IsLeaf() and stops at n.Bucket, never visiting those children at all.
We measured the exact damage on RandomCluster(1000, 42) at :
IsLeaf() implementation | Bodies reachable in leaves | Dropped bodies | RMS force error | Max force error |
|---|---|---|---|---|
| Fixed (checks all 8 slots) | 1,000 / 1,000 | 0 (0.0%) | 0.8514% | 9.30% |
Buggy (Children[0] == nil) | 348 / 1,000 | 652 (65.2%) | 57.82% | 307.47% |
Nearly two-thirds of the entire star cluster vanishes into unreachable octants, yet n.Mass and n.CenterOfMass on the root node still match the full 1,000 bodies (because insert updated them on the way down!). That means TestCenterOfMass would still pass on the buggy tree! Only TestEveryBodyInExactlyOneLeaf and TestBarnesHutThetaZeroMatchesNaive catch it immediately — which is why internal/octree/octree.go now loops over all eight slots and carries a four-line warning comment explaining why.
Bug 2: half-side vs full-side in the opening-angle check
In PLAN.md (line 791), traverse wrote:
// Buggy draft from PLAN.md (Bounds.Size is the HALF-side!):
if dist > 0 && n.Bounds.Size/dist < bh.Theta
Because Bounds.Size stores the half-side of the cube (half := max(...) / 2 * 1.01), dividing Bounds.Size by dist omits a factor of 2 compared to the standard Barnes-Hut width :
Setting --theta 0.5 with the half-side formula is algebraically identical to running the true Barnes-Hut algorithm at ! Look back at the rightmost column of our Section 3 table:
- Fixed (
2*Size/d) at :276.5evals/body, 0.44154% RMS error. - Half-side (
Size/d) at :276.5evals/body, 0.44154% RMS error. - Fixed (
2*Size/d) at :47.0evals/body, 5.97822% RMS error. - Half-side (
Size/d) at :47.0evals/body, 5.97822% RMS error.
It looks faster in a naive benchmark — cutting evaluations at from 191.3 to 47.0 — only because you secretly threw away 7× of force accuracy (jumping from 0.85% to 5.98% RMS error, failing TestBarnesHutModerateThetaWithinBound’s 2% gate!). internal/force/barneshut.go line 61 uses the true full width 2*n.Bounds.Size/dist < bh.Theta.
6. Try it yourself
This standalone Go program (only fmt, math, and math/rand) builds the exact RandomCluster(1000, 42) octree and reproduces all five configurations side by side: exact , fixed , the half-side bug proving it equals fixed to five decimal places, and the Children[0] == nil bug dropping 652 bodies:
package main
import (
"fmt"
"math"
"math/rand"
)
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) len() float64 { return math.Sqrt(a.lenSq()) }
type body struct {
id int
m float64
p vec3
}
type bounds struct {
c vec3
s float64 // half-side
}
func (b bounds) octant(p vec3) int {
idx := 0
if p.x >= b.c.x {
idx |= 1
}
if p.y >= b.c.y {
idx |= 2
}
if p.z >= b.c.z {
idx |= 4
}
return idx
}
func (b bounds) child(idx int) bounds {
h := b.s / 2
dx, dy, dz := -h, -h, -h
if idx&1 != 0 {
dx = h
}
if idx&2 != 0 {
dy = h
}
if idx&4 != 0 {
dz = h
}
return bounds{c: vec3{b.c.x + dx, b.c.y + dy, b.c.z + dz}, s: h}
}
type node struct {
b bounds
m float64
com vec3
bucket []body
ch [8]*node
}
func (n *node) isLeaf(buggy bool) bool {
if buggy {
return n.ch[0] == nil // PLAN.md bug: checks only octant 0
}
for _, c := range n.ch {
if c != nil {
return false
}
}
return true
}
func insert(n *node, b body, minSize float64, buggy bool) {
tm := n.m + b.m
if tm > 0 {
n.com = n.com.scale(n.m).add(b.p.scale(b.m)).scale(1 / tm)
}
n.m = tm
if n.isLeaf(buggy) {
if len(n.bucket) == 0 {
n.bucket = []body{b}
return
}
if n.b.s <= minSize {
n.bucket = append(n.bucket, b)
return
}
old := n.bucket
n.bucket = nil
for _, ob := range old {
putChild(n, ob, minSize, buggy)
}
putChild(n, b, minSize, buggy)
return
}
putChild(n, b, minSize, buggy)
}
func putChild(n *node, b body, minSize float64, buggy bool) {
idx := n.b.octant(b.p)
if n.ch[idx] == nil {
n.ch[idx] = &node{b: n.b.child(idx)}
}
insert(n.ch[idx], b, minSize, buggy)
}
func build(bs []body, buggy bool) *node {
minX, maxX := bs[0].p.x, bs[0].p.x
minY, maxY := bs[0].p.y, bs[0].p.y
minZ, maxZ := bs[0].p.z, bs[0].p.z
for _, b := range bs[1:] {
minX, maxX = min(minX, b.p.x), max(maxX, b.p.x)
minY, maxY = min(minY, b.p.y), max(maxY, b.p.y)
minZ, maxZ = min(minZ, b.p.z), max(maxZ, b.p.z)
}
half := max(maxX-minX, maxY-minY, maxZ-minZ) / 2 * 1.01
root := &node{b: bounds{c: vec3{(minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2}, s: half}}
for _, b := range bs {
insert(root, b, half*1e-9, buggy)
}
return root
}
func countLeaves(n *node, buggy bool) int {
if n == nil {
return 0
}
if n.isLeaf(buggy) {
return len(n.bucket)
}
tot := 0
for _, c := range n.ch {
tot += countLeaves(c, buggy)
}
return tot
}
func accel(d vec3, mass, eps2 float64) vec3 {
r2 := d.lenSq() + eps2
return d.scale(mass / (math.Sqrt(r2) * r2))
}
func traverse(n *node, t body, theta, eps2 float64, halfSide, buggy bool, evals *int) vec3 {
if n == nil || n.m == 0 {
return vec3{}
}
if n.isLeaf(buggy) {
var a vec3
for _, b := range n.bucket {
if b.id != t.id {
a = a.add(accel(b.p.sub(t.p), b.m, eps2))
*evals++
}
}
return a
}
d := n.com.sub(t.p)
dist := d.len()
side := 2 * n.b.s
if halfSide {
side = n.b.s
}
if dist > 0 && side/dist < theta {
*evals++
return accel(d, n.m, eps2)
}
var a vec3
for _, c := range n.ch {
a = a.add(traverse(c, t, theta, eps2, halfSide, buggy, evals))
}
return a
}
func rmsErr(ref, got []vec3) float64 {
var sum float64
for i := range ref {
r := ref[i].sub(got[i]).len() / ref[i].len()
sum += r * r
}
return math.Sqrt(sum/float64(len(ref))) * 100
}
func main() {
rng := rand.New(rand.NewSource(42))
bs := make([]body, 1000)
for i := range bs {
bs[i] = body{
id: i + 1,
p: vec3{(rng.Float64()*2 - 1) * 100, (rng.Float64()*2 - 1) * 100, (rng.Float64()*2 - 1) * 100},
m: 0.5 + rng.Float64()*1.5,
}
// consume 3 velocity draws to match scenario.RandomCluster(1000, 42)
rng.Float64()
rng.Float64()
rng.Float64()
}
const eps2 = 0.05 * 0.05
naive := make([]vec3, len(bs))
for i := range bs {
for j := i + 1; j < len(bs); j++ {
d := bs[j].p.sub(bs[i].p)
naive[i] = naive[i].add(accel(d, bs[j].m, eps2))
naive[j] = naive[j].add(accel(d, -bs[i].m, eps2))
}
}
run := func(label string, theta float64, halfSide, buggy bool) {
root := build(bs, buggy)
got := make([]vec3, len(bs))
evals := 0
for i, b := range bs {
got[i] = traverse(root, b, theta, eps2, halfSide, buggy, &evals)
}
fmt.Printf("%-26s leaves=%4d/1000 evals/body=%5.1f rms_err=%8.5f%%\n",
label, countLeaves(root, buggy), float64(evals)/float64(len(bs)), rmsErr(naive, got))
}
run("fixed, theta=0.0 (exact)", 0.0, false, false)
run("fixed, theta=0.5 (2*Size)", 0.5, false, false)
run("half-side bug (Size/d)", 0.5, true, false)
run("fixed, theta=1.0 (2*Size)", 1.0, false, false)
run("IsLeaf bug (Children[0])", 0.5, false, true)
}
$ go run octree_reducer.go
fixed, theta=0.0 (exact) leaves=1000/1000 evals/body=999.0 rms_err= 0.00000%
fixed, theta=0.5 (2*Size) leaves=1000/1000 evals/body=191.3 rms_err= 0.85144%
half-side bug (Size/d) leaves=1000/1000 evals/body= 47.0 rms_err= 5.97822%
fixed, theta=1.0 (2*Size) leaves=1000/1000 evals/body= 47.0 rms_err= 5.97822%
IsLeaf bug (Children[0]) leaves= 348/1000 evals/body=111.5 rms_err=57.82331%
7. What comes next
Our serial Barnes-Hut tree is verified to match Naive to 0.00000% at and to hold 0.85% RMS error at , yet on a single core it still loses to Naive at the default (2.17 ms vs 1.29 ms).
Remember why we rebuilt the octree from scratch every step: the moment octree.Build returns, the tree is completely immutable, and 93% of the step time sits inside traverse — an embarrassingly parallel read-only walk. In Part 3, we split that traversal across goroutines with zero locks, flip from 0.59× (losing) to 2.22× (winning) and to 18.9×, prove why the parallel output stays bitwise identical to serial code across any worker count, and measure where serial octree.Build hits Amdahl’s Law.
Corrections to PLAN.md
Both bugs dissected in Section 5 still appear in the historical Milestone 3 code diffs in PLAN.md, though both were fixed in the committed Go packages:
PLAN.mdline 592 (IsLeaf()): checks onlyn.Children[0] == nil; fixed ininternal/octree/octree.golines 95–102 to check all eight slots.PLAN.mdline 791 (opening-angle criterion): comparesn.Bounds.Size/dist < bh.Theta(half-side); fixed ininternal/force/barneshut.goline 61 to2*n.Bounds.Size/dist < bh.Theta(full cube edge width).
A note on the evidence
Observed. All timings, node counts, allocation counts, and force errors in this post and in data/nbody_part2.json were measured on 30 November 2026 against shaia/n-body commit e010086 using go1.27.4 windows/amd64 (24 logical CPUs). Each -scaling entry is the median of 5 calls to nbody.Benchmark (running 200 steps at , 60 at , 20 at , 10 at , 5 at , and 3 at ). Each -sweep entry is the median of 3 calls to nbody.Benchmark. Notice that N = 1,000, θ = 0.5 read 2.17 ms (0.59×) during the -scaling pass and 2.99 ms (0.65×) during the later -sweep pass as CPU boost clocks settled under sustained load; within each pass, Naive and BarnesHut ran back-to-back inside the same nbody.Benchmark call, so every speedup ratio compares measurements taken seconds apart.
What the 2D figure illustrates. nbody-octree-walk builds a 2D quadtree in JavaScript over the XY projection of the first 48 bodies of RandomCluster(1000, 42) so the cell boundaries and opening-angle test can be seen directly on a flat screen. All quantitative 3D claims come exclusively from the Go measurements in data/nbody_part2.json.
What I would still change. Three straightforward optimisations would slash Serial Barnes-Hut’s 4.4× per-evaluation tax and pull the serial crossover well below :
- Compare
(2*Size)*(2*Size) < theta*theta*distSqinsidetraverseto eliminate the redundantmath.Sqrton every internal node. - Replace
Bucket []body.Bodywith an inline single-body slot (falling back to a slice only whenSize <= minSize) and allocateNodestructs out of a flat reusable[]Nodearena slice perBarnesHutinstance — eliminating all2,954per-step heap allocations and packing nodes contiguously in cache. - Pass
distSqandddirectly intosoftenedAccelinstead of recomputingother.Sub(self)twice on accepted internal nodes.
The O(N log N) tree that lost to O(N²) at N = 1,000