Overview
A random variable is a number whose value depends on chance, such as the face of a die or the height of a person. If it can take only separate values, it is discrete, and you describe it by listing each value with its probability. If it can take any value in a range, it is continuous. Then every single exact value has probability zero, so you describe it by a density: a curve whose area over an interval is the probability of landing there. The questions are the same in both cases (how likely is a range, what is the average, how spread out is it) and the answers have the same form, with sums on one side and integrals on the other.
A short history
Early probability spoke of events and games. In the 1800s writers such as Pafnuty Chebyshev worked with random quantities that had means and variances, which made results such as his inequality possible. Andrey Kolmogorov's 1933 foundations defined a random variable precisely as a function from outcomes to numbers. That one definition covers discrete and continuous cases and underlies all of statistics.
How it works
- Decide whether the variable is discrete (separate values) or continuous (a whole interval of values).
- Describe it: a probability mass function, or PMF, giving for each value, or a probability density function, or PDF, giving on the interval.
- Check that it is valid: masses sum to 1, or the density integrates to 1. The template raises an error otherwise.
- Build the cumulative distribution function, or CDF: the probability of being at or below . It is a staircase for a discrete variable and a smooth curve for a continuous one.
- Get the probability of a range from the CDF, and quantiles by reading the CDF backwards.
- Compute the mean and variance as probability-weighted averages: sums over the PMF or integrals over the PDF.
- Sample by feeding uniform random numbers through the inverse CDF.
Watch out for
- A density value is not a probability. For a continuous variable is zero for every single , and the density can be larger than 1.
- For a discrete variable and differ by the mass at 3. For a continuous variable they are equal.
- The mean of a function is not the function of the mean: is larger than whenever varies.
- ContinuousRV tabulates the density on a finite grid over a finite interval. A density with an infinite range must be cut where the tails are negligible, and a sharp spike needs a finer grid.
- Adding two DiscreteRV objects assumes they are independent. The sum of dependent variables has a different distribution.
Use cases
When to use it
Any time a quantity is uncertain and you need its average, spread or tail probabilities, and as the vocabulary for every statistical model that follows.
In industry
- Insurance
- Claim count is treated as a discrete random variable and claim size as a continuous one, and their means and variances set premiums and reserves.
- Manufacturing
- A part's measured dimension is a continuous random variable, and the share outside tolerance is found by integrating its density.
- Machine learning
- Features, labels and model outputs are all treated as random variables, which is what allows expected loss to be defined and minimised.
Choosing it: what must hold
- A numeric quantity attached to each outcome of a random process.
- Knowing whether it is discrete, which uses a mass function and sums, or continuous, which uses a density and integrals.
- A distribution for it, given by a formula or estimated from data.
When to choose something else
| If | Use instead |
|---|---|
| Outcomes are categories with no numeric meaning | Basic probability over events, or encode the categories first |
| You need to describe two or more quantities together | Joint and marginal probability |
| The quantity changes over time | Stochastic processes or Markov chains |
Math foundations
Mass function and density
Total probability is 1 in both cases. The discrete case adds point masses and the continuous case measures area under the density.
Cumulative distribution function
The probability accumulated up to . It rises from 0 to 1 and never decreases. For a continuous variable the density is its slope.
Probability of a range
For a continuous variable. Probability is area under the density between the two ends. For a discrete variable, add the masses of the values in the range, including the ends.
Expectation
The long-run average of , with each value weighted by how likely it is. Taking gives the mean .
Variance
The average squared distance from the mean. Its square root, the standard deviation, is in the same units as .
Quantiles and inverse transform sampling
The quantile function answers which value has a share of the probability below it. Feeding uniform random numbers through it produces samples of , which is how sample works for ContinuousRV.
Sum of independent discrete variables
Every way of splitting the total between the two variables contributes. This operation is called a convolution of the two mass functions.
Symbols
- random variables
- particular numeric values
- the probability mass at
- the probability density at
- the cumulative distribution function
- the ends of a range
- any function applied to the variable
- the mean
- the quantile function, the inverse of
- a uniform random number between 0 and 1
Worked by hand
Compare a fair die, which takes the values 1 to 6 with probability each, with a continuous variable that is uniform on with density .
The same questions are answered with a sum on one side and an integral on the other. The die has real mass at 3, while the continuous variable has none at any single point and needs an interval.
Visual example
Loading the example.
Try this
- With the fair die, set a and b both to 3: the probability is 1/6. Switch to the uniform variable and it drops to 0.
- Keep the uniform variable and set a = 2.5, b = 3.5 to get 1/6 back from a range.
- Choose the sum of two dice and widen the range until it holds half the probability.
Code sample
import numpy as np
from impl import DiscreteRV, ContinuousRV
die = DiscreteRV([1, 2, 3, 4, 5, 6])
die.mean(), die.variance() # 3.5, 2.9167
(die + die).pmf(7) # 0.1667
wait = ContinuousRV(lambda x: 2.0 * np.exp(-2.0 * x), 0.0, 20.0) # exponential, rate 2
wait.prob(0.0, 1.0) # 0.8647 = 1 - exp(-2)
wait.quantile(0.5) # 0.3466 = ln(2) / 2
wait.pdf(0.0) # 2.0: a density can exceed 1Read the implementation (147 lines)
"""Random variables: discrete and continuous.
`DiscreteRV` is a list of values with a probability mass function. `ContinuousRV` is a probability density
function on an interval, tabulated on a grid. Both answer the same questions (probability of a range, CDF,
quantile, mean, variance, expectation of a function, sampling), which makes the contrast plain: sums over a
PMF on one side, integrals over a PDF on the other.
"""
from __future__ import annotations
import numpy as np
try:
from .config import RandomVariablesConfig
except ImportError: # run from the template's own folder
from config import RandomVariablesConfig
class DiscreteRV:
"""A random variable taking finitely many numeric values.
values: array (k,) of distinct numbers.
probs: array (k,) of probabilities summing to 1; None means equally likely.
"""
def __init__(self, values, probs=None, config: RandomVariablesConfig | None = None) -> None:
self.config = config or RandomVariablesConfig()
values = np.asarray(values, dtype=float).ravel()
probs = np.full(values.size, 1.0 / max(values.size, 1)) if probs is None else np.asarray(probs, dtype=float).ravel()
if values.size == 0 or values.shape != probs.shape:
raise ValueError("values and probs must be non-empty and of equal length")
if np.unique(values).size != values.size:
raise ValueError("values must be distinct")
if np.any(probs < 0) or abs(probs.sum() - 1.0) > self.config.tolerance:
raise ValueError("probs must be non-negative and sum to 1")
order = np.argsort(values)
self.values, self.probs = values[order], probs[order] / probs.sum()
self.rng = np.random.default_rng(self.config.seed)
def pmf(self, x) -> np.ndarray:
"""P(X = x) for each x (any shape); 0 for numbers the variable never takes."""
x = np.asarray(x, dtype=float)
idx = np.clip(np.searchsorted(self.values, x), 0, self.values.size - 1)
return np.where(self.values[idx] == x, self.probs[idx], 0.0)
def cdf(self, x) -> np.ndarray:
"""P(X <= x): a step function that jumps at each value."""
cumulative = np.concatenate([[0.0], np.cumsum(self.probs)])
return cumulative[np.searchsorted(self.values, np.asarray(x, dtype=float), side="right")]
def prob(self, low: float, high: float) -> float:
"""P(low <= X <= high), both ends included."""
return float(self.probs[(self.values >= low) & (self.values <= high)].sum())
def expectation(self, func=None) -> float:
"""E[f(X)] = sum f(x) P(X = x). With no function, the mean."""
fx = self.values if func is None else np.asarray(func(self.values), dtype=float)
return float(np.dot(fx, self.probs))
def mean(self) -> float:
return self.expectation()
def variance(self) -> float:
return self.expectation(lambda v: (v - self.mean()) ** 2)
def quantile(self, q: float) -> float:
"""Smallest value x with P(X <= x) >= q."""
if not 0 <= q <= 1:
raise ValueError("q must lie in [0, 1]")
idx = int(np.searchsorted(np.cumsum(self.probs), q - 1e-12, side="left"))
return float(self.values[min(idx, self.values.size - 1)])
def sample(self, n: int) -> np.ndarray:
"""n independent draws, array (n,)."""
return self.rng.choice(self.values, size=n, p=self.probs)
def transform(self, func) -> "DiscreteRV":
"""Distribution of Y = f(X). Values that map to the same y have their probabilities added."""
y = np.asarray(func(self.values), dtype=float)
new_values, inverse = np.unique(y, return_inverse=True)
return DiscreteRV(new_values, np.bincount(inverse, weights=self.probs), self.config)
def __add__(self, other: "DiscreteRV") -> "DiscreteRV":
"""Distribution of the sum of two independent variables (the convolution of their PMFs)."""
sums = (self.values[:, None] + other.values[None, :]).ravel()
weights = np.outer(self.probs, other.probs).ravel()
new_values, inverse = np.unique(np.round(sums, 12), return_inverse=True)
return DiscreteRV(new_values, np.bincount(inverse, weights=weights), self.config)
class ContinuousRV:
"""A random variable with density `pdf` on the interval [low, high].
pdf: vectorized function, array -> array of non-negative densities. It must integrate to 1 over
[low, high] within config.tolerance, so cut an infinite range where the tail mass is negligible.
The density is tabulated on config.grid_size points; integrals use the trapezoidal rule.
"""
def __init__(self, pdf, low: float, high: float, config: RandomVariablesConfig | None = None) -> None:
self.config = config or RandomVariablesConfig()
if not high > low:
raise ValueError("high must be greater than low")
self.low, self.high = float(low), float(high)
self.grid = np.linspace(self.low, self.high, self.config.grid_size)
self.density = np.asarray(pdf(self.grid), dtype=float)
if self.density.shape != self.grid.shape or np.any(self.density < 0) or not np.all(np.isfinite(self.density)):
raise ValueError("pdf must return one finite non-negative density per grid point")
dx = self.grid[1] - self.grid[0]
steps = 0.5 * (self.density[1:] + self.density[:-1]) * dx
total = steps.sum()
if abs(total - 1.0) > self.config.tolerance:
raise ValueError(f"pdf must integrate to 1 over [low, high], got {total}")
self._cdf = np.concatenate([[0.0], np.cumsum(steps)]) / total
self.rng = np.random.default_rng(self.config.seed)
def pdf(self, x) -> np.ndarray:
"""Density at x (interpolated on the grid); 0 outside [low, high]. A density is not a probability."""
return np.interp(np.asarray(x, dtype=float), self.grid, self.density, left=0.0, right=0.0)
def cdf(self, x) -> np.ndarray:
"""P(X <= x): the integral of the density up to x."""
return np.interp(np.asarray(x, dtype=float), self.grid, self._cdf, left=0.0, right=1.0)
def prob(self, low: float, high: float) -> float:
"""P(low <= X <= high). A single point has probability 0."""
return float(self.cdf(high) - self.cdf(low))
def expectation(self, func=None) -> float:
"""E[f(X)] = integral of f(x) pdf(x) dx. With no function, the mean."""
fx = self.grid if func is None else np.asarray(func(self.grid), dtype=float)
y = fx * self.density
return float((0.5 * (y[1:] + y[:-1])).sum() * (self.grid[1] - self.grid[0]))
def mean(self) -> float:
return self.expectation()
def variance(self) -> float:
return self.expectation(lambda v: (v - self.mean()) ** 2)
def quantile(self, q) -> np.ndarray:
"""Inverse CDF: the x with P(X <= x) = q, for q in [0, 1] (any shape)."""
q = np.asarray(q, dtype=float)
if np.any((q < 0) | (q > 1)):
raise ValueError("q must lie in [0, 1]")
return np.interp(q, self._cdf, self.grid)
def sample(self, n: int) -> np.ndarray:
"""n independent draws by inverse transform sampling, array (n,)."""
return self.quantile(self.rng.random(n))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build die = DiscreteRV([1, 2, 3, 4, 5, 6]) and check mean, variance and cdf(3). Form two = die + die and print two.pmf(7) and two.quantile(0.5). Then build ContinuousRV(lambda x: np.full_like(x, 1 / 6), 0, 6) and compare prob(2.5, 3.5), mean and variance with the worked example. Draw 10000 values with sample and compare their mean.
Check on learning
- If every single point of a continuous variable has probability zero, how can an interval have positive probability?
A way to think about it
An interval contains uncountably many points, and probabilities are defined as areas, not as sums over points. Think of the length of a line made of points of zero length.
- Why does feeding uniform random numbers through the inverse CDF give samples with the right distribution?
A way to think about it
Ask for the chance that . That happens exactly when , and a uniform number is below a level with probability equal to that level.
- The sum of two dice peaks at 7, though each die alone is flat. Where does the peak come from?
A way to think about it
Count the ways to make each total using the convolution formula. The middle totals can be split in the most ways.
- You tabulate a standard normal density on with the default tolerance. Will ContinuousRV accept it, and what range would you choose?
A way to think about it
The mass outside three standard deviations is about 0.0027. Compare it with the tolerance of 0.0001.
- Is equal to for a fair die? Predict which is larger before computing.
A way to think about it
Work it out with expectation(lambda v: 1 / v). The function curves upward, so averaging after applying it gives more weight to the small values.