Simulating Chance
Before defining probability formally, it helps to watch it happen. A simulation runs a random experiment many times on the computer and records how often each result occurs. The fraction of times an event happens, its relative frequency, settles down as the number of trials grows. That settling down is the intuition behind every probability in this course.
Relative frequency settles down
Toss a fair coin times and track the proportion of heads. Early on it swings wildly; later it barely moves.
import random
rng = random.Random(5)
heads = 0
checkpoints = {10, 100, 1000, 10_000, 100_000}
for n in range(1, 100_001):
heads += rng.random() < 0.5
if n in checkpoints:
print(f"n={n:6d} proportion of heads={heads / n:.4f} heads - n/2 = {heads - n / 2:+.0f}")n= 10 proportion of heads=0.2000 heads - n/2 = -3
n= 100 proportion of heads=0.5000 heads - n/2 = +0
n= 1000 proportion of heads=0.5210 heads - n/2 = +21
n= 10000 proportion of heads=0.4990 heads - n/2 = -10
n=100000 proportion of heads=0.5020 heads - n/2 = +203
Notice the last column. The proportion approaches , but the difference between the number of heads and does not shrink; it typically grows like . "The law of averages" does not mean that heads and tails even out in absolute terms, only relative to . This is made precise in the law of large numbers and in random walks.
Simulating a game
Many probabilities are easy to simulate and hard to compute. Consider this game: roll a die repeatedly and add up the results; you win if the running total ever hits exactly 10. What fraction of games are won?
import random
def hits_target(rng, target):
total = 0
while total < target:
total += rng.randint(1, 6)
return total == target
rng = random.Random(11)
trials = 100_000
wins = sum(hits_target(rng, 10) for _ in range(trials))
print("estimated P(hit 10):", wins / trials)
print("1 / 3.5 =", round(1 / 3.5, 4))estimated P(hit 10): 0.2896
1 / 3.5 = 0.2857
The estimate is close to : since the average step is 3.5, the running total lands on "about one in every 3.5" integers. The exact value comes from a recurrence that you can solve in Exercise 3.
Random numbers into events
Every simulation turns uniform random numbers into the experiment you want:
- an event with probability :
rng.random() < p; - a fair die:
rng.randint(1, 6); - a weighted choice:
rng.choices(outcomes, weights); - a random shuffle:
rng.shuffle(list).
import random
from collections import Counter
rng = random.Random(3)
spins = rng.choices(["red", "black", "green"], weights=[18, 18, 2], k=38_000)
counts = Counter(spins)
for color in ["red", "black", "green"]:
print(color, counts[color], round(counts[color] / len(spins), 4))
print("exact red:", round(18 / 38, 4), " exact green:", round(2 / 38, 4))red 17983 0.4732
black 18048 0.4749
green 1969 0.0518
exact red: 0.4737 exact green: 0.0526
That is an American roulette wheel: a bet on red wins with probability , not , and the two green pockets are the house's edge.
In software
Simulation, often called the Monte Carlo method (Monte Carlo Methods), is how engineers estimate queue lengths, failure rates, financial risk and game balance when formulas are out of reach. A good habit: whenever you derive a probability, write a ten-line simulation to check it.
Exercises
Exercise 1: Roulette
You bet 1 unit on red in American roulette, winning 1 unit with probability and losing 1 otherwise. What is your average gain per bet?
Answer
units, a loss of about 5.3 cents per dollar.
Solution
.
Exercise 2: Proportion versus difference
After fair coin tosses you see 5,080 heads. What are the proportion and the difference from ? Which one is "large"?
Answer
Proportion 0.508; difference +80. Both are typical: the difference is less than one .
Solution
and . The typical size of the difference is (the standard deviation), so 80 is 1.6 standard deviations: unremarkable.
Exercise 3: Exact probability of hitting 10 (code)
Let be the probability that the running total hits exactly . Show that and (with for ), and compute exactly.
Answer
, and .
Solution
To hit , the total must hit for some and then roll exactly . Those cases are disjoint, each with probability .
from fractions import Fraction
p = [Fraction(1)]
for n in range(1, 31):
p.append(sum(p[n - k] for k in range(1, 7) if n - k >= 0) / 6)
print(p[10], round(float(p[10]), 4))
print([round(float(x), 4) for x in p[20:31:5]], round(2 / 7, 4))17492167/60466176 0.2893
[0.2856, 0.2856, 0.2857] 0.2857
Test yourself
As the number of fair coin tosses grows, what happens to (number of heads) − n/2?
- It shrinks to 0
- It typically grows, like
- It stays below 10
- It equals 0 for even n
How do you simulate an event of probability with rng = random.Random(seed)?
rng.random() < prng.random() == prng.randint(0, p)rng.random() > p