Contents/ Part VI · Probability/ Chapter 36

Random Variables & Expectation

A random variable turns the outcome of a random experiment into a number, and once you have numbers you can ask for their average and their spread. Expectation and variance are the two summaries that describe any random variable, and the bridge from probability to statistics.

⏱️ ~15 min read
🐍 Notebook included
📊 Chapter 36

So far an event was a yes-or-no affair: the sum is 7, or it is not. But often we care about a number attached to the outcome, how many heads, what the total is, how much we win. A random variable is exactly that: a rule that assigns a number to every outcome.

X
A random variable is a function that maps each outcome of an experiment to a real number. Its expected value E[X] is the long-run average of those numbers, and its variance measures how far they typically spread from that average.
🔤
Discrete vs continuous

A discrete random variable takes separate, countable values (a die, a head count) and is described by a probability mass function giving P(X = x). A continuous one takes any value in a range (a height, a wait time) and is described by a density curve, the subject of the next Part. This chapter builds the ideas on the cleaner discrete case; they carry straight over.

1

From Outcomes to Numbers

A random variable is a translation layer. The experiment produces a messy outcome (which faces came up, which coins landed heads); the random variable reads off the single number we actually care about.

A random variable X maps each outcome to a number outcomes (2 coin flips) HHHTTHTT X = number of heads 0 1 2 two outcomes both map to 1

For two coin flips, X = number of heads sends HH to 2, both HT and TH to 1, and TT to 0. Collecting the probabilities gives the probability mass function: P(X=0) = 1/4, P(X=1) = 1/2, P(X=2) = 1/4. Like any distribution, the masses are non-negative and sum to 1.

2

Expected Value: the Balance Point

The expected value E[X] is the probability-weighted average of the values a random variable can take: E[X] = Σ x · P(X = x). Physically it is the balance point of the distribution, the spot where the bars would teeter on a fulcrum.

The dice-sum distribution balances at its expected value 2345 6789 101112 E[X] = 7

For the sum of two dice, E[X] = 2(1/36) + 3(2/36) + ... + 12(1/36) = 7. Notice 7 is not a value you can roll on a single die, the expected value is an average, not a guaranteed outcome. And by the Law of Large Numbers from the Probability by Simulation chapter, the mean of many simulated rolls settles right onto 7.

Linearity of expectation

The single most useful property: E[X + Y] = E[X] + E[Y], always, even when X and Y are dependent. And E[aX + b] = a·E[X] + b. In a Secret Santa of n people, each matches their own name with probability 1/n, so the expected number of self-matches is n × (1/n) = 1, for every n. Linearity lets you average first and worry about dependence never.

3

Variance and Standard Deviation

Expectation gives the center; variance gives the spread. It is the expected squared distance from the mean: Var(X) = E[(X − μ)²]. Two distributions can share an expected value yet feel completely different, and variance is what tells them apart.

Same mean, different variance low variance μ (mean) high variance μ (same mean) Var(X) = E[(X − μ)²] = E[X²] − μ²: the average squared distance from the mean

The shortcut Var(X) = E[X²] − μ² is usually easiest by hand. For the dice sum, E[X²] = 54.833 and μ = 7, so Var(X) = 54.833 − 49 = 5.833, and the standard deviation is √5.833 ≈ 2.42. Standard deviation is in the same units as X, which is why it, not variance, is what we usually report.

QuantityDefinitionWhat it tells you
Expected value E[X]Σ x · P(X = x)the center, the long-run average
Variance Var(X)E[(X − μ)²] = E[X²] − μ²the spread, in squared units
Standard deviation SD(X)√Var(X)the spread, in the original units
📏
How constants behave

Shifting by a constant moves the center but not the spread: Var(X + b) = Var(X). Scaling stretches the spread quadratically: Var(aX) = a² Var(X). So a payoff of 2X + 1 has the same shape as X, shifted and stretched: its variance is 4 × Var(X).

4

Expectation in Machine Learning & AI

Expectation is not a side topic in machine learning, it is the objective. Nearly every model is trained by pushing down an expected loss, and several whole fields are built on averaging a random variable.

Training minimizes expected loss (risk): the lower bar wins Model A E[loss] = 0.52 Model B E[loss] = 0.18 ✓

Cross-entropy loss, the workhorse objective for classifiers and language models, is literally an expected value: the average of −log(p) on the true answer across the data. Lower expected loss means a better model, so gradient descent is just a machine for driving an expectation down.

Idea (this chapter)In ML / AI it becomesConcrete example
Expected loss E[loss]The training objective (risk)minimize average cross-entropy over the data
Expected reward E[R]The goal of reinforcement learningan agent maximizes its long-run average reward
Estimating an expectationMonte Carlo methodsaverage many samples to approximate E[X]
VarianceRisk, noise, and uncertaintyhigh-variance gradients make training unstable
Linearity of EWhy batch averages behavethe mean gradient equals the average of the gradients
🤖
Why this matters for AI research

The phrase "minimize the expected loss" hides a random variable: the loss is a number attached to a randomly drawn example, and training drives down its expectation. Reinforcement learning swaps loss for reward and maximizes E[R]. Monte Carlo estimation, the trick behind everything from dropout to policy gradients, approximates an expectation by averaging samples, exactly what every simulation in this chapter did. And variance reappears as the noise in those estimates, which is why variance reduction is a research field of its own. Expectation and variance are the two numbers AI optimizes and fights.

🐍

Average random variables in Python

The companion notebook builds the dice-sum PMF and plots it, computes E[X] = 7 and watches a running sample mean converge to it, measures the variance two ways (5.833, so SD ≈ 2.42), demonstrates linearity of expectation on the dependent matching problem, and compares two models by their expected loss, the quantity training minimizes.

📓 View Notebook (code & outputs) ▶ Open in Colab ⬇ View / Download on GitHub

View opens the rendered notebook instantly (no setup). Open in Colab runs & edits it live in your browser. To run locally, install numpy and matplotlib and launch jupyter notebook.

🎓 Key Takeaways

  • A random variable maps each outcome to a number; a discrete one is described by its PMF, P(X = x).
  • Expected value E[X] = Σ x P(x) is the probability-weighted average, the balance point, and the long-run mean.
  • Linearity: E[X + Y] = E[X] + E[Y] always, and E[aX + b] = a E[X] + b.
  • Variance Var(X) = E[X²] − μ² measures spread; SD = √Var is in the original units. Var(aX + b) = a² Var(X).
  • In ML/AI, training minimizes an expected loss, RL maximizes expected reward, and Monte Carlo estimates expectations by averaging.
5

Practice Challenges

Five short challenges, beginner to intermediate. Try them on paper or in Python before checking the solutions.

1

Build a PMF

Let X = the number of heads in 3 fair coin flips. Write the PMF for X = 0, 1, 2, 3 and confirm it sums to 1.

Hint: counts 1, 3, 3, 1 over 8 (row 3 of Pascal's triangle).
2

Expected value

Using that PMF, compute E[X], then verify by simulating 100,000 sets of 3 flips.

Hint: for a fair coin, E[heads] = n/2.
3

Variance

Find Var(X) and SD(X) for the head count, using the shortcut E[X²] − (E[X])².

Hint: E[X²] = 3, so Var = 3 − 1.5².
4

Linear transform

A game pays 2X + 1 dollars, where X is one fair die. Find the expected payoff and its variance.

Hint: E[aX+b] = aE[X]+b; Var(aX+b) = a²Var(X).
5

Is the bet worth it?

A $2 lottery ticket pays $100 with probability 0.01, otherwise nothing. Find the expected net gain. Should you play?

Hint: E[net] = 100(0.01) − 2.
Check your work

A fully-worked solutions notebook walks through all five challenges, each verified in code. Try them yourself first, then compare.

📓 View Solutions ▶ Open Solutions in Colab ⬇ View / Download on GitHub
6

Quiz: Test Yourself

Eight quick questions on random variables and expectation. Answer them, hit Check Answers, and keep refining until you score 100%. Your progress is saved, so you can hop back to the chapter and return anytime.