Probability Exercises
Time to practise the whole course. Each exercise has a starter program that runs but doesn't do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: For every exercise, find the answer two ways when you can: exactly (with
Fraction, a formula or a linear system) and by simulation with a fixed seed. If they disagree by more than a few standard errors, one of them has a bug.
| # | Exercise | Practises |
|---|---|---|
| 1 | Exact dice probabilities | sample spaces, Fraction, conditional probability |
| 2 | Bayes for a spam word | Bayes' theorem, base rates |
| 3 | Distribution of a sum | convolution, expectation, variance |
| 4 | Coupon collector | geometric waiting times, linearity |
| 5 | Normal approximation | CLT, continuity correction |
| 6 | Stationary distribution | Markov chains, eigenvectors |
| 7 | Gambler's ruin | absorbing chains, linear systems |
| 8 | Estimate with an error bar | Monte Carlo, standard error |
Exercise 1: Exact dice probabilities
Two dice are rolled. Compute exactly and by listing the 36 outcomes (Conditional Probability). The starter's helper always returns 0.
from fractions import Fraction
from itertools import product
omega = list(product(range(1, 7), repeat=2))
def P(event, given=lambda w: True):
# TODO: restrict omega to outcomes satisfying `given`, return the fraction satisfying `event`
return Fraction(0)
high = lambda w: w[0] + w[1] >= 9
six = lambda w: 6 in w
print("P(sum >= 9) =", P(high))
print("P(six | sum >= 9) =", P(six, high))
print("P(six) =", P(six))P(sum >= 9) = 0
P(six | sum >= 9) = 0
P(six) = 0
Expected output when solved:
P(sum >= 9) = 5/18
P(six | sum >= 9) = 7/10
P(six) = 11/36Learning that the sum is high makes a six much more likely: 7 of the 10 high outcomes contain a six.
Hint:
F = [w for w in omega if given(w)], thenFraction(sum(1 for w in F if event(w)), len(F)).
Solution
from fractions import Fraction
from itertools import product
omega = list(product(range(1, 7), repeat=2))
def P(event, given=lambda w: True):
F = [w for w in omega if given(w)]
return Fraction(sum(1 for w in F if event(w)), len(F))
high = lambda w: w[0] + w[1] >= 9
six = lambda w: 6 in w
print("P(sum >= 9) =", P(high))
print("P(six | sum >= 9) =", P(six, high))
print("P(six) =", P(six))P(sum >= 9) = 5/18
P(six | sum >= 9) = 7/10
P(six) = 11/36
Exercise 2: Bayes for a spam word
3% of email is phishing. The word "verify" appears in 40% of phishing mails and 2% of legitimate ones. Compute (Bayes' Theorem), then the posterior after a second independent clue, a mismatched link, present in 70% of phishing and 5% of legitimate mail. The starter returns the prior unchanged.
def update(prior, p_e_given_h, p_e_given_not_h):
# TODO: return the posterior P(H | E) by Bayes' theorem
return prior
p = 0.03
p = update(p, 0.40, 0.02)
print(f"after 'verify': {p:.4f}")
p = update(p, 0.70, 0.05)
print(f"after the mismatched link too: {p:.4f}")after 'verify': 0.0300
after the mismatched link too: 0.0300
Expected output when solved:
after 'verify': 0.3822
after the mismatched link too: 0.8965Each clue multiplies the odds by its likelihood ratio (20, then 14), turning a 3% prior into almost 90%.
Hint: numerator
p_e_given_h * prior, denominatornumerator + p_e_given_not_h * (1 - prior).
Solution
def update(prior, p_e_given_h, p_e_given_not_h):
num = p_e_given_h * prior
return num / (num + p_e_given_not_h * (1 - prior))
p = 0.03
p = update(p, 0.40, 0.02)
print(f"after 'verify': {p:.4f}")
p = update(p, 0.70, 0.05)
print(f"after the mismatched link too: {p:.4f}")after 'verify': 0.3822
after the mismatched link too: 0.8965
Exercise 3: Distribution of a sum
Find the exact distribution of the sum of a fair die and a 4-sided die by convolution (Sums of Discrete Variables), and its mean and variance. The starter does not convolve.
from fractions import Fraction
d6 = {k: Fraction(1, 6) for k in range(1, 7)}
d4 = {k: Fraction(1, 4) for k in range(1, 5)}
def convolve(a, b):
out = {}
# TODO: for each pair of values (x, y), add a[x] * b[y] to out[x + y]
return out
s = convolve(d6, d4)
mean = sum(k * p for k, p in s.items())
var = sum(k * k * p for k, p in s.items()) - mean ** 2
print({k: str(s[k]) for k in sorted(s)})
print("mean", mean, " variance", var){}
mean 0 variance 0
Expected output when solved:
{2: '1/24', 3: '1/12', 4: '1/8', 5: '1/6', 6: '1/6', 7: '1/6', 8: '1/8', 9: '1/12', 10: '1/24'}
mean 6 variance 25/6The mean is and the variance : means and (for independent variables) variances add.
Hint: two nested loops over
a.items()andb.items(), without[x + y] = out.get(x + y, 0) + px * py.
Solution
from fractions import Fraction
d6 = {k: Fraction(1, 6) for k in range(1, 7)}
d4 = {k: Fraction(1, 4) for k in range(1, 5)}
def convolve(a, b):
out = {}
for x, px in a.items():
for y, py in b.items():
out[x + y] = out.get(x + y, 0) + px * py
return out
s = convolve(d6, d4)
mean = sum(k * p for k, p in s.items())
var = sum(k * k * p for k, p in s.items()) - mean ** 2
print({k: str(s[k]) for k in sorted(s)})
print("mean", mean, " variance", var){2: '1/24', 3: '1/12', 4: '1/8', 5: '1/6', 6: '1/6', 7: '1/6', 8: '1/8', 9: '1/12', 10: '1/24'}
mean 6 variance 25/6
Exercise 4: Coupon collector
How many random draws from sticker types are needed on average to collect all of them? Compute exactly (Geometric and Negative Binomial) and simulate. The starter's simulation stops after the first draw.
import random
from fractions import Fraction
n = 20
exact = sum(Fraction(n, n - i) for i in range(n))
print("exact n H_n =", float(round(exact, 3)))
rng = random.Random(1)
def draws_to_complete():
seen, draws = set(), 0
# TODO: keep drawing rng.randrange(n) until all n types are seen
draws += 1
return draws
runs = 20_000
print("simulated:", round(sum(draws_to_complete() for _ in range(runs)) / runs, 2))exact n H_n = 71.955
simulated: 1.0
Expected output when solved:
exact n H_n = 71.955
simulated: 72.2Hint:
while len(seen) < n: seen.add(rng.randrange(n)); draws += 1.
Solution
import random
from fractions import Fraction
n = 20
exact = sum(Fraction(n, n - i) for i in range(n))
print("exact n H_n =", float(round(exact, 3)))
rng = random.Random(1)
def draws_to_complete():
seen, draws = set(), 0
while len(seen) < n:
seen.add(rng.randrange(n))
draws += 1
return draws
runs = 20_000
print("simulated:", round(sum(draws_to_complete() for _ in range(runs)) / runs, 2))exact n H_n = 71.955
simulated: 72.2
Exercise 5: Normal approximation
A server handles 400 independent requests, each failing with probability 0.05. Approximate with the normal curve and the continuity correction, and compare with the exact binomial value (The CLT for Bernoulli Trials). The starter has only the exact sum.
from math import comb, sqrt, erf
n, p = 400, 0.05
exact = sum(comb(n, k) * p ** k * (1 - p) ** (n - k) for k in range(30, n + 1))
Phi = lambda z: 0.5 * (1 + erf(z / sqrt(2)))
approx = 0.0 # TODO: 1 - Phi((29.5 - mean) / sd) with mean n p and sd sqrt(n p (1 - p))
print(f"exact {exact:.4f} normal approximation {approx:.4f}")exact 0.0190 normal approximation 0.0000
Expected output when solved:
exact 0.0190 normal approximation 0.0146The approximation is in the right range but too small: with the binomial is still skewed to the right, so the normal curve underestimates the upper tail.
Hint:
mean, sd = n * p, sqrt(n * p * (1 - p)).
Solution
from math import comb, sqrt, erf
n, p = 400, 0.05
exact = sum(comb(n, k) * p ** k * (1 - p) ** (n - k) for k in range(30, n + 1))
Phi = lambda z: 0.5 * (1 + erf(z / sqrt(2)))
mean, sd = n * p, sqrt(n * p * (1 - p))
approx = 1 - Phi((29.5 - mean) / sd)
print(f"exact {exact:.4f} normal approximation {approx:.4f}")exact 0.0190 normal approximation 0.0146
Exercise 6: Stationary distribution
A user of an app is Active, Idle or Gone-for-a-week each day, with the transition matrix below. Find the long-run fraction of days in each state by solving (Ergodic Chains). The starter just returns the uniform distribution.
import numpy as np
P = np.array([[0.7, 0.2, 0.1],
[0.3, 0.5, 0.2],
[0.2, 0.3, 0.5]])
def stationary(P):
n = len(P)
# TODO: solve w (P - I) = 0 with sum(w) = 1, e.g. replace one equation of (P - I)^T w = 0 by ones
return np.full(n, 1 / n)
w = stationary(P)
print("w =", np.round(w, 4).tolist())
print("check w P = w:", np.allclose(w @ P, w))w = [0.3333, 0.3333, 0.3333]
check w P = w: False
Expected output when solved:
w = [0.4634, 0.3171, 0.2195]
check w P = w: TrueHint:
A = (P - np.eye(n)).T; A[-1] = 1; b = np.zeros(n); b[-1] = 1; return np.linalg.solve(A, b).
Solution
import numpy as np
P = np.array([[0.7, 0.2, 0.1],
[0.3, 0.5, 0.2],
[0.2, 0.3, 0.5]])
def stationary(P):
n = len(P)
A = (P - np.eye(n)).T
A[-1] = 1.0
b = np.zeros(n)
b[-1] = 1.0
return np.linalg.solve(A, b)
w = stationary(P)
print("w =", np.round(w, 4).tolist())
print("check w P = w:", np.allclose(w @ P, w))w = [0.4634, 0.3171, 0.2195]
check w P = w: True
Exercise 7: Gambler's ruin
A player with 3 units bets 1 unit at a time with win probability 0.45 and stops at 0 or 8. Compute the probability of reaching 8 from every starting amount by solving the absorbing-chain system (Absorbing Markov Chains) and compare with the formula of Gambler's Ruin. The starter does not solve the system.
import numpy as np
p, N = 0.45, 8
t = N - 1 # transient states 1..7
Q = np.zeros((t, t))
R_win = np.zeros(t) # one-step probability of jumping to N
for i in range(t):
k = i + 1
if k + 1 < N:
Q[i, i + 1] = p
else:
R_win[i] = p
if k - 1 > 0:
Q[i, i - 1] = 1 - p
win = np.zeros(t) # TODO: win = (I - Q)^{-1} R_win
r = (1 - p) / p
formula = [(1 - r ** k) / (1 - r ** N) for k in range(1, N)]
print("linear system:", np.round(win, 4).tolist())
print("formula: ", np.round(formula, 4).tolist())linear system: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
formula: [0.0558, 0.1241, 0.2075, 0.3095, 0.4341, 0.5864, 0.7725]
Expected output when solved:
linear system: [0.0558, 0.1241, 0.2075, 0.3095, 0.4341, 0.5864, 0.7725]
formula: [0.0558, 0.1241, 0.2075, 0.3095, 0.4341, 0.5864, 0.7725]From 3 units the chance of reaching 8 is only about 0.21, well below the fair-game value .
Hint:
np.linalg.solve(np.eye(t) - Q, R_win).
Solution
import numpy as np
p, N = 0.45, 8
t = N - 1
Q = np.zeros((t, t))
R_win = np.zeros(t)
for i in range(t):
k = i + 1
if k + 1 < N:
Q[i, i + 1] = p
else:
R_win[i] = p
if k - 1 > 0:
Q[i, i - 1] = 1 - p
win = np.linalg.solve(np.eye(t) - Q, R_win)
r = (1 - p) / p
formula = [(1 - r ** k) / (1 - r ** N) for k in range(1, N)]
print("linear system:", np.round(win, 4).tolist())
print("formula: ", np.round(formula, 4).tolist())linear system: [0.0558, 0.1241, 0.2075, 0.3095, 0.4341, 0.5864, 0.7725]
formula: [0.0558, 0.1241, 0.2075, 0.3095, 0.4341, 0.5864, 0.7725]
Exercise 8: Estimate with an error bar
Estimate the probability that three random points on a circle lie in a common semicircle (exact answer ) and report a 95% error bar (Using the CLT). The starter prints the estimate without an error bar and uses a wrong test.
import numpy as np
rng = np.random.default_rng(8)
n = 100_000
angles = np.sort(rng.uniform(0, 1, size=(n, 3)), axis=1) # positions as fractions of the circle
gaps = np.diff(np.concatenate([angles, angles[:, :1] + 1], axis=1), axis=1)
hit = gaps.max(axis=1) > 0.9 # TODO: the points fit in a semicircle iff some gap is at least 1/2
est = hit.mean()
half = 0.0 # TODO: 1.96 * standard error of the mean of `hit`
print(f"estimate {est:.4f} +- {half:.4f} exact 0.75")estimate 0.0295 +- 0.0000 exact 0.75
Expected output when solved:
estimate 0.7522 +- 0.0027 exact 0.75Hint: the three gaps between consecutive points (going round) sum to 1; the points lie in a semicircle exactly when the largest gap is at least . The standard error is
hit.std() / np.sqrt(n).
Solution
import numpy as np
rng = np.random.default_rng(8)
n = 100_000
angles = np.sort(rng.uniform(0, 1, size=(n, 3)), axis=1)
gaps = np.diff(np.concatenate([angles, angles[:, :1] + 1], axis=1), axis=1)
hit = gaps.max(axis=1) >= 0.5
est = hit.mean()
half = 1.96 * hit.std() / np.sqrt(n)
print(f"estimate {est:.4f} +- {half:.4f} exact 0.75")estimate 0.7522 +- 0.0027 exact 0.75
Test yourself
In Exercise 2, why does the posterior jump so much after two clues?
- Because the prior was wrong
- Each independent clue multiplies the odds by its likelihood ratio
- Because probabilities add
- It does not
In Exercise 5, why does the normal approximation underestimate the tail?
- The continuity correction is wrong
- The binomial with is still right-skewed
- The CLT does not apply to binomials
- Rounding errors
Three random points on a circle lie in a common semicircle with probability…
- 1/2
- 2/3
- 3/4
- 1
Where next
The Mini Project puts Markov chains, simulation and the CLT together on a board game. For statistics built on these foundations see Statistics; for the probability behind machine learning see Math for ML.