In a class of 30 students, what's the chance that two share a birthday? Most people guess around 10%, reasoning that there are 365 days and only 30 people. The real answer is about 70%. When intuition and maths disagree this badly, it helps to have a third opinion that anyone can check: simulation. Make a computer run the experiment thousands of times and count how often the event happens.
Simulation, also called the Monte Carlo method, turns the long-run meaning of probability from what is probability? into a tool. It needs no formulas, only the ability to describe the experiment in code. Here you'll build a reusable recipe, test it against exact answers, measure how accurate it is, then use it on three puzzles: the birthday problem, a cricket sticker album and the Monty Hall game.
What you need first: rules of probability: and, or and not and permutations and combinations. The NumPy used here was introduced in NumPy for linear algebra.
Key terms
- Simulation (or Monte Carlo method): estimating a probability by running a random experiment many times and counting how often the event happens.
- Trial: one run of the simulated experiment.
- Estimate: the share of trials in which the event happened. It's close to the true probability, not equal to it.
- Random seed: a starting number for the random generator. Using the same seed gives the same "random" numbers every run, so results can be reproduced.
- Vectorised code: NumPy code that works on whole arrays at once instead of looping over trials one by one. Much faster.
The recipe
Every simulation follows the same four steps:
- Describe one trial in code: what's random, and what happens.
- Decide whether the event happened in that trial: True or False.
- Repeat for many trials.
- Estimate the probability as the share of True results.
Start with a question you can already answer exactly, so you can check the recipe. From the last lesson: the chance of at least one six in 4 rolls of a die is 1 − (5/6)⁴.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(42)
def at_least_one_six(n_trials):
rolls = rng.integers(1, 7, size=(n_trials, 4)) # step 1: one row per trial
happened = (rolls == 6).any(axis=1) # step 2: True if any six
return happened.mean() # steps 3-4: share of True
print(f"simulated {at_least_one_six(100_000):.4f}")
print(f"exact {1 - (5 / 6) ** 4:.4f}")
simulated 0.5157
exact 0.5177
np.random.default_rng(42)makes a random generator with seed 42, so you get the same numbers as this page.size=(n_trials, 4)creates all the trials at once: one row of 4 rolls per trial. That's the vectorised step: noforloop over 100,000 trials.- The mean of True/False values is the share of True, because True counts as 1 and False as 0.
The estimate lands within a fraction of a percent of the exact answer.
How many trials do you need?
A simulation's estimate is a sample, so it wobbles, like the averages in population vs sample. How much? Run the same simulation 200 times at each size and look at the spread of the estimates. Predict: going from 1,000 to 100,000 trials, which is 100 times as many, how much smaller will the wobble be?
exact = 1 - (5 / 6) ** 4
rows = []
for n in [100, 1_000, 10_000, 100_000]:
estimates = np.array([at_least_one_six(n) for _ in range(200)])
rows.append({"trials": n, "typical error": round(estimates.std(), 4),
"worst of 200": round(np.abs(estimates - exact).max(), 4)})
print(pd.DataFrame(rows).to_string(index=False))
trials typical error worst of 200
100 0.0536 0.1923
1000 0.0158 0.0447
10000 0.0051 0.0136
100000 0.0015 0.0043
[at_least_one_six(n) for _ in range(200)]repeats the whole simulation 200 times. The_is a name for a loop variable you don't use.- "Typical error" is the SD of the 200 estimates; "worst of 200" is the biggest miss.
Each 100 times more trials makes the typical error about 10 times smaller. That's a general rule: the error shrinks with the square root of the number of trials. For a rough answer, 10,000 trials is plenty; for three reliable decimal places, use a million. Simulation is cheap, but precision gets expensive.
Puzzle 1: the birthday problem
Back to the class of 30. One trial: give 30 students random birthdays from 365 days (ignoring 29 February), and check whether any day appears twice.
def shared_birthday(group_size, n_trials=20_000):
birthdays = rng.integers(0, 365, size=(n_trials, group_size))
birthdays.sort(axis=1)
repeat = (np.diff(birthdays, axis=1) == 0).any(axis=1)
return repeat.mean()
print(f"class of 30: {shared_birthday(30):.3f}")
class of 30: 0.714
- Each row is one class: 30 random days, numbered 0 to 364.
- Sorting each row puts equal birthdays next to each other, so
np.diff(the gaps between neighbours) is 0 exactly where two students share a day.
About 70%. Now the exact answer, to check the simulation. "At least one shared birthday" is the complement of "all different". Using counting: the first student can have any of 365 days, the second any of the 364 left, and so on, out of 365³⁰ equally likely ways:
P(all different) = (365 × 364 × ... × 336) ÷ 365³⁰
Compare simulation and exact answer for every group size from 2 to 60:
def exact_shared(k):
return 1 - np.prod((365 - np.arange(k)) / 365)
sizes = np.arange(2, 61)
simulated = [shared_birthday(k, 5_000) for k in sizes]
exact_values = [exact_shared(k) for k in sizes]
fig, ax = plt.subplots(figsize=(8.5, 4.2))
ax.plot(sizes, exact_values, color="#1c1917", linewidth=2, label="exact")
ax.scatter(sizes, simulated, color="#c2410c", s=18, zorder=3, label="simulated (5,000 trials each)")
ax.axhline(0.5, color="#57534e", linestyle=":", linewidth=1)
ax.set_xlabel("Number of people")
ax.set_ylabel("P(at least two share a birthday)")
ax.set_title("With just 23 people, a shared birthday is more likely than not")
ax.legend()
plt.show()
print("23 people:", round(exact_shared(23), 3), " 30 people:", round(exact_shared(30), 3), " 50 people:", round(exact_shared(50), 3))
23 people: 0.507 30 people: 0.706 50 people: 0.97
(365 - np.arange(k)) / 365 makes the fractions 365/365, 364/365, ... for each student, and np.prod multiplies them, giving P(all different).
The dots follow the curve: the simulation and the counting agree. And the curve explains the surprise. You aren't asking whether someone shares your birthday; you're asking about any pair. A class of 30 has C(30, 2) = 435 pairs, and each pair has a 1 in 365 chance. With so many pairs, a match is likely.
The same effect matters in computing. Systems that give records random IDs must make the IDs long enough that two never collide, and the birthday problem is how engineers work out how long that is.
Puzzle 2: completing a sticker album
A biscuit brand puts one of 10 cricket player stickers in each packet, each equally likely. How many packets do you need to buy, on average, to collect all 10? This one is hard to work out by hand, but easy to simulate:
def packets_to_complete(n_stickers=10):
collected, packets = set(), 0
while len(collected) < n_stickers:
collected.add(rng.integers(0, n_stickers))
packets += 1
return packets
results = np.array([packets_to_complete() for _ in range(20_000)])
print(f"average packets: {results.mean():.1f}")
print(f"median: {np.median(results):.0f} 90th percentile: {np.percentile(results, 90):.0f}")
print(f"share needing more than 40: {(results > 40).mean():.3f}")
average packets: 29.3
median: 27 90th percentile: 44
share needing more than 40: 0.139
- The
whileloop opens packets until thesetholds all 10 different stickers. A set ignores duplicates, which is exactly what a collector's album does. - This simulation uses a loop rather than vectorised code, because each trial's length varies. 20,000 trials still take only a few seconds.
On average you need about 29 packets for 10 stickers, nearly three times the number of stickers. The last few stickers are the expensive ones: when you have 9 of the 10, each packet has only a 1 in 10 chance of giving the missing one. The simulation also gives what a formula for the average wouldn't: one collector in ten needs about 44 packets or more. Companies that run such promotions use this kind of calculation to decide how many packets they need to print.
Puzzle 3: the Monty Hall game
A game show has 3 doors: a car behind one, goats behind the other two. You pick a door. The host, who knows where the car is, opens one of the other doors to show a goat, then offers you the chance to switch to the remaining closed door. Should you switch?
Most people say it doesn't matter: two doors left, so 50-50. Arguments about this puzzle have run for decades. Simulation settles it:
n = 100_000
car = rng.integers(0, 3, size=n)
first_pick = rng.integers(0, 3, size=n)
stay_wins = (first_pick == car).mean()
switch_wins = (first_pick != car).mean()
print(f"stay wins {stay_wins:.3f} switch wins {switch_wins:.3f}")
stay wins 0.335 switch wins 0.665
Switching wins about two-thirds of the time. Why does first_pick != car describe switching? If your first pick was a goat, the host must open the other goat door, so the remaining door must hide the car: switching wins. If your first pick was the car, switching loses. You pick a goat 2 times in 3, so switching wins 2 times in 3. The host's choice isn't random; it carries information, and that's why it isn't 50-50. Information changing probabilities is exactly what the next module, conditional probability, is about.
When to simulate, and when not to
Simulation is the right tool when:
- an exact calculation is hard or messy, like the sticker album;
- you want to check an exact answer;
- the question involves a whole system: queues, inventory, risk across many loans.
It has limits:
- every estimate has an error, shrinking only with the square root of the number of trials;
- very rare events need a huge number of trials (a one-in-a-million event needs many millions);
- a simulation is only as good as its description of the experiment. If you model birthdays as equally likely when they aren't, or failures as independent when they're linked, you'll get a precise answer to the wrong question.
Where machine learning uses simulation
- Bootstrapping: resampling a dataset thousands of times to see how much a model's accuracy might wobble, which you'll meet in the sampling module.
- Random forests build each tree from a random resample of the data, a simulation idea at the heart of a model.
- Reinforcement learning agents learn by simulating thousands of games or episodes.
- Testing a model's decisions: simulating many loan applicants to estimate profit and risk under different approval thresholds.
Common mistakes
- Too few trials. 100 trials can be off by 5 percentage points; check how much your answer wobbles between runs.
- Forgetting the seed. Without a seed, results change every run, which makes debugging and comparisons hard.
- Slow loops. Generate all trials at once with NumPy arrays where you can.
- Simulating the wrong experiment. Write down the story in words first, then check that each line of code matches it.
Practice
- Simulate the chance that two dice total 7. How close to 1/6 do you get with 10,000 trials? With 1,000,000?
Show the answer
for n in [10_000, 1_000_000]:
totals = rng.integers(1, 7, size=n) + rng.integers(1, 7, size=n)
print(n, round((totals == 7).mean(), 4))
print("exact", round(1 / 6, 4))
10000 0.1636
1000000 0.1663
exact 0.1667
The million-trial estimate is much closer: 100 times more trials, about 10 times less error.
- Predict, then check: how many people are needed for a shared birthday to be 90% likely?
Show the answer
41 people.
print(next(k for k in range(2, 100) if exact_shared(k) >= 0.9))
41
next(...) returns the first group size whose probability reaches 0.9.
- Simulate the chance that a 4-digit OTP has at least one repeated digit. Compare with the exact answer from permutations and combinations.
Show the answer
otps = rng.integers(0, 10, size=(100_000, 4))
otps.sort(axis=1)
print(round((np.diff(otps, axis=1) == 0).any(axis=1).mean(), 4), "exact", 1 - 5040 / 10_000)
0.4959 exact 0.496
The same sort-and-compare trick as the birthday problem: an OTP is a tiny "birthday problem" with 10 possible days.
- Change the sticker album to 20 stickers. Before running, guess the average number of packets.
Show the answer
About 72: more than double the 29 for 10 stickers, because the hunt for the last few gets longer.
print(round(np.mean([packets_to_complete(20) for _ in range(10_000)]), 1))
71.7
- In Monty Hall with 10 doors, the host opens 8 goat doors, leaving your door and one other. Should you switch, and how often does switching win?
Show the answer
Switch. Your first pick is right only 1 time in 10; otherwise the car is behind the one door the host left closed. Switching wins 9 times in 10.
car10 = rng.integers(0, 10, size=n)
pick10 = rng.integers(0, 10, size=n)
print(round((pick10 != car10).mean(), 3))
0.899
Interview questions
What is a Monte Carlo simulation, and how accurate is it?
It estimates a quantity, such as a probability or an average, by simulating a random process many times and averaging the results. The standard error falls in proportion to 1/√n, so 100 times more trials give about 10 times more precision. Accuracy also depends on the model of the process being correct.
Explain the birthday problem and why it matters in practice.
In a group of 23 people, the probability that at least two share a birthday is just over 50%, because there are 253 pairs, each with a 1/365 chance of matching. It explains collision risk for random IDs and hashes: collisions become likely after about the square root of the number of possible values, so IDs must be much longer than intuition suggests.
Key takeaways
- Simulation estimates a probability by running the experiment many times and counting: describe, decide, repeat, estimate.
- Use NumPy arrays to run all trials at once, and set a seed so results can be reproduced.
- The error shrinks with the square root of the number of trials: 100 times more trials, about 10 times more accurate.
- Check simulations against exact answers when you can; use them when exact answers are hard.
- The birthday problem (about 70% in a class of 30) and Monty Hall (switching wins 2 in 3) show how often intuition misjudges probability.
Frequently asked questions
Why is it called Monte Carlo?
After the casino in Monaco, because the method relies on chance. It was named by scientists working on early computer simulations in the 1940s.
Are computer random numbers truly random?
No. They're "pseudo-random": produced by a formula, which is why a seed reproduces them. For simulations they're more than good enough. For passwords and security, use Python's secrets module instead.
Should I simulate or calculate?
Calculate when there's a simple exact answer; simulate when the exact answer is hard, or to check your calculation. Many data scientists do both.
What to learn next
- Revisit the rules you simulated in rules of probability: and, or and not.
- See how simulation estimates vary in population vs sample.
- Next comes the conditional probability module, starting with conditional probability explained. Meanwhile, see Bayes' theorem used in Naive Bayes classifier.