Skip to content
UniKit

Monte Carlo pi estimator

Throw N random points into the unit square and estimate pi as 4 × the fraction inside the quarter circle. The random source is injectable — the default is a seeded LCG — so the same seed reproduces the same estimate, with absolute and relative error plus the 1/√N scale.

Runs in your browserEvery computation happens in your browser — your data never leaves this device.

Points to throw (N)

Estimate

Error scales as roughly 1/√N.

Enter the number of points to run the simulation

Points: 0 · Inside: 0 · Estimated π: 0

What this tool does

  • Classroom demos: watch accuracy creep up as √N from 1000 to a million points.
  • Reproducibility checks: the same seed always yields the same estimate and sample sequence.
  • Micro-benchmarking: push N to a million and compare loop performance across languages.

Example

Input

10000

Output

10000 random points, 7798 inside the quarter circle: π ≈ 4 × 7798 ÷ 10000 = 3.1192
True value Math.PI = 3.141593, absolute error 0.022393 (relative 0.712791%)
Hit rate: 77.98% (theoretical π/4 ≈ 78.539816%)
Standard error scale 1/√N ≈ 0.01; one more decimal needs 100× the points
Random source: built-in LCG (seed = 42; the same seed reproduces the same result)
First 10 points: (0.252345, 0.088125)✓ (0.577281, 0.222554)✓ (0.37566, 0.025664)✓ (0.447281, 0.11846)✓ (0.873814, 0.994634)× (0.853203, 0.499677)✓ (0.642001, 0.861456)× (0.59647, 0.09075)✓ (0.14021, 0.950088)✓ (0.924555, 0.889469)×

With seed 42 and 10000 points the estimate is 3.1192, off by 0.022 — normal for the 1/√N error scale.

Frequently asked questions

Why is the result so far from 3.14159?

Monte Carlo error scales as 1/√N: about ±0.01 at 10000 points, ±0.003 at 100000 and ±0.001 at a million. Every extra correct decimal costs 100× the points, which is why series methods beat it — and why it is such a good teaching example.

Does the same seed give the same answer?

Yes, exactly. The default is a bespoke LCG (a = 1664525, c = 1013904223, m = 2³²) whose state comes from the seed, so the point sequence, hit count and estimate all reproduce. Change 42 to 7 for a different run.

Can I supply my own random source?

Yes — the function accepts `random?: () => number`. The browser page can pass Math.random and tests can pass any deterministic sequence. The page uses the seeded LCG by default so refreshes stay consistent.

What is the maximum number of points?

One million. Beyond that the tab stutters because every point is computed on the main thread; use a local script or a Web Worker for more.

Why is the hit rate π/4?

The quarter circle has area π/4 and the unit square has area 1, so uniformly thrown points land inside with probability π/4 — hence 4 × hit rate ≈ π.

Keywords:Monte Carlopi estimationLCG

Related tools