Estimating Pi Using the Monte Carlo Method in Python

Toss enough random darts at a unit square, count the ones inside the circle, and — boom — you've got π, courtesy of the Monte Carlo method and a bit of Python.

Quick one today — Monte Carlo $\pi$, the classic.

You know the trick, right? Throw a bunch of random darts at a unit square. Some land inside the inscribed circle, some don’t. The ratio of inside-vs-total $\times 4$ estimates $\pi$. With independent uniform draws it converges in the long run; any particular extra dart can move the estimate either way.

Why the factor of four? Our square is $0\le x,y\le1$, and the circle has centre $(0.5,0.5)$ and radius $0.5$. Its area is $\pi/4$, while the square’s area is one. So the chance of a uniformly drawn point landing inside is $p=\pi/4$, and $4\,(\text{inside}/N)$ estimates $\pi$.

Here, watch:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim(0, 1)
plt.ylim(0, 1)
N = 2_000
pause_seconds = 0.001
count = 0
for j in range(1, N + 1):
    x = np.random.rand(1)
    y = np.random.rand(1)
    if ((x-0.5)**2) + ((y-0.5)**2) <= (0.5)**2:
        plt.scatter(x, y, c='r', marker='.')
        count += 1
    else:
        plt.scatter(x, y, c='b', marker='.')
    plt.pause(pause_seconds)
    plt.title(r'$\pi$ = %s' % (round(4 * count / j, 20)))
    plt.draw()

plt.show()

The loop now has actual values for both the number of draws and the pause. Start with 2,000 points so you can watch it; plotting every point is much slower than the arithmetic.

If you only want the estimate, skip the animation:

import numpy as np

rng = np.random.default_rng(42)
N = 100_000
points = rng.random((N, 2))
inside = np.sum((points - 0.5)**2, axis=1) <= 0.25
estimate = 4 * inside.mean()
standard_error = 4 * np.sqrt(inside.mean() * (1 - inside.mean()) / N)
print(estimate, standard_error)

That standard error is a useful reality check. A hundred times as many independent draws reduces the typical sampling error by about ten, because it falls like $1/\sqrt{N}$. Printing twenty decimal places in a plot title doesn’t give us twenty digits of accuracy.

The fixed seed makes this example repeatable. See NumPy’s random sampling guide for the generator interface.

Heads up — when you actually run this thing, it’s slooow. Like, painfully slow.

The video? Yeah lol, I sped that up a ridiculous amount. Like ultra-mega-turbo speed hehe. Don’t be fooled.

If you want the backstory on why this works — the whole “throw enough random stuff at a problem and the average converges” idea — I wrote about it before:

Monte Carlo method — Financial Engineering Programming Study #9

Short version: it’s basically the Law of Large Numbers wearing a different hat. As the number of independent samples grows, the estimate converges to the true value. It can still wobble along the way. That’s the whole magic.

Monte Carlo pi estimation

Questions or corrections?

Did a step lose you, or does a number look off? Email me or use the contact page. Include the note title and the step or figure you mean.

Feedback goes to me privately by email; it is not posted as a public comment.