Skip to main content

Learn · Monte Carlo Pi

Estimating pi with Monte Carlo

Throw darts at random into a square with a circle drawn inside it. The fraction that land inside the circle is the ratio of their areas — which happens to be π/4. Multiply by four and you have an estimate of π built from nothing but random numbers. Throw a few, throw a lot, and watch the estimate settle.

Cyan darts landed inside the circle, pink ones outside.

0
total darts
0
inside circle
π estimate
abs error vs π

Estimate vs number of darts (N, log scale)

The cyan line is the running estimate; the dashed gold line marks the true value of π. Notice how the wobble shrinks as N grows.

Why the ratio equals π/4

Take a square of side 2, centred on the origin, and inscribe a circle of radius 1 inside it. The circle's area is πr² = π; the square's area is 2 × 2 = 4. So a dart thrown uniformly at random into the square has probability π/4 ≈ 0.785 of landing inside the circle. We can't measure that probability directly — but we can estimate it by throwing lots of darts and counting. If a fraction p = inside / total land inside, then p ≈ π/4, so π ≈ 4 × inside / total. Every dart is a single Bernoulli trial; the estimate is just four times the sample mean.

Why more darts means less error

The standard error of the estimate shrinks like 1/√N, where N is the number of darts. That is the double-edged truth of Monte Carlo: it converges, but slowly. To make the estimate ten times more precise you need a hundred times as many samples. That is why the convergence line above lurches around at first and then tightens into a narrow band around π rather than snapping straight to it. No amount of cleverness in the counting changes the 1/√N rate — only more samples, or a smarter sampling scheme, does.

Where Monte Carlo actually earns its keep

Estimating π this way is a toy — there are far faster formulas for π. The method matters because the same idea scales to problems with no closed-form answer: pricing exotic options and stress-testing portfolios in finance; simulating particle transport and statistical systems in physics; modelling tail events in insurance and risk; and integrating over high-dimensional spaces where grid methods are hopeless. When the geometry gets too complicated to integrate by hand, you throw random samples at it and count — exactly what you are doing here.

Caveat: this is an illustrative demo. It leans on the browser's Math.random(), a pseudo-random generator that is fine for teaching but not cryptographically sound, and it plots a single run rather than averaging many. Real Monte Carlo work pins the random seed for reproducibility, quotes confidence intervals, and often uses variance-reduction tricks to beat plain 1/√N convergence. The area-ratio maths above, though, is exactly right. More on the Learn shelf.