TExcelTAD
Home › Probability Theory › Simulating Chance

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 nn times and track the proportion of heads. Early on it swings wildly; later it barely moves.

python · try it yourself
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 1/21/2, but the difference between the number of heads and n/2n/2 does not shrink; it typically grows like n\sqrt{n}. "The law of averages" does not mean that heads and tails even out in absolute terms, only relative to nn. 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?

python · try it yourself
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 1/3.5=2/71/3.5 = 2/7: 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 pp: rng.random() < p;
  • a fair die: rng.randint(1, 6);
  • a weighted choice: rng.choices(outcomes, weights);
  • a random shuffle: rng.shuffle(list).
python · try it yourself
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 18/38≈0.47418/38 \approx 0.474, not 1/21/2, 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 18/3818/38 and losing 1 otherwise. What is your average gain per bet?

Answer

−2/38≈−0.053-2/38 \approx -0.053 units, a loss of about 5.3 cents per dollar.

Solution

1⋅1838−1⋅2038=−2381 \cdot \frac{18}{38} - 1 \cdot \frac{20}{38} = -\frac{2}{38}.

Exercise 2: Proportion versus difference

After 10,00010{,}000 fair coin tosses you see 5,080 heads. What are the proportion and the difference from n/2n/2? Which one is "large"?

Answer

Proportion 0.508; difference +80. Both are typical: the difference is less than one n=100\sqrt{n} = 100.

Solution

5080/10000=0.5085080/10000 = 0.508 and 5080−5000=805080 - 5000 = 80. The typical size of the difference is n/2=50\sqrt{n}/2 = 50 (the standard deviation), so 80 is 1.6 standard deviations: unremarkable.

Exercise 3: Exact probability of hitting 10 (code)

Let pnp_n be the probability that the running total hits exactly nn. Show that p0=1p_0 = 1 and pn=16(pn−1+⋯+pn−6)p_n = \frac{1}{6}(p_{n-1} + \cdots + p_{n-6}) (with pk=0p_k = 0 for k<0k < 0), and compute p10p_{10} exactly.

Answer

p10=17492167/60466176≈0.2893p_{10} = 17492167/60466176 \approx 0.2893, and pn→2/7≈0.2857p_n \to 2/7 \approx 0.2857.

Solution

To hit nn, the total must hit n−kn - k for some k∈{1,…,6}k \in \{1, \ldots, 6\} and then roll exactly kk. Those cases are disjoint, each with probability 16pn−k\frac{1}{6} p_{n-k}.

python · try it yourself
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?

  1. It shrinks to 0
  2. It typically grows, like n\sqrt{n}
  3. It stays below 10
  4. It equals 0 for even n

How do you simulate an event of probability pp with rng = random.Random(seed)?

  1. rng.random() < p
  2. rng.random() == p
  3. rng.randint(0, p)
  4. rng.random() > p