# Darts at a Quarter Circle

*Task 1 of 4 · [Monte Carlo Methods](https://gpu.rocks/learn/monte-carlo-methods-9ea19810.md) · GPU.js Learn*

Monte Carlo is statistics as a weapon: throw random darts at a square, and the
*fraction* that lands inside the quarter circle inscribed in it approaches its area —
π/4. No geometry beyond the Pythagorean check `x² + y² ≤ 1`.

The method is embarrassingly parallel: every dart is judged independently, so every dart
gets its own thread. One rule, though — the randomness is made **outside** the
kernel. `xs` and `ys` hold 4,096 seeded dart positions; the kernel's
job is only the verdict. Deterministic data in, deterministic verdicts out — that's what
makes GPU Monte Carlo debuggable.

## Figures

- **throw darts, count hits — the circle’s area falls out of the ratio**

## Goal

**Goal:** make each thread return `1` if its dart
`(xs[x], ys[x])` lands inside the unit quarter circle, else `0`.

## Requirements

- Read this thread's dart: `xs[this.thread.x]` and `ys[this.thread.x]`
- Inside means `x² + y² ≤ 1` — no `Math.sqrt` needed
- Return exactly `1` or `0`, nothing in between

## Hint 1 — skip the square root

The dart is inside when its distance to the origin is ≤ 1 — and distances
compare the same way squared: `x * x + y * y <= 1` is the whole test.

## Hint 2 — the verdict

```js
if (x * x + y * y <= 1) {
  return 1;
}
return 0;
```

— a branch is
fine in a kernel as long as every path returns.

## Same idea elsewhere

Real GPU Monte Carlo keeps the random numbers on-device — CUDA ships cuRAND, and
WebGPU/Metal compute shaders run counter-based generators like Philox per thread — but the
shape is exactly this: one thread, one sample, one verdict.

## Starter code

```js
// 4,096 seeded darts. One thread judges one dart.
const gpu = new GPU({ mode });

const inside = gpu.createKernel(function (xs, ys) {
  const x = xs[this.thread.x];
  const y = ys[this.thread.x];
  // TODO: return 1 if this dart lands inside the unit quarter
  // circle (x² + y² ≤ 1), otherwise 0.
  return 0;
}, { output: [4096] });

const hits = await inside(xs, ys);

let count = 0;
for (let i = 0; i < hits.length; i++) count += hits[i];
console.log(count, 'of 4096 darts hit — π ≈', (4 * count) / 4096);
```

---

Interactive version: https://gpu.rocks/learn/monte-carlo-methods-9ea19810/1

[Next task](https://gpu.rocks/learn/monte-carlo-methods-9ea19810/2.md)
