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

100000

Output

100000 次投点中命中 78749 次,π ≈ 4 × 78749 ÷ 100000 = 3.14996
真实值 Math.PI = 3.141593,绝对误差 0.008367(相对 0.26633%)
命中率:78.749%(理论上 π/4 ≈ 78.539816%)
标准误差量级 1/√N ≈ 0.003162,想多一位小数需要 100 倍点数
随机源:内置 LCG(seed = 42,相同种子结果可复现)
前 10 个点:(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 Carlo估算圆周率pi estimation随机投点种子随机数LCG模拟实验

Related tools