Random variables and expectation
About this lesson
A random variable turns each outcome of a chance experiment into a number. Follow three fair coin flips: list the 8 outcomes, let X count the heads, and watch the outcomes stack into the distribution 1/8, 3/8, 3/8, 1/8. Then add value × probability to get the expected value E[X] = 1.5, split X into three simpler pieces, measure the spread with the variance, and see a Python simulation settle near 1.5.
Three flips, eight outcomes
Flip a fair coin three times. There are 2 × 2 × 2 = 8 possible outcomes, from HHH to TTT. All are equally likely, so each has probability 1/8. The set of every outcome is the sample space.
>>> from itertools import product
>>> S = list(product('HT', repeat=3))
>>> len(S), S[0], S[-1]
(8, ('H', 'H', 'H'), ('T', 'T', 'T'))Read the lesson step by step
Three flips, eight outcomes
Flip a fair coin three times. There are 2 × 2 × 2 = 8 possible outcomes, from HHH to TTT. All are equally likely, so each has probability 1/8. The set of every outcome is the sample space.
>>> from itertools import product >>> S = list(product('HT', repeat=3)) >>> len(S), S[0], S[-1] (8, ('H', 'H', 'H'), ('T', 'T', 'T'))X turns outcomes into numbers
A random variable is a rule that gives every outcome a number. Let X count the heads: HHT gives 2 and TTT gives 0. The rule itself is fixed; the chance lies in which outcome happens.
>>> from itertools import product >>> S = list(product('HT', repeat=3)) >>> [w.count('H') for w in S] # X of each outcome [3, 2, 2, 1, 2, 1, 1, 0]Stack outcomes by value
Group the outcomes by their value of X. Each drops a 1/8 block on its column: one block at 0 heads, three at 1, three at 2, one at 3. The list of P(X = x) is the distribution of X.
>>> from collections import Counter >>> from itertools import product >>> Counter(w.count('H') for w in product('HT', repeat=3)) Counter({2: 3, 1: 3, 3: 1, 0: 1})Chances add up to 1
Exactly one outcome happens on every try, so a distribution always adds up to 1: 1/8 + 3/8 + 3/8 + 1/8 = 8/8 = 1. One head and two heads are the most likely values.
>>> from fractions import Fraction as F >>> p = {0: F(1, 8), 1: F(3, 8), 2: F(3, 8), 3: F(1, 8)} >>> sum(p.values()) Fraction(1, 1)Expected value
The expected value E[X] weights each value by its probability, then adds: 0 × 1/8 + 1 × 3/8 + 2 × 3/8 + 3 × 1/8 = 12/8 = 1.5. It is the long-run average of X over many tries.
>>> from fractions import Fraction as F >>> p = {0: F(1, 8), 1: F(3, 8), 2: F(3, 8), 3: F(1, 8)} >>> E = sum(x * p[x] for x in p) >>> E, float(E) (Fraction(3, 2), 1.5)The balance point
Picture the blocks as weights on a beam. E[X] = 1.5 is the point where the beam balances. It need not be a value X can take: no single try gives one and a half heads.
>>> E = 1.5 >>> # weighted distances from E cancel out >>> sum((x - E) * n for x, n in {0: 1, 1: 3, 2: 3, 3: 1}.items()) 0.0Linearity of expectation
Or split X: X = X1 + X2 + X3, where Xk is 1 if flip k is heads, else 0. Each flip is heads in 4 of 8 outcomes, so E[Xk] = 1/2. Expectations add: E[X] = 1/2 + 1/2 + 1/2 = 1.5.
>>> from itertools import product >>> S = list(product('HT', repeat=3)) >>> [sum(w[k] == 'H' for w in S) / 8 for k in range(3)] [0.5, 0.5, 0.5] >>> 0.5 + 0.5 + 0.5 1.5Variance: the spread
Variance measures spread: Var(X) = E[X²] − (E[X])². Here E[X²] = (0 + 3 + 12 + 9)/8 = 3, so Var(X) = 3 − 1.5² = 0.75. Its square root, the standard deviation, is about 0.87.
>>> from fractions import Fraction as F >>> p = {0: F(1, 8), 1: F(3, 8), 2: F(3, 8), 3: F(1, 8)} >>> EX2 = sum(x**2 * p[x] for x in p) >>> EX2, EX2 - F(3, 2)**2 (Fraction(3, 1), Fraction(3, 4)) >>> float(EX2 - F(3, 2)**2) ** 0.5 # standard deviation 0.8660254037844386Averages settle near E[X]
Now simulate it. With random.seed(1), Python's average of X is 1.9 after 10 tries, 1.5 after 100 and 1.4937 after 10,000. The law of large numbers says the average settles near E[X] = 1.5.
>>> import random >>> random.seed(1) >>> def X(): return random.choices('HT', k=3).count('H') ... >>> for n in (10, 100, 10_000): ... xs = [X() for _ in range(n)] ... print(n, sum(xs) / n) ... 10 1.9 100 1.5 10000 1.4937The exact answer in code
In code, list the sample space with itertools.product, apply X to every outcome and take the mean. All 8 outcomes are equally likely, so sum(X) / len(S) is exactly E[X] = 1.5.
>>> from itertools import product >>> S = list(product('HT', repeat=3)) >>> X = [w.count('H') for w in S] >>> sum(X) / len(S) 1.5 >>> from fractions import Fraction >>> Fraction(sum(X), len(S)) Fraction(3, 2)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01You roll one fair six-sided die. What is E[X], where X is the number shown?
Each face has probability 1/6, so E[X] = (1 + 2 + 3 + 4 + 5 + 6) / 6 = 21 / 6 = 3.5. Like 1.5 heads, 3.5 is not a value the die can show.
02For three fair coin flips, what is P(X = 2), where X is the number of heads?
Three of the eight equally likely outcomes have exactly two heads: HHT, HTH and THH. So P(X = 2) = 3/8.
03Flip a fair coin 10 times. Using linearity of expectation, what is the expected number of heads?
Write X = X1 + … + X10, where Xk is 1 if flip k is heads. Each E[Xk] = 1/2, and expectations add, so E[X] = 10 × 1/2 = 5. No list of outcomes needed.
04A random variable has E[X] = 2 and E[X²] = 5. What is Var(X)?
Var(X) = E[X²] − (E[X])² = 5 − 2² = 5 − 4 = 1.
05A simulation of X averages 1.9 after 10 tries but 1.4937 after 10,000. What explains this?
E[X] = 1.5 is fixed. Each simulated average is random, and averages of more tries vary less, so they settle near 1.5.
Glossary
- Sample space
- The set of every possible outcome of an experiment. For three coin flips it has 8 outcomes, HHH to TTT.
- Random variable
- A rule that gives each outcome a number, such as X = the number of heads. Written with a capital letter.
- Distribution (PMF)
- The list of each value x a random variable can take with its probability P(X = x). The probabilities add up to 1.
- Expected value
- E[X], the sum of each value times its probability. It is the long-run average of X and the balance point of its distribution.
- Indicator variable
- A random variable that is 1 when an event happens and 0 when it does not. Its expected value is the event's probability.
- Linearity of expectation
- E[X + Y] = E[X] + E[Y], and E[aX] = a·E[X], for any random variables, dependent or not.
- Variance
- Var(X) = E[(X − E[X])²] = E[X²] − (E[X])², the average squared distance from the mean. Its square root is the standard deviation.
- Law of large numbers
- As the number of independent tries grows, the average of the results gets closer and closer to the expected value.
Notes and sources
- Linearity of expectation, E[X + Y] = E[X] + E[Y], holds for any random variables, even ones that depend on each other. Variances only add like this when the variables are independent.
- Capital X names the random variable; small x stands for one of its values. P(X = x) is the probability that X takes the value x.
- The number of heads in n fair flips follows the binomial distribution, with E[X] = n/2 and Var(X) = n/4. For n = 3 that gives 1.5 and 0.75.
- random.seed(1) makes the pseudo-random numbers repeat, so the same three averages print every run. Without a seed you get different averages, but they still settle near 1.5.
- The standard deviation √Var(X) is in the same units as X (heads), which makes it easier to read than the variance.
- Lehman, Leighton & Meyer, Mathematics for Computer Science (MIT 6.042J), chapters 'Random Variables' and 'Deviation from the Mean'
- MIT 18.05 Introduction to Probability and Statistics (Orloff & Bloom), class notes on discrete random variables, expectation and variance
- Blitzstein & Hwang, Introduction to Probability, 2nd ed., ch. 3 and 4 (Harvard Stat 110)
- Python library: itertools.product
- Python library: random (seed, choices)
- Python library: fractions.Fraction
Quiz Unlocks after the last step.