Chapter 7 · Simulation

Estimating π with Monte Carlo

← Chapter 7
Thrown0
Inside0
π estimate–
Absolute error–

Ready.

Estimating π with Monte Carlo

Uniformly distributed random points are thrown into the unit square and those that land inside the quarter circle are counted. The fraction of points inside gives an estimate of π.

The idea

The square with side 1 has area 1. The quarter circle of radius 1 centered at a corner of the square has area π/4. A point (x, y) chosen uniformly from the square lies inside the quarter circle when x² + y² ≤ 1, and the probability of this equals the ratio of the two areas, that is π/4. If k of n thrown points land inside, then k/n ≈ π/4, which gives the estimate π ≈ 4 · k / n.

A Monte Carlo algorithm

For n points the running time is known in advance: Θ(n). The answer, however, is random and may deviate from the true value. An algorithm whose running time is fixed and whose result is correct (or close enough) only with some probability is called a Monte Carlo algorithm. In this respect it differs from Las Vegas algorithms, whose result is always correct but whose running time is random. In the π estimate the error is two-sided: the estimate can fall both above and below the true value.

The error shrinks at the rate 1/√n

Each point is a Bernoulli trial with success probability p = π/4. The standard deviation of the estimate 4 · k / n is 4 · √(p(1 − p) / n) ≈ 1.64 / √n. The error therefore shrinks at about the rate 1/√n: to gain one more decimal digit of accuracy you need about 100 times as many points. The shaded band in the chart is the interval π ± 1.64/√n; the estimate stays inside this band with probability of about two thirds.

nStandard deviation ≈ 1.64/√n
1000.16
10,0000.016
1,000,0000.0016

How to use

  • The 1 point, 100 points and 1000 points buttons throw that many points. When a single point is thrown, its coordinates and the value of x² + y² appear in the status line, and the point is circled in the square.
  • Throw continuously keeps throwing points; while it runs, the button becomes Stop. Speed sets how many points are thrown per frame: 1, 10, 100 or 1000.
  • Seed is the starting value of the pseudo-random generator. The same seed always gives the same sequence of points. When the seed changes or Reset is pressed, the run starts over. The generator is mulberry32; the Java example in the slides (new Random(2024)) uses a different generator, so the points are not identical to its points.
  • Green points are inside the quarter circle, red points are outside. The horizontal axis of the chart shows the number of points on a logarithmic scale; the dashed horizontal line is the true value of π.
  • At most 100,000 points can be thrown.