Random Variables
14 min
A random variable is a numeric outcome of something uncertain — the result of a die roll, tomorrow's stock return, how many bugs are in a release. For a discrete random variable (finite or countable outcomes), the PMF (probability mass function) lists every possible outcome and how likely it is.
# A fair six-sided die
pmf = {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
print(round(sum(pmf.values()), 10)) # 1.0 -- every valid PMF sums to 1 (rounding here just clears floating-point noise like 0.9999999999999999)
Estimating a PMF from data is just counting how often each outcome occurred, then dividing by the total — the empirical distribution.
The expected value E[X] is the probability-weighted average of every possible outcome — not necessarily a value X can actually take (the expected value of a fair die is 3.5, which the die can never actually show).
pmf = {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
expected = sum(value * prob for value, prob in pmf.items())
print(expected) # 3.5
That's the same "weight times value, summed" pattern from the NumPy linear algebra course — expectation is a dot product between outcomes and their probabilities.
Write `pmf_from_counts(counts)`: given a dict of outcome → frequency count, return a dict of outcome → probability (each count divided by the total), with each probability rounded to 4 decimals.
Write `expected_value(pmf)`, where `pmf` is a dict of numeric value → probability. Return the expected value E[X] = Σ (value × probability).
What must the probabilities in a valid PMF (probability mass function) sum to?
You can build a PMF from observed frequency counts and compute a random variable's expected value from its PMF.