← Writing

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 θ\theta 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 N=1,000N = 1{,}000 and N=4,000N = 4{,}000. 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 (i,j)(i, j) is visited once — N(N−1)/2N(N - 1)/2 interactions in total, or (N−1)/2(N - 1)/2 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 NN that loop is absurdly fast. At large NN the quadratic wall arrives ruthlessly: doubling NN 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 O(N2)O(N^2) 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 O(N2)O(N^2) to O(Nlog⁡N)O(N \log N).

Before looking at the benchmark sweep across N=100…8,000N = 100 \dots 8{,}000, make your call on the default N=1,000N = 1{,}000 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?

Naive O(N²)
Serial Barnes-Hut
eval cost ratio
octree build

Here is the full measured table on RandomCluster(N, 42) at θ=0.5\theta = 0.5, ε=0.05\varepsilon = 0.05 (medians of five nbody.Benchmark runs):

NNaive O(N²)Serial BHSerial vs NaiveNaive pairs/bodyBH evals/bodyTree nodesBuild allocsRMS error
1000.013 ms0.065 ms0.20×49.562.81452900.729%
2500.082 ms0.267 ms0.31×124.5102.43647280.738%
5000.314 ms0.747 ms0.42×249.5144.97221,4440.793%
1,0001.285 ms2.167 ms0.59×499.5191.31,4772,9540.851%
1,5003.008 ms4.115 ms0.73×749.5221.92,2144,4280.772%
2,0005.369 ms6.483 ms0.83×999.5242.62,9405,8800.678%
3,00012.145 ms11.892 ms1.02×1,499.5275.34,3798,7580.629%
4,00028.278 ms22.328 ms1.27×1,999.5300.65,86311,7260.575%
6,00069.128 ms38.333 ms1.80×2,999.5338.38,91317,8260.522%
8,000117.918 ms55.458 ms2.13×3,999.5366.111,95323,9060.503%

Look closely at the two columns for N=1,000N = 1{,}000 — 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 N=2,000N = 2{,}000 — 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 N=2,000N = 2{,}000 and N=3,000N = 3{,}000 (right around N≈2,800N \approx 2{,}800). 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 XX, YY, and ZZ 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:

  1. 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 by 1.01 so no body sits precariously on an outer face.
  2. Insert each body from the root down. As a body passes through every ancestor node n, we update n’s running mass and centre of mass incrementally:
cnew=Mold cold+mb rbMold+mb,Mnew=Mold+mb. \mathbf{c}_{\text{new}} = \frac{M_{\text{old}} \, \mathbf{c}_{\text{old}} + m_b \, \mathbf{r}_b}{M_{\text{old}} + m_b}, \qquad M_{\text{new}} = M_{\text{old}} + m_b .

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. When n.Bounds.Size <= minSize (root.Size * 1e-9), insert stops splitting and appends to n.Bucket instead (TestCoincidentBodiesNoStackOverflow inserts 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 N=1,000N = 1{,}000, rebuilding the entire 1,477-node tree from scratch takes 0.150 ms — just 7% of the 2.17 ms serial step! Even at N=8,000N = 8{,}000 (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:

sd<θ,s=2⋅Bounds.Size,d=∥cnode−rtarget∥. \frac{s}{d} < \theta, \qquad s = 2 \cdot \text{Bounds.Size}, \qquad d = \|\mathbf{c}_{\text{node}} - \mathbf{r}_{\text{target}}\| .

Here ss is the full edge width of the cubic cell and dd is the distance from the target body to the cell’s centre of mass. The ratio s/ds / d is the angular size (in radians) the cell subtends as seen from the target body:

  • If s/d<θs / d < \theta, 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 θ=0\theta = 0, s/d<0s / d < 0 is never true (both ss and dd 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 θ\theta 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.

0.50
collapsed pseudo-body (s/d < θ) opened internal cell leaf summed directly target body
tree interactions
vs 47 exact pairs
collapsed cells
relative force error

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 θ=0.0…1.5\theta = 0.0 \dots 1.5 on RandomCluster at both N=1,000N = 1{,}000 and N=4,000N = 4{,}000.

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)

Serial BH step time
evals / body
RMS force error
with half-side bug

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 N=1,000N = 1{,}000 (Naive reference during this sweep: ~1.9 ms):

θSerial BHSpeedup vs NaiveVisits / bodyEvals / bodyRMS errorMax errorHalf-side bug RMS
0.019.13 ms0.10×1,477.0999.00.00000%0.00000%0.00000%
0.211.55 ms0.16×863.0648.30.04784%0.36773%0.44154%
0.37.37 ms0.26×546.4431.40.16950%1.71396%1.40095%
0.44.45 ms0.43×343.7276.50.44154%4.11258%2.89170%
0.52.99 ms0.65×235.0191.30.85144%9.29859%5.97822%
0.71.73 ms1.15×121.9100.12.11525%16.60174%19.34442%
1.01.02 ms1.99×57.347.05.97822%77.82577%62.53326%
1.50.70 ms2.81×27.022.125.53127%283.30379%189.78640%

That table explains why θ=0.5\theta = 0.5 (DL-015) is the classic sweet spot: RMS force error stays under 1% (0.85% at N=1,000N = 1{,}000, dropping to 0.58% at N=4,000N = 4{,}000). Push θ\theta to 1.0 and Serial Barnes-Hut beats Naive by 1.99× at N=1,000N = 1{,}000, 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 N=1,000N = 1{,}000 (θ = 0.5):

  • Naive: 1.285 ms across 499,500 pair evaluations = 2.57 ns per pair.
  • Serial Barnes-Hut: 2.167 ms across 191,300 force 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:

  1. No Newton’s third-law symmetry (2× floor). Naive computes the vector d and 1 / (r² + eps²)^(3/2) once per pair (i,j)(i, j) and updates both out[i] and out[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 θ=0\theta = 0 row in Section 3: when Barnes-Hut does exact gravity (999 evals/body = 999,000 total, exactly 2× Naive’s 499,500), it takes 19.13 ms — roughly 15× slower than Naive!
  2. Pointer-chasing across scattered 152-byte heap nodes. Naive walks a flat contiguous []body.Body slice that the hardware prefetcher predicts effortlessly. BarnesHut.traverse chases [8]*Node pointers through 1,477 heap-allocated 152-byte structs, touching 235.0 nodes per body (meaning 43.7 internal-node visits per body do branching and pointer dereferencing without even producing a force term) and recursing on the call stack at every level.
  3. A redundant math.Sqrt on every accepted internal node. Look back at lines 59–63 of internal/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() calls math.Sqrt(d.LenSq()) just to test the opening angle — and on every single internal node that passes (plus every node that fails and recurses!), softenedAccel recomputes d := other.Sub(self) and calls math.Sqrt(d.LenSq() + eps2) a second time! Comparing (2*Size)*(2*Size) < theta*theta*distSq would eliminate the first square root and division from every internal node in the walk.
  4. Per-step heap allocations and GC pressure. Rebuilding the tree allocates 2,954 heap objects per step at N=1,000N = 1{,}000 (23,906 at N=8,000N = 8{,}000): one 152-byte &Node{} and one []body.Body{*b} backing slice per leaf. Even though Build itself only takes 0.150 ms at N=1,000N = 1{,}000, 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 NN 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 N=2,000N = 2{,}000 and N=3,000N = 3{,}000, 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 (7/8)2=49/64≈76.6%(7/8)^2 = 49/64 \approx 76.6\%. 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 θ=0.5\theta = 0.5:

IsLeaf() implementationBodies reachable in leavesDropped bodiesRMS force errorMax force error
Fixed (checks all 8 slots)1,000 / 1,0000 (0.0%)0.8514%9.30%
Buggy (Children[0] == nil)348 / 1,000652 (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 s=2⋅Bounds.Sizes = 2 \cdot \text{Bounds.Size}:

Bounds.Sized<θ  ⟺  2⋅Bounds.Sized<2θ. \frac{\text{Bounds.Size}}{d} < \theta \;\Longleftrightarrow\; \frac{2 \cdot \text{Bounds.Size}}{d} < 2\theta .

Setting --theta 0.5 with the half-side formula is algebraically identical to running the true Barnes-Hut algorithm at θ=1.0\theta = 1.0! Look back at the rightmost column of our Section 3 table:

  • Fixed (2*Size/d) at θ=0.4\theta = 0.4: 276.5 evals/body, 0.44154% RMS error.
  • Half-side (Size/d) at θ=0.2\theta = 0.2: 276.5 evals/body, 0.44154% RMS error.
  • Fixed (2*Size/d) at θ=1.0\theta = 1.0: 47.0 evals/body, 5.97822% RMS error.
  • Half-side (Size/d) at θ=0.5\theta = 0.5: 47.0 evals/body, 5.97822% RMS error.

It looks faster in a naive benchmark — cutting evaluations at θ=0.5\theta = 0.5 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 θ=0\theta = 0, fixed θ=0.5\theta = 0.5, the half-side bug proving it equals fixed θ=1.0\theta = 1.0 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 θ=0\theta = 0 and to hold 0.85% RMS error at θ=0.5\theta = 0.5, yet on a single core it still loses to Naive at the default N=1,000N = 1{,}000 (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 N=1,000N = 1{,}000 from 0.59× (losing) to 2.22× (winning) and N=8,000N = 8{,}000 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:

  1. PLAN.md line 592 (IsLeaf()): checks only n.Children[0] == nil; fixed in internal/octree/octree.go lines 95–102 to check all eight slots.
  2. PLAN.md line 791 (opening-angle criterion): compares n.Bounds.Size/dist < bh.Theta (half-side); fixed in internal/force/barneshut.go line 61 to 2*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 NN-scaling entry is the median of 5 calls to nbody.Benchmark (running 200 steps at N=100N = 100, 60 at N=250N = 250, 20 at N=500N = 500, 10 at N=1,000N = 1{,}000, 5 at N=1,500–4,000N = 1{,}500\text{–}4{,}000, and 3 at N=6,000–8,000N = 6{,}000\text{–}8{,}000). Each θ\theta-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 NN-scaling pass and 2.99 ms (0.65×) during the later θ\theta-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 N=1,000N = 1{,}000:

  1. Compare (2*Size)*(2*Size) < theta*theta*distSq inside traverse to eliminate the redundant math.Sqrt on every internal node.
  2. Replace Bucket []body.Body with an inline single-body slot (falling back to a slice only when Size <= minSize) and allocate Node structs out of a flat reusable []Node arena slice per BarnesHut instance — eliminating all 2,954 per-step heap allocations and packing nodes contiguously in cache.
  3. Pass distSq and d directly into softenedAccel instead of recomputing other.Sub(self) twice on accepted internal nodes.

More