Task 2 of 4
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 π.
partialSums kernel so each of its
256 threads returns the sum of its own 256-element slice of hits, then log
the π estimate.inside) is last task's dart test — leave it as ispartialSums, thread x starts at this.thread.x * 256i = 0…255 and accumulate hits[base + i]4 * total / 65536Thread 0 sums hits[0…255], thread 1 sums hits[256…511],
and so on. The starting offset is this.thread.x * 256.
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.
This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.