Sign in

Random variables

A random variable assigns a number to each outcome; discrete ones are described by a mass function and sums, continuous ones by a density and integrals.

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

  1. Decide whether the variable is discrete (separate values) or continuous (a whole interval of values).
  2. Describe it: a probability mass function, or PMF, giving P(X=x)P(X = x) for each value, or a probability density function, or PDF, giving f(x)f(x) on the interval.
  3. Check that it is valid: masses sum to 1, or the density integrates to 1. The template raises an error otherwise.
  4. Build the cumulative distribution function, or CDF: the probability of being at or below xx. It is a staircase for a discrete variable and a smooth curve for a continuous one.
  5. Get the probability of a range from the CDF, and quantiles by reading the CDF backwards.
  6. Compute the mean and variance as probability-weighted averages: sums over the PMF or integrals over the PDF.
  7. Sample by feeding uniform random numbers through the inverse CDF.

Watch out for

  • A density value is not a probability. For a continuous variable P(X=x)P(X = x) is zero for every single xx, and the density can be larger than 1.
  • For a discrete variable P(X≤3)P(X \le 3) and P(X<3)P(X < 3) 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: E[X2]\mathbb{E}[X^{2}] is larger than (E[X])2(\mathbb{E}[X])^{2} whenever XX 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

IfUse instead
Outcomes are categories with no numeric meaningBasic probability over events, or encode the categories first
You need to describe two or more quantities togetherJoint and marginal probability
The quantity changes over timeStochastic processes or Markov chains

Math foundations

  1. Mass function and density

    ∑xP(X=x)=1or∫−∞∞f(x) dx=1,f(x)≥0\sum_{x} P(X = x) = 1 \qquad \text{or} \qquad \int_{-\infty}^{\infty} f(x)\,dx = 1, \quad f(x) \ge 0

    Total probability is 1 in both cases. The discrete case adds point masses and the continuous case measures area under the density.

  2. Cumulative distribution function

    F(x)=P(X≤x)=∑t≤xP(X=t)orF(x)=∫−∞xf(t) dtF(x) = P(X \le x) = \sum_{t \le x} P(X = t) \qquad \text{or} \qquad F(x) = \int_{-\infty}^{x} f(t)\,dt

    The probability accumulated up to xx. It rises from 0 to 1 and never decreases. For a continuous variable the density is its slope.

  3. Probability of a range

    P(a≤X≤b)=F(b)−F(a)=∫abf(x) dxP(a \le X \le b) = F(b) - F(a) = \int_{a}^{b} f(x)\,dx

    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.

  4. Expectation

    E[g(X)]=∑xg(x) P(X=x)orE[g(X)]=∫g(x) f(x) dx\mathbb{E}[g(X)] = \sum_{x} g(x)\,P(X = x) \qquad \text{or} \qquad \mathbb{E}[g(X)] = \int g(x)\,f(x)\,dx

    The long-run average of g(X)g(X), with each value weighted by how likely it is. Taking g(x)=xg(x) = x gives the mean μ\mu.

  5. Variance

    Var⁡(X)=E[(X−μ)2]=E[X2]−μ2\operatorname{Var}(X) = \mathbb{E}\big[(X - \mu)^{2}\big] = \mathbb{E}[X^{2}] - \mu^{2}

    The average squared distance from the mean. Its square root, the standard deviation, is in the same units as XX.

  6. Quantiles and inverse transform sampling

    Q(u)=F−1(u),U∼Uniform⁡(0,1) ⟹ Q(U)  has CDF FQ(u) = F^{-1}(u), \qquad U \sim \operatorname{Uniform}(0, 1) \ \Longrightarrow\ Q(U) \ \text{ has CDF } F

    The quantile function answers which value has a share uu of the probability below it. Feeding uniform random numbers through it produces samples of XX, which is how sample works for ContinuousRV.

  7. Sum of independent discrete variables

    P(X+Y=s)=∑xP(X=x) P(Y=s−x)P(X + Y = s) = \sum_{x} P(X = x)\,P(Y = s - x)

    Every way of splitting the total ss between the two variables contributes. This operation is called a convolution of the two mass functions.

Symbols

X, YX,\ Y
random variables
x, t, sx,\ t,\ s
particular numeric values
P(X=x)P(X = x)
the probability mass at xx
f(x)f(x)
the probability density at xx
F(x)F(x)
the cumulative distribution function
a, ba,\ b
the ends of a range
gg
any function applied to the variable
μ\mu
the mean E[X]\mathbb{E}[X]
Q(u)Q(u)
the quantile function, the inverse of FF
UU
a uniform random number between 0 and 1

Worked by hand

Compare a fair die, which takes the values 1 to 6 with probability 1/61/6 each, with a continuous variable that is uniform on [0,6][0, 6] with density 1/61/6.

E[Xdie]=1+2+3+4+5+66=3.5,E[Xdie2]=916≈15.167\mathbb{E}[X_{\text{die}}] = \frac{1 + 2 + 3 + 4 + 5 + 6}{6} = 3.5, \qquad \mathbb{E}[X_{\text{die}}^{2}] = \frac{91}{6} \approx 15.167
Var⁡(Xdie)=15.167−3.52=2.917\operatorname{Var}(X_{\text{die}}) = 15.167 - 3.5^{2} = 2.917
E[Xunif]=∫06x6 dx=3,Var⁡(Xunif)=6212=3\mathbb{E}[X_{\text{unif}}] = \int_{0}^{6} \frac{x}{6}\,dx = 3, \qquad \operatorname{Var}(X_{\text{unif}}) = \frac{6^{2}}{12} = 3
P(Xdie=3)=16,P(Xunif=3)=0,P(2.5≤Xunif≤3.5)=16P(X_{\text{die}} = 3) = \frac{1}{6}, \qquad P(X_{\text{unif}} = 3) = 0, \qquad P(2.5 \le X_{\text{unif}} \le 3.5) = \frac{1}{6}

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 1
Read 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

  1. 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.

  2. 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 Q(U)≤xQ(U) \le x. That happens exactly when U≤F(x)U \le F(x), and a uniform number is below a level with probability equal to that level.

  3. 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.

  4. You tabulate a standard normal density on [−3,3][-3, 3] 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.

  5. Is E[1/X]\mathbb{E}[1 / X] equal to 1/E[X]1 / \mathbb{E}[X] 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 1/x1/x curves upward, so averaging after applying it gives more weight to the small values.