-
Method 1: rejection sampling: sample uniformly in a cube, then reject points outside the unit sphere.
-
Method 2: polar sampling: use polar coordinates to directly generate points uniformly in the sphere
There are two implementations here. One in JavaScript, one in C. Which method is faster is different depending on the language!
Using Node v14.16.1.
rejection x 14,358,214 ops/sec ±0.73% (91 runs sampled)
polar x 16,253,126 ops/sec ±0.63% (90 runs sampled)
Converted to timing: rejection is 69.6 ns/sample, polar is 61.5 ns/sample.
Rejection sampling takes 14% more time.
Using GCC 10.2.1, with -O3 -ffast-math
.
rejection: 21.1 ns/sample, ±4.3 ns/sample
polar: 32.1 ns/sample, ±0.7 ns/sample
Rejection sampling takes 34% less time.
The JavaScript version does everything at double precision, which may explain the differences.