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.
- Seeded random numbers with default_rng
- Estimating pi from random points
- Probabilities by counting simulated outcomes
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.
rng.random(n)🎯 Throw n darts at random spotsx**2 + y**2 <= 1⭕ Did the dart land inside the circle?4 * inside / n🧮 The share inside, scaled up to estimate pin = 1_000_000📈 More darts, better estimateA 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
np.random.default_rng(42)makes a seeded generator, so the results repeat.- Points in the quarter circle land with probability pi / 4, so
4 * inside / nestimates pi. rng.integers(1, 7, size=(100_000, 2))rolls two dice 100,000 times.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
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}")
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.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Wrong upper bound for dice
integers excludes the upper bound, so 6 never comes up.
rng.integers(1, 6, size=100_000)
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.
for _ in range(n): x = rng.random()
x = rng.random(n)
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Generate Random Numbers with NumPyGenerate reproducible random integers with NumPy's modern Generator API.
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.