Algorithms
Force calculation algorithms explained.
Force Calculation Algorithms
Three algorithms are provided for computing N-body forces, each with different time/space complexity trade-offs.
layout: docs lang: en
Algorithm Comparison
| Algorithm | Time | Space | Best For |
|---|---|---|---|
| Direct N² | O(N²) | O(1) | Small systems, validation |
| Barnes-Hut | O(N log N) | O(N) | Large gravitational systems |
| Spatial Hash | O(N) | O(N) | Short-range forces |
layout: docs lang: en
Direct N² Algorithm
Overview
Computes exact pairwise gravitational forces between all particles.
1
2
3
4
5
6
for each particle i:
for each particle j (j â i):
r = position[j] - position[i]
dist = |r| + softening
force = G * mass[i] * mass[j] / dist²
acceleration[i] += force * r / dist
Time Complexity
- Force calculation: O(N²)
- Memory: O(1) per thread (uses shared memory caching)
When to Use
- Particle count < 10,000
- Accuracy validation
- Benchmarking other methods
layout: docs lang: en
Barnes-Hut Algorithm
Overview
Uses hierarchical octree to approximate forces from distant particle groups.
Key Idea
If a group of particles is sufficiently far away (θ < s/d), treat them as a single point mass at their center of mass.
1
2
3
4
5
6
7
8
9
10
âââââââââââââââââ
â Root â
â Center of â θ = s/d determines approximation
â Mass â
âââââââââŦââââââââ
ââââââââââŧâââââââââ
ââââââ´âââââ ââ´â âââââââââ´âââââââ
â NW â â â â NE â Leaf = single particle
â (4) â â â â (4) â Node = center of mass
âââââââââââ âââ ââââââââââââââââ
Time Complexity
- Tree construction: O(N log N)
- Force calculation: O(N log N)
- Memory: O(N)
θ Parameter
| θ Value | Accuracy | Speed |
|---|---|---|
| 0.3 | High | Slower |
| 0.5 | Medium | Balanced |
| 0.7 | Lower | Faster |
When to Use
- Large-scale gravitational simulation
- Particle count > 10,000
- Long-range forces
layout: docs lang: en
Spatial Hash Algorithm
Overview
Partitions 3D space into uniform grid cells, only computing forces between particles in neighboring cells.
1
2
3
4
5
6
7
8
9
âââââââŦââââââŦââââââ
â â â â â â Particle only checks
âââââââŧââââââŧâââââ⤠neighbors in adjacent
â â â â â cells (including diagonal)
âââââââŧââââââŧââââââ¤
â â â â â â
âââââââ´ââââââ´ââââââ
â
Cutoff radius
Time Complexity
- Grid construction: O(N)
- Force calculation: O(N) per particle (constant neighbors)
- Memory: O(N)
When to Use
- Short-range forces (cutoff radius)
- Molecular dynamics
- Very large particle counts (> 100K)
layout: docs lang: en
Algorithm Selection Guide
1
2
3
4
5
6
Particle Count â Algorithm
ââââââââââââââââŧâââââââââââââ
< 10K â Direct N²
10K - 100K â Barnes-Hut
> 100K â Spatial Hash (short-range)
> 100K â Barnes-Hut (long-range)
Runtime switching:
1
2
3
4
./nbody_sim
# Press 1: Direct N²
# Press 2: Barnes-Hut
# Press 3: Spatial Hash