3 Discrete random variables
An experiment often produces a complicated outcome, but our question concerns a numerical feature of that outcome. A random variable translates the experiment into a number. This lets us use algebra to combine quantities and calculate their distributions.
3.1 Random variables and their distributions
A real-valued random variable is a measurable function \(X:\Omega\to\mathbb R\). Measurability means that inverse images of Borel sets are events, so expressions such as \(\Pr(X\le x)\) are well-defined. For a discrete random variable, the range can be taken to be finite or countably infinite. Its probability mass function (PMF) is
\[ p_X(x)=\Pr(X=x), \qquad p_X(x)\ge0,\qquad\sum_xp_X(x)=1. \]
The sum is over the support (the possible values with positive mass). Distinct events \(\{X=x\}\) are disjoint, so summing their weights gives probabilities of more general events. For example, \(\Pr(2\le X\le4)=\sum_{x=2}^4p_X(x)\) when \(X\) is integer-valued.
The cumulative distribution function (CDF) is defined for every real \(t\):
\[ F_X(t)=\Pr(X\le t)=\sum_{x\le t}p_X(x). \]
It is nondecreasing and right-continuous, tends to zero at \(-\infty\) and one at \(+\infty\), and satisfies \(\Pr(a<X\le b)=F_X(b)-F_X(a)\). For integer-valued \(X\), \(p_X(k)=F_X(k)-F_X(k-1)\). An atom is visible as a jump in the CDF rather than a region of area.
3.1.1 Worked example: number of retries
A service records the number of retries needed for a completed transaction:
| \(x\) | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| \(p_X(x)\) | 0.60 | 0.25 | 0.10 | 0.05 |
| \(F_X(x)\) | 0.60 | 0.85 | 0.95 | 1.00 |
The probability of at most one retry is \(F_X(1)=0.85\); the probability of more than one is \(1-0.85=0.15\). The CDF is constant between adjacent integers. In particular, \(F_X(1.8)=0.85\).

3.2 Expectation, moments and variance
When \(\sum_x |x|p_X(x)<\infty\), the expectation (mean) is
\[ \mu=\operatorname{E}[X]=\sum_x xp_X(x). \]
For a function \(g\), the law of the unconscious statistician (LOTUS) states that \(\operatorname{E}[g(X)]=\sum_xg(x)p_X(x)\) whenever the expression is integrable. This follows by grouping all values of \(X\) that map to the same value of \(g(X)\) and then summing their probabilities. We do not need to calculate the distribution of \(g(X)\) first.
Linearity of expectation is especially useful:
\[ \operatorname{E}[aX+bY+c]=a\operatorname{E}[X]+b\operatorname{E}[Y]+c. \]
It holds whether or not \(X\) and \(Y\) are independent. For a finite space, expand the expectation as a sum over outcomes in \(\Omega\) and distribute the coefficients. For integrable variables on a more general space, the same identity follows from linearity of integration.
Variance measures average squared distance from the mean:
\[ \begin{aligned} \operatorname{Var}(X) &=\operatorname{E}[(X-\mu)^2]\\ &=\operatorname{E}[X^2]-2\mu\operatorname{E}[X]+\mu^2\\ &=\operatorname{E}[X^2]-\mu^2. \end{aligned} \]
It is nonnegative, and equals zero precisely when \(X=\mu\) almost surely. From its definition \(\operatorname{Var}(aX+b)=a^2\operatorname{Var}(X)\). The standard deviation \(\sigma=\sqrt{\operatorname{Var}(X)}\) has the same units as \(X\).
For the retry example, \(\operatorname{E}[X]=0.25+0.20+0.15=0.60\), and \(\operatorname{E}[X^2]=0.25+0.40+0.45=1.10\). Therefore \(\operatorname{Var}(X)=1.10-0.60^2=0.74\). No single transaction has \(0.60\) retries; the mean is a long-run average, not a required attainable outcome.
Indicator trick. If \(I_A=\mathbf 1\{A\}\), then \(\operatorname{E}[I_A]=\Pr(A)\). Write a count as a sum of indicators and calculate its mean one event at a time.
3.3 Bernoulli and binomial models
A Bernoulli random variable takes \(1\) with probability \(p\) and \(0\) with probability \(1-p\). Its mean is \(p\), and since \(X^2=X\), its variance is \(p-p^2=p(1-p)\).
Let \(X_1,\dots,X_n\) be independent Bernoulli variables with the same parameter \(p\). Their sum \(S_n=\sum_i X_i\) is binomial:
\[ \Pr(S_n=k)=\binom nk p^k(1-p)^{n-k}, \quad k=0,\dots,n. \]
Derivation. A particular sequence with \(k\) successes has probability \(p^k(1-p)^{n-k}\) by independence. Exactly \(\binom nk\) sequences have this count. Add their disjoint probabilities. Normalization follows from the binomial theorem \((p+(1-p))^n=1\).
Linearity gives \(\operatorname{E}[S_n]=np\). For independent variables the cross-covariances vanish; hence \(\operatorname{Var}(S_n)=np(1-p)\) (proved generally in Chapter 5).
For 12 independent transactions with probability \(0.2\) of needing an additional check, the number of checks has mean \(2.4\) and variance \(1.92\). The probability of exactly two is \(\binom{12}{2}(0.2)^2(0.8)^{10}\). A binomial model requires a fixed number of trials, identical probabilities, and independence. If transactions share a hidden load condition, these assumptions may fail.
3.4 Waiting for the first success: geometric distribution
Suppose independent Bernoulli trials continue until the first success. The waiting time \(T\) has support \(1,2,\ldots\) and
\[ \Pr(T=k)=(1-p)^{k-1}p,\qquad \Pr(T>k)=(1-p)^k. \]
The tail event means that all first \(k\) trials fail. This yields the memoryless property:
\[ \Pr(T>s+t\mid T>s)=\frac{(1-p)^{s+t}}{(1-p)^s} =(1-p)^t=\Pr(T>t) \]
for nonnegative integers \(s,t\) and \(0<p<1\). For a positive integer-valued variable, \(T=\sum_{k=0}^\infty\mathbf{1}\{T>k\}\). Nonnegative summation allows expectation to pass through the sum:
\[ \operatorname{E}[T]=\sum_{k=0}^\infty(1-p)^k=\frac1p. \]
Writing \(q=1-p\), differentiating the geometric series twice (for \(|q|<1\)) gives \(\sum_{k\ge1}k^2q^{k-1}=(1+q)/(1-q)^3\). Thus \(\operatorname{E}[T^2]=(2-p)/p^2\) and \(\operatorname{Var}(T)=(1-p)/p^2\).
Some software defines a geometric variable as failures before success, whose support starts at zero. NumPy and SciPy use the trials convention starting at one in their geometric generators and PMF.
3.5 Rare counts: the Poisson distribution
A nonnegative integer \(X\) has a Poisson distribution with rate parameter \(\lambda>0\) if
\[ \Pr(X=k)=e^{-\lambda}\frac{\lambda^k}{k!},\qquad k=0,1,\ldots. \]
The Taylor series for \(e^\lambda\) gives normalization. To calculate the mean, cancel the factor \(k\):
\[ \begin{aligned} \operatorname{E}[X] &=\sum_{k=1}^\infty k e^{-\lambda}\frac{\lambda^k}{k!}\\ &=\lambda e^{-\lambda}\sum_{j=0}^\infty\frac{\lambda^j}{j!} =\lambda. \end{aligned} \]
Similarly \(\operatorname{E}[X(X-1)]=\lambda^2\), so \(\operatorname{E}[X^2]=\lambda^2+\lambda\) and \(\operatorname{Var}(X)=\lambda\).
One reason the Poisson model arises is the binomial limit. Set \(p_n=\lambda/n\) and fix \(k\). Then
\[ \begin{aligned} \binom nk (\lambda/n)^k(1-\lambda/n)^{n-k} ={}&\frac{\lambda^k}{k!} \left[\prod_{j=0}^{k-1}(1-j/n)\right] (1-\lambda/n)^n(1-\lambda/n)^{-k}\\ &\longrightarrow \frac{\lambda^k}{k!}e^{-\lambda}. \end{aligned} \]
The finite product tends to one and \(n\log(1-\lambda/n)\to-\lambda\). Thus many independent rare opportunities with a fixed expected count lead to a Poisson approximation.
3.6 Sampling without replacement: hypergeometric counts
Suppose a finite population contains \(K\) marked items among \(N\), and sample \(n\) distinct items uniformly. The count \(X\) of marked items obeys
\[ \Pr(X=k)=\frac{\binom Kk\binom{N-K}{n-k}}{\binom Nn}, \]
using zero for impossible terms. Write \(X=\sum_{i=1}^n I_i\), where \(I_i\) indicates a marked item at draw \(i\). Each has mean \(p=K/N\). For \(i\ne j\), \(\operatorname{E}[I_iI_j]=K(K-1)/[N(N-1)]\), so the covariance is \(-p(1-p)/(N-1)\). Summing variances and covariances,
\[ \operatorname{E}[X]=np,\qquad \operatorname{Var}(X)=np(1-p)\frac{N-n}{N-1}. \]
The last factor is the finite-population correction. It tends to one when the sample is small relative to the population, and becomes zero when every item is inspected: there is then no sampling uncertainty.
3.7 Python experiment: comparing a model to simulation
import numpy as np
from scipy.stats import binom, poisson
import matplotlib.pyplot as plt
rng = np.random.default_rng(303)
n, p, N = 80, .035, 60_000
x = np.arange(0, 13)
draws = rng.binomial(n, p, size=N)
empirical = np.bincount(draws, minlength=13)[:13] / N
plt.bar(x-.22, binom.pmf(x, n, p), width=.22, label="Binomial")
plt.bar(x, poisson.pmf(x, n*p), width=.22, label="Poisson")
plt.bar(x+.22, empirical, width=.22, label="Empirical")
plt.xlabel("Number of successes")
plt.ylabel("Probability mass")
plt.legend()
plt.show()
print("Means:", draws.mean(), n*p)
assert abs(draws.mean()-n*p) < .05The two PMFs are close because \(p\) is small and \(np\) remains modest. The simulated probabilities fluctuate around the binomial, which is the actual generating model.
3.8 Practice problems
Work in your browser with Google Colab, or download the notebooks for Jupyter.
Practice notebook
Worked solutions
3.8.1 Exercise 1: Normalize a discrete model
Suppose \(p_X(k)=ck\) for \(k=1,2,3,4\). Determine \(c\), \(\operatorname{E}X\), \(\operatorname{Var}(X)\) and \(F_X(2.5)\).
Normalization gives \(c(1+2+3+4)=1\), so \(c=0.1\). \(\operatorname{E}X=0.1(1+4+9+16)=3\). \(\operatorname{E}X^2=0.1(1+8+27+64)=10\), giving variance \(1\). Finally \(F_X(2.5)=0.1(1+2)=0.3\).
3.8.2 Exercise 2: A binomial tail
Eight independent tests each pass with probability \(0.85\). Find the probability that at least seven pass and the expected number of failures.
Let \(S\sim\operatorname{Bin}(8,0.85)\). Then \(\Pr(S\ge7)=8(0.85)^7(0.15)+(0.85)^8\approx0.6572\). The number of failures is \(8-S\) and has mean \(8-8(0.85)=1.2\).
3.8.3 Exercise 3: Waiting time
Each attempt at sending a packet succeeds independently with probability \(0.4\). Given that the first three attempts fail, find the chance that success first occurs on attempt five. Find the conditional mean number of further attempts needed.
The residual waiting time has the original geometric distribution. Exactly two further attempts means one failure and then success, giving \((0.6)(0.4)=0.24\). Its mean is \(1/0.4=2.5\). Equivalently, \(\Pr(T=5\mid T>3)=0.6^4(0.4)/0.6^3\).
3.8.4 Exercise 4: Python — derive and implement a PMF from scratch
For \(X\sim\operatorname{Bin}(15,0.35)\), implement its PMF with the standard-library combination function. Check normalization, compute the mean and variance using sums (not library moments), and verify them against formulas and SciPy. Simulate 100,000 counts.
Using the PMF, the mean is \(np=5.25\) and variance is \(np(1-p)=3.4125\). The code calculates these independently.
from math import comb
import numpy as np
from scipy.stats import binom
n, p = 15, .35
k = np.arange(n+1)
mass = np.array([comb(n, int(i))*p**i*(1-p)**(n-i) for i in k])
mu = k @ mass
variance = (k-mu)**2 @ mass
assert np.isclose(mass.sum(), 1)
assert np.isclose(mu, n*p)
assert np.isclose(variance, n*p*(1-p))
assert np.allclose(mass, binom.pmf(k, n, p))
rng = np.random.default_rng(305)
draws = rng.binomial(n,p,100_000)
print(mu, variance, draws.mean(), draws.var())The comparison verifies consistency between the formula, the identity for moments, a numerical implementation, and Monte Carlo results.
3.8.5 Exercise 5: Python — quantify a Poisson approximation
Fix \(\lambda=4\). For \(n=10,25,100,500\), let \(Y_n\sim\operatorname{Bin}(n,4/n)\). Compare its PMF to the Poisson(4) PMF using total variation distance \(d_{\mathrm{TV}}=\frac12\sum_k|p(k)-q(k)|\). Use a grid with sufficiently small omitted Poisson tail and plot the distance against \(n\) on log-log axes.
The distance measures the largest possible probability discrepancy over sets of outcomes. On the grid below, the omitted tail is negligible.
import numpy as np
from scipy.stats import binom, poisson
import matplotlib.pyplot as plt
ns = np.array([10, 25, 100, 500])
k = np.arange(0, max(ns)+1)
q = poisson.pmf(k, 4)
assert poisson.sf(k[-1], 4) < 1e-12
dist = np.array([
.5*np.abs(binom.pmf(k, n, 4/n)-q).sum() for n in ns
])
print(np.c_[ns,dist])
assert np.all(np.diff(dist)<0)
plt.loglog(ns, dist, "o-")
plt.xlabel("Binomial trial count")
plt.ylabel("Total variation distance")
plt.show()As \(n\) increases with \(np=4\), the discrepancy decreases, as suggested by the binomial limit.
3.8.6 Exercise 6: Python — the finite-population correction
Sample \(n=5,20,40,60\) items without replacement from a population of 60 items, 18 marked. Calculate and simulate the variance of the marked count for each \(n\). Compare with a binomial variance.
Here \(p=18/60=0.3\) and \(\operatorname{Var}(X)=n(0.3)(0.7)(60-n)/59\). For \(n=60\), the count is always 18.
import numpy as np
rng = np.random.default_rng(306)
N, K = 60, 18
p = K/N
for n in [5,20,40,60]:
expected = n*p*(1-p)*(N-n)/(N-1)
sample = rng.hypergeometric(K,N-K,n,size=80_000)
print(n, "exact", round(expected,4), "sim", round(sample.var(),4),
"with replacement", round(n*p*(1-p),4))
assert abs(sample.var()-expected)<.12With a large sampling fraction, without-replacement sampling induces strong negative dependence. The binomial variance is too large.