Math and Science with Python

Monte Carlo Simulation in Python with NumPy

Answer questions about chance by simulating them thousands of times: estimate pi and dice probabilities with random numbers.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • Seeded random numbers with default_rng
  • Estimating pi from random points
  • Probabilities by counting simulated outcomes
Estimates of pi
1,000
100,000
1,000,000
3.14800
3.13704
3.14201

Try it many times and count

The problem

Some probability questions are hard to work out with formulas, and some systems, like queues, games or risks, are too messy for exact maths. Simulating the situation many times and counting what happens gives a good estimate.

Think of it like this

A Monte Carlo simulation is like throwing darts at a square board with a circle drawn on it. If the darts land randomly, the share that lands inside the circle tells you how big the circle is compared with the square.

From darts to code
rng.random(n)🎯 Throw n darts at random spots
x**2 + y**2 <= 1⭕ Did the dart land inside the circle?
4 * inside / n🧮 The share inside, scaled up to estimate pi
n = 1_000_000📈 More darts, better estimate
Random throws, counted.
In one sentence

A Monte Carlo simulation estimates a quantity by running many random trials and averaging the results. The error shrinks roughly with 1 / sqrt(n), so 100 times more trials give about 10 times more accuracy.

Key points

  1. np.random.default_rng(42) makes a seeded generator, so the results repeat.
  2. Points in the quarter circle land with probability pi / 4, so 4 * inside / n estimates pi.
  3. rng.integers(1, 7, size=(100_000, 2)) rolls two dice 100,000 times.
  4. np.mean(condition) is the share of trials where the condition is True.

When should you use it?

  • Probability homework and checking an exact answer.
  • Risk and finance models with uncertain inputs.
  • Physics simulations such as random walks and diffusion.

When not to use it

  • An exact formula is easy: the simulation only gives an estimate.
  • You need many correct digits: the error shrinks slowly, so it needs huge numbers of trials.

Example code

Open in editor →
main.py
import numpy as np

rng = np.random.default_rng(42)

# Estimate pi: throw random points into a 1 x 1 square and count how many
# land inside the quarter circle x**2 + y**2 <= 1
for n in [1_000, 100_000, 1_000_000]:
    x = rng.random(n)
    y = rng.random(n)
    inside = np.count_nonzero(x**2 + y**2 <= 1)
    print(f"n = {n:>9,}  pi ~ {4 * inside / n:.5f}")

# Probability that two dice add up to 7 (exact answer 1/6 = 0.1667)
rolls = rng.integers(1, 7, size=(100_000, 2))
p_seven = np.mean(rolls.sum(axis=1) == 7)
print(f"P(sum = 7) ~ {p_seven:.4f}")

# Probability of at least one six in four rolls (exact 0.5177)
four = rng.integers(1, 7, size=(100_000, 4))
print(f"P(at least one 6 in 4 rolls) ~ {np.mean((four == 6).any(axis=1)):.4f}")
Get a Run button for this example

Result of running the code

n =     1,000  pi ~ 3.14800
n =   100,000  pi ~ 3.13704
n = 1,000,000  pi ~ 3.14201
P(sum = 7) ~ 0.1676
P(at least one 6 in 4 rolls) ~ 0.5169

Code explanation

rng is a seeded random Generator, so the run gives the same numbers every time. Random points in the unit square land inside the quarter circle with probability pi / 4, so 4 * inside / n estimates pi, and the estimate is 3.14201 with a million points. rng.integers(1, 7, size=(100_000, 2)) rolls two dice 100,000 times; the share of rows that add up to 7 is 0.1676, close to the exact 1/6. The last line estimates the chance of at least one six in four rolls.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Wrong upper bound for dice

integers excludes the upper bound, so 6 never comes up.

Problem
rng.integers(1, 6, size=100_000)
Fix
rng.integers(1, 7, size=100_000)

Looping over every trial in Python

A loop over a million trials is slow; let NumPy work on whole arrays.

Problem
for _ in range(n): x = rng.random()
Fix
x = rng.random(n)

Finished this lesson?

Mark it as learned to track your progress.

Tools for this lesson