All projects

Estimating π with Monte Carlo

Random points in a square are enough to approximate π. Start the simulation and watch the estimate close in on the true value.

Estimate of π
—
Points drawn
0
Inside the quarter disc
0
Distance from π
—
Medium

How it works

Take a square of side 1 and, inside it, a quarter disc of radius 1 centred on one corner. The square has area 1; the quarter disc has area π/4.

We draw points uniformly at random in the square: two numbers x and y between 0 and 1. The point is inside the quarter disc if x² + y² ≤ 1. The share of points that land inside gets closer to π/4, so:

π ≈ 4 × points inside the quarter discpoints drawn

The error shrinks roughly like 1/√N, where N is the number of points: to gain one decimal place you need about a hundred times more points. It is a slow way to compute π, but it shows a very general idea: using randomness to estimate a quantity that is hard to compute directly.

What I learned

This project introduced me to the law of large numbers: a random draw, repeated thousands of times, ends up giving a precise result. I also saw that convergence is slow: to gain one more decimal of π, you need about a hundred times more points.

View the code on GitHub