Discrete Random Variables
Probability Theory
When Outcomes Are Numbers, Not Just Names
A discrete random variable takes on a countable number of distinct values, each with an associated probability. It transforms qualitative outcomes into quantitative analysis.
- PMF — The probability mass function assigns a probability to each possible value
- CDF — The cumulative distribution function gives P(X ≤ x) for any value
- Expected value — The probability-weighted average of all possible outcomes
- Variance — How much the random variable fluctuates around its expected value
What You'll Learn
- 1Translate a verbal experiment into a discrete random variable with a complete probability mass function
- 2Verify a valid PMF using the non-negativity and unit-sum axioms
- 3Compute expected value and variance by hand and through the E[X²] − (E[X])² shortcut
- 4Connect indicator variables and the four workhorse distributions to real counting scenarios
Probability theory begins with equally spaced coin flips and six-sided dice, but real questions speak in numbers: how many defects come off the line before lunch, how many retries a request needs, how many clicks an ad receives before the budget empties. A discrete random variable is the formal bridge from those countable outcomes to arithmetic. Once an experiment is attached to a function mapping outcomes to numbers, you can average it, measure its spread, and — most powerfully — replace it with a named distribution whose properties arrive from a table instead of from a fresh derivation every time.
From Outcomes to Random Variables
A random variable is a function on the sample space. Flipping three coins produces eight equally likely strings; the random variable counting heads takes values 0 through 3 with probabilities 1/8, 3/8, 3/8, and 1/8. Rolling two dice yields 36 outcomes; the sum ranges from 2 to 12 with the familiar triangular PMF peaking at 7. The choice of is yours, and different choices from the same experiment answer different questions — count of sixes versus sum of pips versus whether any six appeared at all. Discrete means the range is countable: finite, or infinite but listable like the positive integers. Anything measured on a continuum — height, exact waiting time — needs the continuous machinery instead, though binning it into counts brings you right back here.
The Probability Mass Function
The PMF assigns each attainable value its probability and nothing more — the function is zero at every other number. Two axioms certify a valid PMF: for every , and . Software that skips the unit-sum check is how impossible tables slip into production reports. The cumulative distribution function stacks the masses: , a non-decreasing staircase that jumps by exactly at each support point and is flat in between. The CDF works at every real , not just the support, which makes it the safer object for inequalities such as or computed as .
Consider a quality gate where counts rework cycles with PMF , , , . The masses sum to 1.00, so the table is admissible, and the CDF climbs 0.20, 0.50, 0.85, 1.00 at the four support points.
import numpy as np
from scipy import stats
values = np.array([0, 1, 2, 3])
probs = np.array([0.20, 0.30, 0.35, 0.15])
print("PMF check:")
print(f" All probabilities non-negative: {np.all(probs >= 0)}")
print(f" Sum of probabilities: {probs.sum():.4f}")
print("\nCDF (cumulative staircase):")
cumulative = np.cumsum(probs)
for v, cp in zip(values, cumulative):
print(f" F({v}) = P(X <= {v}) = {cp:.2f}")
print(f"\nP(X <= 2) = {cumulative[2]:.2f}")
print(f"P(X > 2) = {1 - cumulative[2]:.2f}")
Expected Value: The Long-Run Average
Expected value is the probability-weighted sum of the support, . It is not a value will probably take — in the rework example, and never equals 1.45 — it is the limit of the sample average as repetitions grow, which makes it the right quantity for budgeting and pricing. A game paying 10 dollars with probability 0.1 returns an average of 1 dollar per play; a game paying 2 dollars with probability 0.6 returns 1.2. Rational players prefer the second despite its smaller jackpot, because expectation, not maximum payout, governs repeated play. Linearity of expectation adds power without any independence requirement: the expected number of aces in five card draws is even though the draws are dependent.
Variance and the Shortcut Formula
Variance measures the typical squared wander around the mean: . Computing it directly is fine for four support points and tedious for forty, which is why the shortcut earns its place in every toolkit. For the rework PMF, , so and the standard deviation is about 0.97 cycles. Note the unit change: variance is in squared cycles, standard deviation returns to cycles, and only the latter can be compared directly to the mean. Expectation of a function of follows the same weighting pattern, , and plugging into that identity is exactly what produces the shortcut.
expected = np.sum(values * probs)
second_moment = np.sum(values ** 2 * probs)
variance_direct = np.sum((values - expected) ** 2 * probs)
variance_shortcut = second_moment - expected ** 2
print(f"E[X] = {expected:.4f}")
print(f"E[X^2] = {second_moment:.4f}")
print(f"Var (direct) = {variance_direct:.4f}")
print(f"Var (shortcut) = {variance_shortcut:.4f}")
print(f"SD(X) = {np.sqrt(variance_direct):.4f}")
Indicator Variables and Functions of X
The simplest discrete random variable is an indicator: equals 1 when a specified event occurs and 0 otherwise. Its PMF is two-point, its expectation is the event probability (), and its variance is — the Bernoulli distribution in miniature. Indicators are additive even when events are not: the total number of successes in trials is the sum of indicators, so its mean is by linearity alone, with no combinatorial argument required. This trick resurfaces in coupon collector problems, occupancy counts, and the derivation of the binomial mean, and it is the reason "count the cases" reasoning stays exact under dependence when you only need the expectation.
| Building block | Range | E[X] | Var(X) |
|---|---|---|---|
| Indicator of event A | 0 or 1 | P(A) | P(A)(1 − P(A)) |
| Bernoulli(p) | 0 or 1 | p | p(1 − p) |
| Sum of n indicators (binomial) | 0 to n | np | np(1 − p) |
| g(X) for any function g | g of support | sum of g(x)p(x) | E[g(X)²] − E[g(X)]² |
The Four Workhorse Discrete Distributions
Most applied counting problems map onto one of four named families, and recognizing the mapping is the entire skill. Bernoulli covers a single yes/no trial — a click, a defect, a conversion. Binomial counts successes across independent identical trials. Poisson models rare event counts over continuous exposure such as calls per hour or typos per page, with mean equal to variance by construction. Geometric measures the waiting time until the first success, supported on 1, 2, 3, and so on. Each family ships closed-form means and variances, so once the model fits, the summary statistics arrive without simulation.
| Distribution | When it fits | PMF | Mean | Variance |
|---|---|---|---|---|
| Bernoulli(p) | One binary trial | |||
| Binomial(n, p) | n independent trials | |||
| Poisson(λ) | Rare counts per exposure | |||
| Geometric(p) | Wait until first success |
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
x = np.arange(0, 11)
axes[0, 0].bar(x, stats.binom.pmf(x, n=10, p=0.5), color='steelblue')
axes[0, 0].set_title('Binomial(n=10, p=0.5)')
axes[0, 1].bar(np.arange(0, 12), stats.poisson.pmf(np.arange(0, 12), mu=3), color='steelblue')
axes[0, 1].set_title('Poisson(lambda=3), mean equals variance')
axes[1, 0].bar(np.arange(1, 11), stats.geom.pmf(np.arange(1, 11), p=0.3), color='steelblue')
axes[1, 0].set_title('Geometric(p=0.3), wait for first success')
axes[1, 1].bar([0, 1], [0.3, 0.7], color='steelblue')
axes[1, 1].set_title('Bernoulli(p=0.7)')
for ax in axes.flat:
ax.set_xlabel('x')
ax.set_ylabel('P(X = x)')
plt.tight_layout()
plt.show()
lam = 3
print(f"Poisson(3): mean = {lam}, variance = {lam}, SD = {np.sqrt(lam):.3f}")
print(f"P(X >= 6) = {1 - stats.poisson.cdf(5, mu=3):.4f}")
Discrete Random Variables in Machine Learning
Classifier outputs are discrete random variables wearing a modern costume. Softmax converts logits into a PMF over class labels, argmax picks the mode, and expected cost under that PMF is the quantity decision theory actually optimizes. Autoregressive language models treat the next token as a discrete variable conditioned on context, and training minimizes the expected negative log-likelihood — the cross-entropy between the empirical PMF of observed tokens and the model's predicted PMF. Count models still matter too: Poisson regression targets event rates, negative binomial layers absorb over-dispersed counts, and Markov chains move probability mass across discrete states at every step.
logits = np.array([2.0, 1.0, 0.5, 0.1])
softmax = np.exp(logits) / np.sum(np.exp(logits))
print(f"Logits: {logits}")
print(f"Softmax: {softmax.round(4)} (sums to {softmax.sum():.4f})")
print(f"Predicted class: {np.argmax(softmax)}")
costs = np.array([0.0, 1.0, 5.0, 20.0]) # cost of each wrong class
expected_cost = np.sum(softmax * costs)
print(f"Expected cost under the predicted PMF: {expected_cost:.3f}")
arrivals = stats.poisson.rvs(5, size=10, random_state=0)
print(f"\nPoisson(5) arrivals: {arrivals}")
print(f"Sample mean {arrivals.mean():.2f} vs theoretical 5.00")
💡Check the support before you trust a mean
Common Mistakes
Reading E[X] as the most likely value of X
Fix: The expectation is a long-run average and need not lie on the support; the mode — the value with the largest PMF — is a different summary.
Forgetting to normalize an ad hoc probability table
Fix: Verify the masses sum to one before computing moments; a silent 0.97 total distorts every expectation downstream.
Applying the binomial to dependent trials
Fix: Successes must be independent with constant probability; otherwise reach for Poisson, beta-binomial, or a simulation.
Best Practices
- Validate PMFs with assertions on non-negativity and unit sum at ingestion time
- Use the E[X²] − (E[X])² shortcut in code but keep the direct sum as a unit test
- Prefer named SciPy distributions over hand-rolled PMFs when the scenario matches a standard family
- Store the CDF for inequality queries; it answers tail questions in one lookup
Key Takeaways
- A discrete random variable maps countable outcomes to numbers with a PMF that is non-negative and sums to one
- The CDF is the running total of PMF mass and answers every inequality probability directly
- Expected value is the probability-weighted average; variance equals E[X²] minus the square of that average
- Bernoulli, binomial, Poisson, and geometric cover most applied counting scenarios with ready-made formulas
Frequently Asked Questions
What is the difference between a PMF and a PDF?
A PMF assigns probability to individual values of a discrete variable and sums to one; a probability density function describes a continuous variable, where the density at a single point is zero and probabilities come from integrating over intervals. Mixing them — reading a PDF value as a probability — is a classic category error.
Why does Poisson have mean equal to variance?
That equality is the Poisson defining property, and it is also its limitation: real count data often show variance larger than the mean (over-dispersion), which is the signal to switch to a negative binomial or to add random effects. Testing the mean-variance balance is a quick model diagnostic.
Can expected value be infinite?
Yes, for heavy-tailed discrete distributions. A Pareto-like PMF with has finite mean but infinite variance, and slower tails push the mean itself to infinity. When sample averages refuse to stabilize, suspect an infinite or near-infinite first moment before blaming the code.
Interview Questions
Q1: Define a valid probability mass function.
A function p on the countable support of X such that p(x) is greater than or equal to zero for every x, and the sum of p over the support equals exactly one. Both conditions must hold; either alone is insufficient.
Q2: Compute the variance of a Bernoulli(0.3) variable using the shortcut.
E[X] = 0.3 and E[X²] = 0.3 because x² = x on {0, 1}. Var(X) = 0.3 − 0.09 = 0.21, matching p(1 − p).
Q3: How does a softmax output relate to discrete random variables?
Softmax turns logits into a valid PMF over the class set: entries are non-negative and sum to one. The predicted class is the mode, and decision-theoretic outputs such as expected cost are computed by weighting class-specific losses with that PMF.