Random Variables, Expectation & Variance
Turn random events into numbers, physically balance Expectation on a seesaw, unlock the Linearity superpower, and understand why Variance measures risk
100 guests throw their hats into a giant bin, shake it up, and each guest grabs 1 random hat back. On average, how many guests end up with their OWN hat?
- Think of a Random Variable X simply as a 'number tag' attached to each random outcome (like dollars won or clicks earned).
- Feel Expected Value E[X] physically as the center of gravity (balancing point) of a distribution — and as the long-run average.
- Use Linearity of Expectation E[X + Y] = E[X] + E[Y] (which works EVEN WHEN X and Y ARE DEPENDENT!) to crush hard puzzles in 2 lines.
- Understand Variance Var(X) and Standard Deviation σ as measures of spread/risk, and prove why scaling X by c multiplies Variance by c².
So far we've talked about events like 'Rain' or 'King of Hearts'. To do machine learning, finance, or data science, we attach a number to every outcome (dollars won, clicks earned, milliseconds of latency). Once outcomes become numbers, two questions tell you almost everything about the game: Where is the center (Expected Value)? and How bumpy is the ride (Variance)?
1. Random Variables & Expected Value = The Balance Point!
Imagine a carnival spinner with 4 equal slices: three slices pay $0, and one golden slice pays $20. The carnival host charges $6 to spin. Should you play?
Think about playing 400 times: about 300 times you win $0, and about 100 times you win $20 (total $2,000 across 400 spins = $5 per spin on average). Paying $6 for a game worth $5 on average means you'll lose $1 per spin in the long run! That $5 is the Expected Value !
Expected Value Is Simply a Weighted Average!
Multiply each possible payout by how likely it is , and add them up:
- For our spinner: \mathbb{E}[X] = (\0)\frac{3}{4} + ($20)\frac{1}{4} = \mathbf{$5}$.
- For a fair 6-sided die: .
Feel It Physically: Expectation = Center of Mass!
Imagine placing physical weights proportional to along a wooden plank labeled 1, 2, 3, 4, 5, 6. The exact spot where you put a triangle fulcrum so the plank balances perfectly level IS ! Try balancing the live seesaw below right now!
Stack probability blocks on numbers 1–6, then slide the triangle fulcrum underneath until the beam balances perfectly flat! The balancing point IS the Expected Value E[X].
Pause & Check: A lottery scratch-off costs $2. 99% of tickets win $0, and 1% win $100. What is your expected PAYOUT (before subtracting the $2 ticket price)?
A loaded 4-sided die lands on 1 (prob 0.1), 2 (prob 0.2), 3 (prob 0.3), and 4 (prob 0.4). Compute its Expected Value E[X] and Cumulative Probability F(2) = P(X ≤ 2).
2. The Ultimate Cheat Code: Linearity of Expectation
If I ask you for the average sum of rolling 10 dice, would you build a massive table of all combinations? NO! You'd instantly say: "One die averages 3.5, so 10 dice average !"
Now here is the jaw-dropping twist that makes probability experts look like wizards: that exact shortcut STILL WORKS even when the random variables are messy and DEPENDENT on each other!
Linearity of Expectation (Works ALWAYS — Independence NOT Required!)
Combined with Indicator Variables (a tiny on/off switch that equals if guest wins and otherwise, so !), you can now solve our scary 100-Hat Party Puzzle in 4 tiny steps!
Solving the 100-Hat Puzzle in 30 Seconds (Indicator Trick!)
100 guests grab 1 random hat each from a pile. What is the expected number of guests who get their own hat back? Notice the picks are DEPENDENT (if I grab your hat, you definitely can't grab your hat!).
Define if Guest # gets their OWN hat, and otherwise. Then the total number of matches in the room is simply:
You flip a fair coin 5 times (e.g., H-H-T-H-H). How many adjacent pairs of flips (like positions 1&2, 2&3, 3&4, 4&5) are EXPECTED to be 'HH'?
3. Variance & Standard Deviation — Measuring Risk & Spread
Compare two job offers that BOTH have an Expected Value of $100,000/year:
- Job A (Steady Salary): You get $100,000 guaranteed (100% chance).
- Job B (Wild Startup Bet): 50% chance you make $0, 50% chance you make $200,000!
Both jobs have the exact same Expected Value ($100k) — yet they feel completely different! Expected value tells you the center; Variance and Standard Deviation measure the roller-coaster risk around that center!
Why We Square the Deviations (And Take Square Root at the End!)
If you just averaged the signed distances from the mean, the +\100k-$100kon Job B would **cancel out to zero**! So we **square** every distance first (making negatives positive AND punishing huge outliers extra hard!): $$\operatorname{Var}(X) = \mathbb{E}[(X - \mu)^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2$$ Because squaring turns dollars into *dollars-squared*, we take the square root to get back into human-friendly units — the **Standard Deviation\sigma = \sqrt{\operatorname{Var}(X)}$**!
- Job A: \sigma = \mathbf{\0}$ (zero risk!).
- Job B: \sigma = \mathbf{\100{,}000}$ (huge swings!).
The Two Scaling Rules Every Interview Tests
- Adding a constant shifts the whole curve — spread DOES NOT change: (Giving everyone a $5,000 bonus raises the average by $5,000, but doesn't change the gap between salaries!)
- Multiplying by stretches distances by , so SQUARED distances stretch by : (Unlike Expectation, Variance ONLY adds when and are uncorrelated / independent!)
'Mean of the Square MINUS Square of the Mean' — the fastest hand-calculation formula in probability!
Square every outcome x FIRST (turning 1, 2, 3 into 1, 4, 9), THEN take their weighted average!
A game has E[X] = 10 and Var(X) = 4 (SD = 2). The casino triples every prize AND charges a $5 entry fee: Y = 3X − 5. Find E[Y], Var(Y), and SD(Y).
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Because 'Expected Value' is a slightly misleading historical name! It does NOT mean 'the number you expect to see on one roll' — it means the average over thousands of rolls (and the exact balancing point on a seesaw). Just like the average family can have 2.3 kids even though nobody has 0.3 of a kid!
Expected Loss (Risk Minimization) in ML
Training a neural net literally minimizes Expected Loss E[L(y, f(x))] approximated by the empirical average over mini-batches!
Bias–Variance Tradeoff
Total test MSE splits cleanly into Bias² + Variance + Noise using the exact E[X²] = Var(X) + (E[X])² identity!
Reinforcement Learning Rewards & Value Functions
An RL agent's Value Function V(s) = E[Σ γ^t R_t | s] is literally the Expected Value of future discounted rewards!
BatchNorm & LayerNorm in Deep Learning
Every Transformer block subtracts μ = E[x] and divides by σ = √Var(x) so activations stay centered at 0 with spread 1!
import numpy as np
# 1. Exact E[X], Var(X), and SD(X) for any discrete PMF
outcomes = np.array([1, 2, 3, 4, 5, 6], dtype=float)
probs = np.array([0.05, 0.05, 0.10, 0.10, 0.20, 0.50]) # loaded die!
mean = float(np.sum(outcomes * probs))
e_x2 = float(np.sum((outcomes ** 2) * probs))
var = e_x2 - mean ** 2
print(f"Loaded die: E[X]={mean:.3f}, Var(X)={var:.3f}, SD={np.sqrt(var):.3f}")
# 2. Verify the 100-Hat Problem (E[matches] = 1.0 regardless of N!)
rng = np.random.default_rng(42)
N, trials = 100, 20_000
matches = [int(np.sum(rng.permutation(N) == np.arange(N))) for _ in range(trials)]
print(f"100-Hat simulation over {trials} parties: average matches = {np.mean(matches):.3f}")