Expectation
The expected value of a random variable is its long-run average: what you get on average over many repetitions. Expectation is the main tool for analysing randomized algorithms ("quicksort makes comparisons on average") and for comparing bets, strategies and caching policies. Its most useful property, linearity, works even when the variables are dependent.
Definition
A fair die: . The expected value need not be a possible value.
For a variable with values in there is a useful alternative: .
Mean time to failure. If each step fails independently with probability , the number of steps until the first failure is geometric, and
A server that crashes with probability per hour runs 1000 hours on average.
Linearity of expectation
For any random variables and constants (no independence needed):
The trick is to write a complicated count as a sum of indicator variables (1 if event happens, else 0), whose expectation is .
Hat-check problem. people get their hats back in a random order. Expected number who get their own hat? Let indicate that person does. , so the expectation is , for every , although the are dependent.
import random
rng = random.Random(3)
for n in [3, 10, 100]:
trials, total = 20000, 0
for _ in range(trials):
p = list(range(n))
rng.shuffle(p)
total += sum(p[i] == i for i in range(n))
print(f"n={n:3d}: average fixed points = {total / trials:.3f}")n= 3: average fixed points = 0.998
n= 10: average fixed points = 1.011
n=100: average fixed points = 1.001
Coupon collector. To collect all coupon types, the wait for the -th new type is geometric with success probability , expectation . By linearity the total is (harmonic numbers).
Quicksort's expected comparisons
Randomized quicksort compares elements (in sorted order) at most once, and does so exactly when the first pivot chosen from is or : probability . By linearity,
import random, math
def quicksort_comparisons(a, rng):
if len(a) <= 1:
return 0
pivot = a[rng.randrange(len(a))]
less = [x for x in a if x < pivot]
more = [x for x in a if x > pivot]
return len(a) - 1 + quicksort_comparisons(less, rng) + quicksort_comparisons(more, rng)
rng = random.Random(8)
n = 1000
avg = sum(quicksort_comparisons(list(range(n)), rng) for _ in range(30)) / 30
exact = sum(2 / (d + 1) * (n - d) for d in range(1, n)) # pairs at distance d
print(f"simulated: {avg:.0f} exact expectation: {exact:.0f} 2n ln n: {2 * n * math.log(n):.0f}")simulated: 11057 exact expectation: 10986 2n ln n: 13816
Expectation of products
holds when are independent, but not in general: for a fair coin indicator , . Also in general.
In software
Expected running time is the standard measure for randomized algorithms (quicksort, hash tables, skip lists, randomized load balancing). Linearity of expectation also gives quick estimates in practice: the expected number of duplicate IDs among random 32-bit IDs is , which already exceeds 1 at .
Exercises
Exercise 1: A game
You roll a die and win the square of the number shown, in euros. What is the expected win?
Answer
euros.
Solution
. Note this is not .
Exercise 2: Matching birthdays (linearity)
In a group of 30 people, what is the expected number of pairs sharing a birthday (365 equally likely days)?
Answer
.
Solution
One indicator per pair, each with probability ; there are pairs, so the expectation is .
Exercise 3: Expected rolls until a six (code)
What is the expected number of die rolls until the first 6? Verify by simulation.
Answer
Solution
Geometric with , so .
import random
rng = random.Random(4)
def rolls():
k = 1
while rng.randint(1, 6) != 6:
k += 1
return k
print(round(sum(rolls() for _ in range(100000)) / 100000, 2))6.0
Test yourself
Linearity of expectation requires the variables to be…
- independent
- identically distributed
- nothing: it always holds
- positive
Each attempt succeeds with probability . Expected attempts until the first success?
- 2
- 3
- 4
- 8
A random permutation of items has how many fixed points on average?
- 0
- 1