Task 2 of 4

Reduce 65,536 Hits to π

Last task summed the verdicts with a JavaScript loop — fine for 4,096 darts, wasteful for 65,536 and absurd for a billion. The GPU answer is a parallel reduction: don't ship every verdict home, ship partial sums. A second kernel with 256 threads gives each thread its own 256-verdict slice to total, collapsing 65,536 numbers to 256 in one launch.

Thread t owns the slice starting at t * 256 — a statically bounded for loop walks it. JavaScript then folds the 256 partials into the final count, and 4 × hits / 65536 is your π.

Goal: complete the partialSums kernel so each of its 256 threads returns the sum of its own 256-element slice of hits, then log the π estimate.

Requirements

Hint 1 — who sums what

Thread 0 sums hits[0…255], thread 1 sums hits[256…511], and so on. The starting offset is this.thread.x * 256.

Hint 2 — the loop
const base = this.thread.x * 256;
let sum = 0;
for (let i = 0; i < 256; i++) {
  sum += hits[base + i];
}
return sum;

The bound is a literal, so gpu.js can unroll it safely.

Same idea elsewhere

Reduction is the fundamental pattern of GPU computing — CUDA has warp shuffles and the CUB library for it, Metal has SIMD-group reductions, WebGPU builds them from workgroup shared memory. Chunked partial sums like yours are always the first rung.

All tasks in Monte Carlo Methods

  1. Darts at a Quarter Circle
  2. Reduce 65,536 Hits to π
  3. Integrate the Un-integrable
  4. Price an Option

This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.