Module contents
Lesson 4 of 24Core 95 min

Random variables, laws and distribution functions

A random variable is a measurable function, and its law is the pushforward measure it induces. The distribution function characterizes the law; the quantile function inverts it and enables simulation from a uniform. Classify laws as discrete, absolutely continuous or singular, and interpret σ(X) as the information revealed by X.

After this lesson you can

  • Define a random variable as a measurable function and check measurability using generators.
  • Construct the law of X as a pushforward measure and prove the distribution function determines it.
  • Characterize distribution functions and construct a variable with a given distribution via its quantile function.
  • Implement inverse sampling for discrete, continuous, mixed and singular distributions.
  • Apply the Doob–Dynkin lemma to express σ(X)-measurable variables as functions of X.

Before you start

Motivation: from “what happens” to “what is measured”

Initialize a network with random weights WW and give it a fixed input. Output Y=f(W)Y = f(W) is a random number, and you want the probability it exceeds a threshold: P(Y>t)\Pr(Y > t). But the σ-algebra lesson showed P\Pr is evaluated only on elements of F\mathcal{F}. Set {ω:f(W(ω))>t}\{\omega : f(W(\omega)) > t\} is an event only if there is a reason. For a thousand-layer network you cannot check by hand, so a general answer is needed. That answer is measurability, and the lesson has four interdependent parts.

  1. Measurable functions. Those carrying events back to events through preimages. Nearly everything you program is measurable; the generator criterion checks it with one calculation.
  2. A random variable’s law. A random variable is a measurable function, and its law remembers only how it distributes probability on R\R. Very different variables can have the same law; confusing variable and law is the course’s most common conceptual error.
  3. The distribution function and its inverse. A function FF from the line to [0,1][0, 1] describes an entire law. Its generalized inverse F−1F^{-1} turns a uniform number into a sample from any law. This powers simulation; a modern generative model is the same idea with F−1F^{-1} replaced by a network.
  4. σ(X)\sigma(X) as information. The σ-algebra generated by XX comprises questions XX answers, and the Doob–Dynkin lemma says what can be computed from XX is exactly functions of XX.

Measurable functions

A function between sets with σ-algebras must respect them. The requirement concerns preimages, because they interact well with complements and unions: f−1(Bc)=f−1(B)cf^{-1}(B^c) = f^{-1}(B)^c and f−1(⋃nBn)=⋃nf−1(Bn)f^{-1}\big(\bigcup_n B_n\big) = \bigcup_n f^{-1}(B_n). (Direct images do not satisfy the first, and thus do not work.)

Checking the definition for every Borel set seems impossible, and is unnecessary. It suffices to inspect a generating family.

Proof

(⇒\Rightarrow) is trivial because C⊂E\mathcal{C} \subset \mathcal{E}. (⇐\Leftarrow) Let G={B⊂E:f−1(B)∈F}\mathcal{G} = \{B \subset E : f^{-1}(B) \in \mathcal{F}\}. It is a σ-algebra on EE: f−1(E)=Ω∈Ff^{-1}(E) = \Omega \in \mathcal{F}, and preimages preserve complements and countable unions, which F\mathcal{F} also preserves. It contains C\mathcal{C} by hypothesis, hence σ(C)=E\sigma(\mathcal{C}) = \mathcal{E}. ■\blacksquare

∎

This is the preceding lesson’s “smallest σ-algebra containing C\mathcal{C}” argument, used constantly. Known generators of B(R)\mathcal{B}(\R) yield practical consequences.

Proof

(a) Rays (−∞,t](-\infty, t] generate B(R)\mathcal{B}(\R). (b) 1A−1(B)\ind_A^{-1}(B) is ∅\emptyset, AA, AcA^c or Ω\Omega depending on whether BB contains 00 and 11. (c) If ff is continuous, preimages of open sets are open, and open sets generate B\mathcal{B}. If ff is monotone, the preimage of a ray is an interval, hence Borel. (d) (g∘f)−1(B)=f−1(g−1(B))(g \circ f)^{-1}(B) = f^{-1}(g^{-1}(B)). ■\blacksquare

∎

Measurable functions are closed under operations used to pass to limits, the reason for “σ” in σ-algebra.

Proof

For pair (f,g):Ω→R2(f, g) : \Omega \to \R^2, the preimage of box (a,b]×(c,d](a, b] \times (c, d] is {f∈(a,b]}∩{g∈(c,d]}∈F\{f \in (a, b]\} \cap \{g \in (c, d]\} \in \mathcal{F}, and boxes generate B(R2)\mathcal{B}(\R^2). Thus (f,g)(f, g) is measurable, and f+gf + g and fgfg are its compositions with continuous functions (x,y)↦x+y(x, y) \mapsto x + y and (x,y)↦xy(x, y) \mapsto xy (likewise maximum and absolute value). For suprema, {sup⁡nfn≤t}=⋂n{fn≤t}∈F\{\sup_n f_n \le t\} = \bigcap_n \{f_n \le t\} \in \mathcal{F} and inf⁡nfn=−sup⁡n(−fn)\inf_n f_n = -\sup_n (-f_n). Hence lim sup⁡nfn=inf⁡msup⁡n≥mfn\limsup_n f_n = \inf_m \sup_{n \ge m} f_n and lim inf⁡nfn=sup⁡minf⁡n≥mfn\liminf_n f_n = \sup_m \inf_{n \ge m} f_n are measurable. Finally lim inf⁡<lim sup⁡\liminf < \limsup if and only if a rational qq exists with lim inf⁡<q<lim sup⁡\liminf < q < \limsup, so {lim inf⁡<lim sup⁡}=⋃q∈Q{lim inf⁡<q}∩{lim sup⁡>q}∈F\{\liminf < \limsup\} = \bigcup_{q \in \Q} \{\liminf < q\} \cap \{\limsup > q\} \in \mathcal{F}, and its complement is the set where the limit exists. ■\blacksquare

∎
QuizWhich are measurable?
Let Ω={1,2,3,4}\Omega = \{1, 2, 3, 4\} have σ-algebra F\mathcal{F} generated by partition {1,2},{3,4}\{1, 2\}, \{3, 4\} (its atoms). Which functions Ω→R\Omega \to \R are F\mathcal{F}-measurable?

More than one answer may be correct.

Random variables and their law

With measurable functions, the course’s central definition fits on one line.

Measurability makes P(X∈B)\Pr(X \in B) and P(X≤x)\Pr(X \le x) legitimate: they mean P(X−1(B))\Pr(X^{-1}(B)) and P({ω:X(ω)≤x})\Pr(\{\omega : X(\omega) \le x\}), and those sets belong to F\mathcal{F}. This answers the motivating question: if WW is a random vector and ff is continuous (or a composition of sums, products, ReLU⁡\relu and matrices, which are continuous), then f(W)f(W) is a random variable, and P(f(W)>t)\Pr(f(W) > t) makes sense for every tt.

A random variable is a function: it assigns a number to each outcome ω\omega. But ω\omega rarely matters to us. We care how probability is distributed among values of XX. That is a measure on R\R.

Proof

PX(R)=P(Ω)=1\Pr_X(\R) = \Pr(\Omega) = 1 and PX(B)≥0\Pr_X(B) \ge 0. If B1,B2,…B_1, B_2, \dots are disjoint Borel sets, preimages X−1(Bn)X^{-1}(B_n) are disjoint events and X−1(⨆nBn)=⨆nX−1(Bn)X^{-1}\big(\bigsqcup_n B_n\big) = \bigsqcup_n X^{-1}(B_n), so countable additivity of P\Pr gives it for PX\Pr_X. ■\blacksquare

∎

Law as transported mass

Think of Ω=[0,1]\Omega = [0, 1] with Lebesgue measure as a sand bar of total mass 11 spread uniformly. Function XX moves each grain to its new location in R\R, and the law is the resulting sand distribution. Where XX is nearly flat, many grains land together and sand piles up (high density, and an atom if fully flat). Where XX is steep, grains spread apart and sand thins.

InteractiveLaw as transported mass
Left: X(ω)X(\omega) on Ω=[0,1]\Omega = [0, 1] with uniform mass. Right: its law, with mass stacked by origin
0.250.250.500.500.750.751.001.00ωlaw of Xatom 0.25
  • segment 1
  • segment 2
  • segment 3
  • segment 4
  • preimages of y∗y^*
0.50
Atoms: position (mass)0.30 (0.25)
Mass with a density0.75
Preimages of y∗y^*0.625
Density ∑1/∣X′(ω)∣\sum 1/\abs{X'(\omega)} at y∗y^*1/1.60 = 0.625
P(X≤y∗)\Pr(X \le y^*)0.625
Uniform mass of Ω=[0,1]\Omega = [0, 1] (horizontal axis) travels through function XX to the vertical axis, where the law of XX accumulates (bars at right). Start with the plateau: how much mass does the atom have and which part of Ω\Omega produces it? Choose X(ω)≈ω2X(\omega) \approx \omega^2 and move probe y∗y^*: why does density rise toward 00? Try the ‘tent’: what do two preimages of each y∗y^* mean? Uncheck ‘Join the seams’ to create jumps in XX, and drag segment endpoints to build your own law.

Two examples are solved by hand. With X(ω)=ω2X(\omega) = \omega^2 on ([0,1],λ)([0, 1], \lambda),

P(X≤x)=λ{ω:ω≤x}=x,x∈[0,1],\Pr(X \le x) = \lambda\{\omega : \omega \le \sqrt{x}\} = \sqrt{x}, \qquad x \in [0, 1],

whose derivative 1/(2x)1/(2\sqrt{x}) blows up at 00, where XX is flat. If XX equals cc on a segment of length ℓ\ell of Ω\Omega, the law has an atom at cc with P(X=c)≥ℓ\Pr(X = c) \ge \ell (exactly ℓ\ell if XX does not equal cc elsewhere). Density at yy is generally sum ∑1/∣X′(ω)∣\sum 1/\abs{X'(\omega)} over preimages of yy (as the figure probe reads): the change-of-variables formula proved in random-variable transformations.

A finite law is pure bookkeeping. On the two-dice space sum SS has law PS({k})=P(S=k)\Pr_S(\{k\}) = \Pr(S = k); the next cell calculates it using exact fractions, checks properties of FF seen shortly, and verifies the earlier warning’s practical rule: a function is measurable for a partition if constant on its atoms.

[ ]The image measure on a finite spaceBrowser
from fractions import Fraction as Fr
from itertools import product
from collections import defaultdict

omega = list(product(range(1, 7), repeat=2))              # Ω: 36 resultados de dos dados
P = {w: Fr(1, 36) for w in omega}                          # probabilidad uniforme

def ley(X, P=P):
    """Medida imagen P_X({x}) = P(X^{-1}({x})) de una variable sobre un Ω finito."""
    m = defaultdict(Fr)
    for w, p in P.items():
        m[X(w)] += p
    return dict(sorted(m.items()))

def F(m, x):
    return sum(p for v, p in m.items() if v <= x)

S  = lambda w: w[0] + w[1]            # suma de los dos dados
S2 = lambda w: 14 - w[0] - w[1]       # otra variable sobre el mismo Ω

mS, mS2 = ley(S), ley(S2)
print("ley de S:", {k: str(v) for k, v in mS.items()})
print("S y 14 - S tienen la misma ley:", mS == mS2, "   P(S = 14 - S) =", sum(p for w, p in P.items() if S(w) == S2(w)))
print("F(6) =", F(mS, 6), "  F(5.99) =", F(mS, 5.99), "  salto en 6 =", mS[6])
print("P(3 < S <= 6) = F(6) - F(3) =", F(mS, 6) - F(mS, 3), "=", sum(mS[k] for k in (4, 5, 6)))

# Medibilidad: X es medible respecto de la σ-álgebra de una partición si es constante en cada átomo
def es_medible(X, atomos):
    return all(len({X(w) for w in a}) == 1 for a in atomos)

primero = [frozenset(w for w in omega if w[0] == i) for i in range(1, 7)]    # átomos de σ(primer dado)
for nombre, X in {"primer dado": lambda w: w[0], "su paridad": lambda w: w[0] % 2, "suma S": S}.items():
    print(f"{nombre:12s} medible respecto de σ(primer dado): {es_medible(X, primero)}")

The second line is the counterexample giving the next section its title: SS and 14−S14 - S are different variables on the same space with exactly the same law; they agree only when S=7S = 7, with probability 1/61/6.

A variable is not its law

A law is a measure on R\R; a variable is a function on Ω\Omega. Forgetting the difference causes logical, not computational, errors.

  • U∼Unif⁡(0,1)U \sim \Unif(0, 1) and 1−U1 - U have the same law, and P(U=1−U)=P(U=1/2)=0\Pr(U = 1 - U) = \Pr(U = 1/2) = 0. If Z∼N(0,1)Z \sim \Normal(0, 1), also −Z∼N(0,1)-Z \sim \Normal(0, 1), and Z≠−ZZ \ne -Z except on a null event.
  • Variables on different spaces can share a law: a coin toss and die parity are Bern⁡(1/2)\Bern(1/2) and live on different Ω\Omega.
  • Even with shared Ω\Omega, the law does not remember how XX relates to other variables: (X,X)(X, X) and (X,1−X)(X, 1 - X) with X∼Bern⁡(1/2)X \sim \Bern(1/2) have the same marginals and very different joint laws. The joint law is another measure, on R2\R^2.

For what follows remember that everything depending only on XX (probabilities of events {X∈B}\{X \in B\} and expectations E[g(X)]\E[g(X)] defined with the Lebesgue integral) depends only on PX\Pr_X. Thus Ω\Omega can be forgotten: given any probability μ\mu on R\R, space (R,B(R),μ)(\R, \mathcal{B}(\R), \mu) with X(x)=xX(x) = x has X∼μX \sim \mu. A “distribution” is a probability on R\R, and theory next describes it with a function.

The distribution function

A measure on B(R)\mathcal{B}(\R) is huge, but rays suffice to give its values on all R\R: that is the previous lesson’s uniqueness theorem.

Proof

(1) If x≤yx \le y, {X≤x}⊂{X≤y}\{X \le x\} \subset \{X \le y\}. (2) If xn↓−∞x_n \downarrow -\infty, events {X≤xn}\{X \le x_n\} decrease to ∅\emptyset, and probability continuity from above gives F(xn)→0F(x_n) \to 0. If xn↑∞x_n \uparrow \infty they increase to Ω\Omega, and F(xn)→1F(x_n) \to 1. Since FF is monotone, the limit is sequence-independent. (3) If xn↓xx_n \downarrow x, events {X≤xn}\{X \le x_n\} decrease to {X≤x}\{X \le x\} (a point ω\omega lies in all exactly when X(ω)≤xX(\omega) \le x), and continuity again gives F(xn)→F(x)F(x_n) \to F(x). If xn↑xx_n \uparrow x strictly, {X≤xn}\{X \le x_n\} increases to {X<x}\{X < x\}, so F(x−)=P(X<x)F(x^-) = \Pr(X < x) and difference F(x)−F(x−)F(x) - F(x^-) is P(X=x)\Pr(X = x). The interval formula is P(X≤b)−P(X≤a)\Pr(X \le b) - \Pr(X \le a). Finally, a monotone function has one-sided limits everywhere and its discontinuities are jumps (one-sided limits and monotone functions), and for each kk there are at most kk jumps of size at least 1/k1/k, because all jumps sum to at most 11. A countable union of finite sets is countable. ■\blacksquare

∎

(Some texts use convention P(X<x)\Pr(X < x), left-continuous. Here ≤\le is used because P(a<X≤b)=F(b)−F(a)\Pr(a < X \le b) = F(b) - F(a) and because scipy, numpy and other software use it.)

Uniqueness is already proved. Variables with the same FF have the same law: rays (−∞,x](-\infty, x] form a π-system generating B(R)\mathcal{B}(\R), and π-λ gives uniqueness of probabilities agreeing there. The distribution function determines the law. The remaining converse, which functions are distribution functions, is answered by the figure’s builder: you draw FF and the platform tells you its law.

InteractiveDistribution function builder
F(x)=P(X≤x)F(x) = \Pr(X \le x): drag the knots
F−1(u)=inf⁡{x:F(x)≥u}F^{-1}(u) = \inf\{x : F(x) \ge u\}: the reflection of FF
Frequency of F−1(U1),…,F−1(Un)F^{-1}(U_1), \dots, F^{-1}(U_n) per bin (bars) versus the mass given by FF (marks)
0.300.15
  • FF
  • F−1F^{-1}
  • probe u∗u^*
  • samples
  • exact mass
2.20
0.45
Samples
Mass of the atoms0.45
Mass with a density0.55
Singular mass0.00
F(x∗)F(x^*) and F(x∗−)F(x^{*}-)0.600 and 0.600
P(X=x∗)\Pr(X = x^*)0.000
F−1(u∗)F^{-1}(u^*)1.500
F(F−1(u∗))F(F^{-1}(u^*)) versus u∗u^*0.600 ≥ 0.450
sup⁡x∣Fn−F∣\sup_x \abs{F_n - F}0.0170 (1/√n = 0.0224)
Atoms (mass)1.50 (0.30), 4.50 (0.15)
Density of each ramp, from left to right0.30 · 0.25
Drag vertices of the left polygonal curve to draw FF. Two vertices at the same xx form a jump (an atom), two at the same height a flat segment, and between them a ramp (constant density). The platform adjusts the drawing so FF is increasing and right-continuous. Below, samples from F−1(U)F^{-1}(U) reproduce the mass described by FF. Move probe x∗x^* onto a jump and compare F(x∗)F(x^*) with F(x∗−)F(x^*-). Then move probe u∗u^* and observe in the F−1F^{-1} panel (the reflection of FF) how jumps in FF become flat segments in F−1F^{-1} and flat segments become jumps. What height does F−1F^{-1} have at a level u∗u^* exactly at a jump boundary?

Everything drawn under three conditions (increasing, equals 00 and 11 at endpoints, right-continuous) is a distribution function. The quantile-function section proves this by explicit construction from one uniform number: extension theory need not be used again, since the only required measure is Lebesgue measure on (0,1)(0, 1), already constructed.

Three kinds of laws

The preceding figure mixes ramps, jumps and gaps. Name them.

  • A law is discrete if PX=∑ipiδxi\Pr_X = \sum_i p_i \delta_{x_i} with pi≥0p_i \ge 0 and ∑ipi=1\sum_i p_i = 1 on countably many atoms xix_i. FF jumps at each xix_i by pip_i and grows only through jumps: isolated atoms form stairs flat between them, but atoms can be dense (e.g. all rationals), in which case FF is strictly increasing and discontinuous on a dense set.
  • A law is absolutely continuous if a density f≥0f \ge 0 exists with F(x)=∫−∞xf(t)  ⁣dtF(x) = \int_{-\infty}^x f(t)\,\dd t. Then FF is continuous and differentiable where ff is continuous, with F′=fF' = f. The precise concept and Radon–Nikodym theorem appear in the density lesson.
  • A law is singular continuous if FF is continuous (no atoms) but PX\Pr_X lives on a Lebesgue-null set. It may appear pathological; the next section constructs one.

Every law is a mixture αdμd+αacμac+αsμs\alpha_d \mu_d + \alpha_{ac} \mu_{ac} + \alpha_s \mu_s of one part of each kind, with αd+αac+αs=1\alpha_d + \alpha_{ac} + \alpha_s = 1 (Lebesgue decomposition, proved in the density lesson). The builder reads “atom mass / density mass / singular mass”. Mixed laws are common: customer expenditure (zero with positive probability and continuous if purchasing), portfolio losses with a capital cushion, or activation ReLU⁡\relu applied to a Gaussian, concentrating half the mass at atom 00 and distributing the rest with density.

The devil’s staircase

Can a distribution function be continuous without having a density? Yes: the example is the previous lesson’s Cantor set C=⋂nCnC = \bigcap_n C_n, length zero and uncountable. On Ω=[0,1)\Omega = [0, 1) with Lebesgue measure, let bk(ω)∈{0,1}b_k(\omega) \in \{0, 1\} be the kk-th binary digit of ω\omega (each bkb_k is an indicator of a finite interval union, hence measurable), and

X(ω)=∑k≥12 bk(ω) 3−k.X(\omega) = \sum_{k \ge 1} 2\, b_k(\omega)\, 3^{-k}.

It is measurable as the limit of measurable partial sums. In words: read binary digits of ω\omega and rewrite as ternary digits 00 or 22. The result lives in CC.

Proof

For each nn, XX falls in one of 2n2^n intervals of CnC_n (of length 3−n3^{-n}): interval IbI_b corresponding to the first nn binary digits bb of ω\omega, because X−∑k≤n2bk3−k=∑k>n2bk3−k∈[0,3−n]X - \sum_{k \le n} 2 b_k 3^{-k} = \sum_{k > n} 2 b_k 3^{-k} \in [0, 3^{-n}]. Each bb occurs with probability 2−n2^{-n}, and since 2n2^n intervals are disjoint, P(X∈Ib)=2−n\Pr(X \in I_b) = 2^{-n} for each. In particular X∈CX \in C almost surely (indeed, always).

No atoms. A point xx lies in at most one IbI_b for every nn, so P(X=x)≤2−n\Pr(X = x) \le 2^{-n} for every nn, i.e. P(X=x)=0\Pr(X = x) = 0. Thus FF has no jumps and is continuous.

Constant on gaps. If (a,b)(a, b) is a removed interval, P(X∈(a,b))=0\Pr(X \in (a, b)) = 0 because X∈CX \in C, so F(b)−F(a)=P(a<X≤b)=P(X=b)=0F(b) - F(a) = \Pr(a < X \le b) = \Pr(X = b) = 0.

No density. If f≥0f \ge 0 existed with P(X∈B)=∫Bf\Pr(X \in B) = \int_B f for every Borel set BB, taking B=CB = C would give 1=∫Cf1 = \int_C f. But λ(C)=0\lambda(C) = 0, and the integral of a nonnegative function over a null set is zero (proved in the Lebesgue-integral lesson). Contradiction. ■\blacksquare

∎

View construction of FF as the limit of distribution functions FnF_n of the uniform on CnC_n, polygonal with 2n2^n increasing segments: ∣F−Fn∣≤2−n\abs{F - F_n} \le 2^{-n} because both assign mass 2−n2^{-n} to each IbI_b. This is the “staircase”: FF is continuous and rises from 00 to 11, but F′=0F' = 0 everywhere outside CC, a full-measure set. Thus ∫01F′=0≠1=F(1)−F(0)\int_0^1 F' = 0 \ne 1 = F(1) - F(0): the fundamental theorem of calculus fails for FF, continuous and increasing but not absolutely continuous.

InteractiveThe devil's staircase
FnF_n (blue) converges to the Cantor function FF (gray); below is the set CnC_n supporting the mass
Estimated density with 343^{4} bins, from 6000 samples of the Cantor law
  • FnF_n
  • Cantor function FF
  • CnC_n and samples
  • uniform density (height 1)
n = 0
4 (81 bins)
Intervals of CnC_n1 of length 3⁰
Lebesgue measure of CnC_n(2/3)⁰ = 1.0000
Bound on sup⁡x∣F−Fn∣\sup_x \abs{F - F_n}2⁰ = 1.0000
Occupied histogram bins16 of 81
Height of each occupied bin(3/2)⁴ = 5.06
Above, the construction: FnF_n is the uniform distribution function on CnC_n and increases with nn toward the Cantor function. Below is a histogram of Cantor-law samples (random ternary digits 00 or 22) with 3m3^m bins. If there were a density, heights would stabilize as the histogram is refined. Increase mm and check they do not: occupied bins number 2m2^m, each height (3/2)m(3/2)^m, growing without bound. What height would a continuous-density histogram have as mm grows?

Two more facts. First: for 1/4=0.0202…31/4 = 0.0202\ldots_3 its binary image is 0.0101…2=1/30.0101\ldots_2 = 1/3, so F(1/4)=1/3F(1/4) = 1/3 (an exercise). Second: map ω↦X(ω)\omega \mapsto X(\omega) agrees with the generalized inverse of FF (except at dyadic ω\omega, a countable set), used by the next section’s sampler. Simulating a Cantor variable means reading bits of a uniform number.

The quantile function

A continuous strictly increasing FF has an ordinary inverse F−1F^{-1}, and F−1(u)F^{-1}(u) is the uu-quantile. When FF jumps it is not surjective, and when flat it is not injective: no inverse exists. A definition that always works rescues it.

The set whose infimum is taken is nonempty (since F→1>uF \to 1 > u, some xx has F(x)≥uF(x) \ge u) and bounded below (since F→0<uF \to 0 < u, F(x)<uF(x) < u for sufficiently negative xx), so F−1(u)∈RF^{-1}(u) \in \R. The infimum is attained by right continuity: F(F−1(u))≥uF(F^{-1}(u)) \ge u. This yields the section’s tool.

Proof

(⇐\Leftarrow) If u≤F(x)u \le F(x), then xx belongs to the set whose infimum is taken, so F−1(u)≤xF^{-1}(u) \le x. (⇒\Rightarrow) If F−1(u)≤xF^{-1}(u) \le x, monotonicity and attainment of the infimum give F(x)≥F(F−1(u))≥uF(x) \ge F(F^{-1}(u)) \ge u. ■\blacksquare

∎

Everything following comes from this equivalence, saying FF and F−1F^{-1} form a Galois correspondence. In particular:

  • F−1F^{-1} is increasing and left-continuous (if un↑uu_n \uparrow u, then F−1(un)↑q≤F−1(u)F^{-1}(u_n) \uparrow q \le F^{-1}(u), and F(q)≥F(F−1(un))≥unF(q) \ge F(F^{-1}(u_n)) \ge u_n for every nn, hence F(q)≥uF(q) \ge u and F−1(u)≤qF^{-1}(u) \le q).
  • F(F−1(u))≥uF(F^{-1}(u)) \ge u, with equality if FF is continuous. (For y<F−1(u)y < F^{-1}(u) we have F(y)<uF(y) < u, so F(F−1(u)−)≤uF(F^{-1}(u)^-) \le u.)
  • F−1(F(x))≤xF^{-1}(F(x)) \le x (if F(x)∈(0,1)F(x) \in (0, 1)), with strict inequality exactly when FF is constant on an interval [y,x][y, x] with y<xy < x.
  • Exchange. A jump of FF at x0x_0, from aa to bb, is a flat segment of F−1F^{-1}: F−1(u)=x0F^{-1}(u) = x_0 for every u∈(a,b]u \in (a, b]. A flat segment of FF, with F=cF = c on [x1,x2)[x_1, x_2), is a jump of F−1F^{-1} from x1x_1 to x2x_2 at level cc, with value x1x_1 at that level (hence left continuity). Geometrically, the graph of F−1F^{-1} is that of FF reflected across the diagonal, vertical segments filled and horizontal ones cut.

Examples worth memorizing. Exponential with rate λ\lambda, F(x)=1−e−λxF(x) = 1 - e^{-\lambda x}, has F−1(u)=−ln⁡(1−u)/λF^{-1}(u) = -\ln(1 - u)/\lambda. Cauchy, F(x)=12+1πarctan⁡xF(x) = \tfrac12 + \tfrac{1}{\pi} \arctan x, has F−1(u)=tan⁡(π(u−12))F^{-1}(u) = \tan\big(\pi(u - \tfrac12)\big). Bernoulli with parameter pp has F−1(u)=0F^{-1}(u) = 0 if u≤1−pu \le 1 - p and 11 if u>1−pu > 1 - p. The median is F−1(1/2)F^{-1}(1/2), and portfolio Value at Risk at level α\alpha is a quantile of its loss distribution.

u=F(x)=1−e−λxu = F(x) = 1 - e^{-\lambda x}
Find x satisfying F(x) = u for an exponential; F is continuous and strictly increasing on [0, ∞), so its generalized inverse is the ordinary inverse.
1/4

Inverse sampling and the probability integral transform

We can now prove the lesson’s most practical result and the remaining existence theorem.

Proof

F−1F^{-1} is increasing, hence Borel, and XX is a random variable. By duality, for every x∈Rx \in \R,

P(X≤x)=P(F−1(U)≤x)=P(U≤F(x))=F(x),\Pr(X \le x) = \Pr\big(F^{-1}(U) \le x\big) = \Pr\big(U \le F(x)\big) = F(x),

where the final equality uses F(x)∈[0,1]F(x) \in [0, 1] and uniformity of UU. Thus FF is the distribution function of XX; the reverse implication is the properties theorem. ■\blacksquare

∎

The meaning matters. With one uniform number and one monotone function we construct a random variable of any law on R\R. This is inverse sampling, the first nonuniform random-variable generator in Monte Carlo simulation (inverse F−1F^{-1} has closed form for exponential, Cauchy, Weibull, logistic, Pareto and every finite discrete law). When F−1F^{-1} lacks closed form, as for normal, gamma or beta, a numerical approximation is used; normal laws are also generated by transforms such as Box–Muller, studied in random-variable transformations. A modern generative model follows the same scheme: uniform or Gaussian noise passes through a learned function, and the sample distribution is the noise’s pushforward.

The reverse direction has a name.

Proof

(a) By duality, F−1(u)≤X(ω)  ⟺  u≤F(X(ω))F^{-1}(u) \le X(\omega) \iff u \le F(X(\omega)), i.e. {F(X)≥u}={X≥F−1(u)}\{F(X) \ge u\} = \{X \ge F^{-1}(u)\}. Thus P(F(X)<u)=P(X<F−1(u))=F(F−1(u)−)\Pr(F(X) < u) = \Pr(X < F^{-1}(u)) = F(F^{-1}(u)^-), at most uu because F(y)<uF(y) < u for y<F−1(u)y < F^{-1}(u).

(b) If FF is continuous, F(F−1(u)−)=F(F−1(u))=uF(F^{-1}(u)^-) = F(F^{-1}(u)) = u (already seen). Thus P(F(X)<u)=u\Pr(F(X) < u) = u for every u∈(0,1)u \in (0, 1), the uniform CDF (and P(F(X)≤u)=lim⁡ε↓0P(F(X)<u+ε)=u\Pr(F(X) \le u) = \lim_{\varepsilon \downarrow 0} \Pr(F(X) < u + \varepsilon) = u).

(c) If FF jumps at x0x_0 from aa to bb, then F(X)F(X) takes value bb with probability b−a>0b - a > 0, and a uniform variable has no atoms. For the randomized version fix v∈(0,1)v \in (0, 1) and let q=F−1(v)q = F^{-1}(v), so F(q−)≤v≤F(q)F(q^-) \le v \le F(q). If X<qX < q, then V≤F(X)≤F(q−)≤vV \le F(X) \le F(q^-) \le v. If X>qX > q, then V≥F(X−)≥F(q)≥vV \ge F(X^-) \ge F(q) \ge v, and equality occurs only on a null event. If X=qX = q (possible only if FF jumps at qq), VV is uniform on (F(q−),F(q)](F(q^-), F(q)] and P(V≤v∣X=q)=v−F(q−)F(q)−F(q−)\Pr(V \le v \mid X = q) = \dfrac{v - F(q^-)}{F(q) - F(q^-)}. Thus

P(V≤v)=F(q−)+P(X=q) v−F(q−)F(q)−F(q−)=F(q−)+(v−F(q−))=v.\Pr(V \le v) = F(q^-) + \Pr(X = q)\,\frac{v - F(q^-)}{F(q) - F(q^-)} = F(q^-) + \big(v - F(q^-)\big) = v.

If FF does not jump at qq, then F(q−)=F(q)=vF(q^-) = F(q) = v and the calculation is direct. ■\blacksquare

∎

This checks calibration. If the model says YY has CDF FtF_t at every time tt, and prediction is good, values Ft(Yt)F_t(Y_t) are uniform: a flat PIT histogram signals calibration. A U shape means model tails are too thin; bell shape means too thick. But implication (b) requires continuous FF, hence the randomized version for discrete or mixed data.

InteractiveUniforms bouncing off the distribution function
A UU enters from the left at height UU, bounces off FF and falls onto the xx axis
Frequency of X=F−1(U)X = F^{-1}(U) per bin (bars) and exact mass of FF (marks)
  • FF
  • uniform UU
  • X=F−1(U)X = F^{-1}(U)
  • exact mass
Direction
Samples nn60
sup⁡x∣Fn(x)−F(x)∣\sup_x \abs{F_n(x) - F(x)}0.1000 (1/√n = 0.1291)
Outside the view1.7 %
In inversion mode, each uniform UU enters from the left at height UU, bounces off the graph of FF and falls onto the horizontal axis as F−1(U)F^{-1}(U). Falls form a histogram approaching the law. Choose exponential, Cauchy, discrete, mixed and Cantor: why do jumps of FF become atoms and flat segments gaps? Compare the tallest bar with its exact value. Then switch to PIT mode (the reverse path from XX to F(X)F(X)): with continuous FF the result is uniform, but with jumps it accumulates at a few values. Enable ‘Randomize within each jump’ to see how theorem part (c) fixes this.

σ(X)\sigma(X): what XX reveals

In the σ-algebra lesson information was a finite partition. For a random variable a specific σ-algebra plays that role.

Proof

Preimages preserve complements, unions and X−1(R)=ΩX^{-1}(\R) = \Omega, so σ(X)\sigma(X) is a σ-algebra. If XX is G\mathcal{G}-measurable, each X−1(B)X^{-1}(B) is in G\mathcal{G} by definition. ■\blacksquare

∎

Events of σ(X)\sigma(X) are those decidable by someone knowing XX: {X∈B}\{X \in B\} is true or false according to X(ω)X(\omega). On finite Ω\Omega atoms of σ(X)\sigma(X) are level sets {X=x}\{X = x\}, and σ(X)\sigma(X) is the set of all their unions, the σ-algebra lesson’s diagram. A natural question: which other variables can be computed knowing only XX? Exactly functions of XX.

Proof

(⇐\Leftarrow) For Borel BB, {g(X)∈B}=X−1(g−1(B))∈σ(X)\{g(X) \in B\} = X^{-1}(g^{-1}(B)) \in \sigma(X). (⇒\Rightarrow) Proceed in three standard measure-theoretic stages.

Indicators. If Y=1AY = \ind_A with A∈σ(X)A \in \sigma(X), a Borel set BB exists with A=X−1(B)A = X^{-1}(B), and then Y=1B(X)Y = \ind_B(X).

Simple functions. If Y=∑i=1mci1AiY = \sum_{i=1}^m c_i \ind_{A_i} with Ai∈σ(X)A_i \in \sigma(X), use functions gi=1Big_i = \ind_{B_i} from the preceding stage and g=∑icigig = \sum_i c_i g_i.

General. Let Yn=max⁡(−n,min⁡(n,2−n⌊2nY⌋))Y_n = \max\big(-n, \min(n, 2^{-n}\lfloor 2^n Y \rfloor)\big). Each YnY_n is σ(X)\sigma(X)-measurable, takes finitely many values and converges to YY at every ω\omega. By the preceding stage Yn=gn(X)Y_n = g_n(X) with Borel gng_n. Let LL be the set of x∈Rx \in \R where gn(x)g_n(x) converges: it is Borel by the operations theorem, and g=lim⁡ngn1Lg = \lim_n g_n \ind_L is Borel. For each ω\omega, sequence gn(X(ω))=Yn(ω)g_n(X(\omega)) = Y_n(\omega) converges, i.e. X(ω)∈LX(\omega) \in L, and g(X(ω))=Y(ω)g(X(\omega)) = Y(\omega). ■\blacksquare

∎

In a finite space this is a table. If YY is constant on each level {X=x}\{X = x\}, the table assigning xx the value of YY on that level is gg. Otherwise two outcomes have the same XX and different YY: XX is insufficient to calculate YY. The next cell constructs that table; the figure explores combinations.

[ ]Doob–Dynkin on finite Ω: build g or find a witnessBrowser
from itertools import product

omega = ["".join(t) for t in product("01", repeat=3)]        # tres lanzamientos, 1 = cara
caras = lambda w: w.count("1")

def tabla_g(X, Y):
    """Si Y es σ(X)-medible devuelve (g, None) con Y = g(X); si no, (None, par de resultados que X no distingue y Y sí)."""
    g = {}
    for w in omega:
        x = X(w)
        if x in g and g[x][1] != Y(w):
            return None, (g[x][0], w)
        g.setdefault(x, (w, Y(w)))
    return {x: y for x, (_, y) in g.items()}, None

casos = {
    "X = nº de caras,  Y = 1[al menos 2 caras]": (caras, lambda w: int(caras(w) >= 2)),
    "X = nº de caras,  Y = paridad de las caras": (caras, lambda w: caras(w) % 2),
    "X = paridad,      Y = nº de caras": (lambda w: caras(w) % 2, caras),
    "X = nº de caras,  Y = primer lanzamiento": (caras, lambda w: w[0]),
}
for nombre, (X, Y) in casos.items():
    g, malo = tabla_g(X, Y)
    print(nombre, "->", f"g = {g}" if g is not None else f"no: {malo[0]} y {malo[1]} dan el mismo X y distinto Y")
InteractiveWhat can be computed knowing only X?
Ω={000,…,111}\Omega = \{000, \dots, 111\} (1 = heads), with uniform P\Pr. Each box is an atom {X=x}\{X = x\}; the value of YY appears below each outcome
X = 0
000
0
g(0) = 0
X = 1 (3 outcomes)
001
0
010
0
100
0
g(1) = 0
X = 2 (3 outcomes)
011
1
101
1
110
1
g(2) = 1
X = 3
111
1
g(3) = 1
Atoms of σ(X)\sigma(X)4
Events of σ(X)\sigma(X)2⁴ = 16
Entropy of XX1.81 of 3 bits
σ(Y)⊆σ(X)\sigma(Y) \subseteq \sigma(X)yes
YY is constant on each atom: it is σ(X)\sigma(X)-measurable and equals Y=g(X)Y = g(X), with gg given by the boxes.
Three coin tosses, eight outcomes. Choose what you know (XX): boxes are atoms of σ(X)\sigma(X), level sets {X=x}\{X = x\}. Choose what to calculate (YY): its value appears below each outcome. If YY is constant within each box it is σ(X)\sigma(X)-measurable and table gg gives Y=g(X)Y = g(X). Otherwise the problematic box is the witness. With XX = head count, can you calculate the last toss? Parity? Now XX = parity: what is lost? Which listed XX is least informative? Most?

Three recurring readings of the lemma. Processing creates no information: if Y=g(X)Y = g(X), then σ(Y)⊂σ(X)\sigma(Y) \subset \sigma(X). For example σ(X2)⊂σ(X)\sigma(X^2) \subset \sigma(X), but not conversely: X2X^2 forgets the sign, as the figure’s parity shows. This is the set-theoretic data-processing inequality and why no model trained on features can use what those features do not reveal. The best prediction is a function of observations: conditional expectation E[Y∣X]\E[Y \mid X] will be σ(X)\sigma(X)-measurable, hence by Doob–Dynkin g(X)g(X) for Borel gg, what regression estimates. Filtrations are increasing families: if Ft=σ(X1,…,Xt)\mathcal{F}_t = \sigma(X_1, \dots, X_t) is information after tt observations, Ft⊂Ft+1\mathcal{F}_t \subset \mathcal{F}_{t+1}, and an adapted process has its variable at time tt as gt(X1,…,Xt)g_t(X_1, \dots, X_t).

Implementation from scratch: a universal sampler

The inverse theorem is implemented almost unchanged. The only ingredient is computing F−1(u)=inf⁡{x:F(x)≥u}F^{-1}(u) = \inf\{x : F(x) \ge u\} for arbitrary FF, safest by bisection: maintain invariant F(lo)<u≤F(hi)F(\text{lo}) < u \le F(\text{hi}) and each step keeps the satisfying half. Jumps and flat segments work unchanged because it uses only that FF is increasing and the infimum attained (hence comparison ≥\ge rather than >>). Validate with Kolmogorov–Smirnov distance sup⁡x∣Fn(x)−F(x)∣\sup_x \abs{F_n(x) - F(x)} of empirical CDF FnF_n, here only a diagnostic: for a sample of size nn from the correct law, n sup⁡x∣Fn−F∣\sqrt{n}\,\sup_x \abs{F_n - F} is of order 11 (its 95th percentile is 1.361.36).

[ ]Universal inverse sampler (bisection)Browser
import numpy as np

def cuantil(F, u, iters=100):
    """F^{-1}(u) = inf{x : F(x) >= u} por bisección. Invariante: F(lo) < u <= F(hi)."""
    u = np.atleast_1d(np.asarray(u, dtype=float))
    lo, hi = np.full_like(u, -1.0), np.full_like(u, 1.0)
    for _ in range(100):                       # ensancha el intervalo hasta atrapar a u
        sube, baja = F(lo) >= u, F(hi) < u
        if not (sube.any() or baja.any()):
            break
        lo, hi = np.where(sube, 2 * lo - 1, lo), np.where(baja, 2 * hi + 1, hi)
    for _ in range(iters):
        mid = (lo + hi) / 2
        ok = F(mid) >= u                       # ">=": el ínfimo se alcanza por la continuidad por la derecha
        hi, lo = np.where(ok, mid, hi), np.where(ok, lo, mid)
    return hi

def F_exp(x, lam=2.0):
    x = np.asarray(x, dtype=float)
    return np.where(x < 0, 0.0, 1 - np.exp(-lam * np.maximum(x, 0)))

def F_cauchy(x):
    return 0.5 + np.arctan(np.asarray(x, dtype=float)) / np.pi

atomos, masas = np.array([0.0, 1.0, 2.0, 4.0]), np.array([0.15, 0.35, 0.30, 0.20])
def F_disc(x):
    return (masas * (np.asarray(x, dtype=float)[..., None] >= atomos)).sum(-1)

def F_mixta(x):                                # 0.3 δ_0 + 0.7 Exp(1)
    x = np.asarray(x, dtype=float)
    return np.where(x < 0, 0.0, 0.3 + 0.7 * (1 - np.exp(-np.maximum(x, 0))))

def F_cantor(x, cifras=40):
    """Función de Cantor: se leen los dígitos ternarios de x hasta el primer 1 y se pasan a binario."""
    x = np.asarray(x, dtype=float)
    t, out, w, vivo = np.clip(x, 0, 1), np.zeros_like(x), 0.5, np.ones(x.shape, dtype=bool)
    for _ in range(cifras):
        t = 3 * t
        d = np.floor(t)
        t = t - d
        out = out + np.where(vivo & (d >= 1), w, 0.0)
        vivo = vivo & (d != 1)
        w /= 2
    return np.where(x <= 0, 0.0, np.where(x >= 1, 1.0, out))

def ks(muestra, F):
    """sup_x |F_n(x) - F(x)|, exacto: se mira a la derecha y a la izquierda de cada valor."""
    x = np.sort(muestra)
    n = len(x)
    i = np.arange(1, n + 1)
    Fd, Fi = F(x), F(np.nextafter(x, -np.inf))
    return max((i / n - Fd).max(), (Fi - (i - 1) / n).max())

rng = np.random.default_rng(1)
n = 10_000
leyes = {"exponencial(2)": F_exp, "Cauchy": F_cauchy, "discreta": F_disc, "mixta": F_mixta, "Cantor": F_cantor}
for nombre, Fn in leyes.items():
    D = ks(cuantil(Fn, rng.random(n)), Fn)
    print(f"{nombre:15s} sup|F_n - F| = {D:.4f}   sqrt(n) * D = {np.sqrt(n) * D:.2f}")

X = cuantil(F_disc, rng.random(n))
vals, cnt = np.unique(X, return_counts=True)
print("\ndiscreta: valores", vals, " frecuencias", cnt / n, " masas", masas)
Xm = cuantil(F_mixta, rng.random(n))
print("mixta: frecuencia de X = 0:", (Xm == 0).mean(), " (exacta 0.3)")
Xc = cuantil(F_cantor, rng.random(n))
print("Cantor: casos en el tercio central (1/3, 2/3):", ((Xc > 1 / 3) & (Xc < 2 / 3)).sum(), "  F(1/4) =", round(float(F_cantor(0.25)), 9), " (exacta 1/3)")

# la «inversa» de un dibujo: interpolar la tabla (F(x), x) inventa valores que la ley no toma
rejilla = np.linspace(-1, 6, 2001)
Xn = np.interp(rng.random(n), F_disc(rejilla), rejilla)
print("\ninversa ingenua en la discreta: valores distintos =", len(np.unique(Xn)), "  sup|F_n - F| =", round(ks(Xn, F_disc), 3))

The same code serves all five laws, including Cantor, absent from libraries: bisection needs only evaluation of FF. For the discrete law frequencies reproduce masses 0.15,0.35,0.30,0.200.15, 0.35, 0.30, 0.20 and values are exactly atoms; for the mixed law atom frequency approaches 0.30.3; for Cantor no sample falls in the middle third. The last line shows what happens with the “inverse” obtained by interpolating the table (F(x),x)(F(x), x), the first attempt when inverting a plot: it invents intermediate values absent from the law and Kolmogorov–Smirnov distance jumps to 0.2550.255, about seventy times the generalized inverse (0.00380.0038).

The second experiment checks PIT with samples not from our sampler, avoiding a circular check.

[ ]PIT: uniform with continuous F, not with jumpsBrowser
def pit(X, F, rng=None):
    """F(X) y, si se da rng, la versión aleatorizada V = F(X-) + U (F(X) - F(X-))."""
    Fd = F(X)
    if rng is None:
        return Fd
    Fi = F(np.nextafter(X, -np.inf))
    return Fi + rng.random(len(X)) * (Fd - Fi)

# muestras de numpy, independientes de nuestro muestreador
b = rng.integers(0, 2, (n, 40))
muestras = {
    "exponencial(2)": rng.exponential(0.5, n),
    "Cauchy": rng.standard_cauchy(n),
    "discreta": rng.choice(atomos, n, p=masas),
    "mixta": np.where(rng.random(n) < 0.3, 0.0, rng.exponential(1.0, n)),
    "Cantor": (2 * b * 3.0 ** -np.arange(1, 41)).sum(1),
}
uniforme = lambda v: np.clip(v, 0, 1)
for nombre, Fn in leyes.items():
    X = muestras[nombre]
    A, B = pit(X, Fn), pit(X, Fn, rng)
    print(f"{nombre:15s} valores distintos de F(X): {len(np.unique(A)):5d}   sup|G_n - id|: {ks(A, uniforme):.4f}   aleatorizada: {ks(B, uniforme):.4f}")

X = muestras["discreta"]
print("\ndiscreta: P(F(X) < 0.7) =", (F_disc(X) < 0.7).mean(), "  F(Q(0.7)-) =", F_disc(np.nextafter(2.0, -np.inf)), "  (un uniforme daría 0.7)")

Both atomic laws, discrete and mixed, have large distance from uniform without randomization (0.350.35 and 0.300.30; for mixed it is exactly atom size because F(X)F(X) never falls in (0,0.3)(0, 0.3)); randomization brings it to noise level like the continuous laws. The last line is theorem part (a): P(F(X)<0.7)=F(F−1(0.7)−)=F(2−)=0.5<0.7\Pr(F(X) < 0.7) = F(F^{-1}(0.7)^-) = F(2^-) = 0.5 < 0.7, and simulation gives frequency 0.490.49.

The library version

scipy.stats implements this theory exactly: cdf is FF, ppf (“percent point function”) is generalized inverse F−1F^{-1}, and rvs generates samples. Check identities F(F−1(u))=uF(F^{-1}(u)) = u and F−1(F(x))=xF^{-1}(F(x)) = x in the continuous case and their weakening to theorem inequalities in the discrete case, and that previous bisection reproduces ppf in both.

[ ]cdf, ppf and rvs in scipy.statsBrowser
from scipy import stats

u = np.array([0.01, 0.25, 0.5, 0.9, 0.999])
for nombre, d in {"expon(scale=1/2)": stats.expon(scale=0.5), "cauchy": stats.cauchy(), "norm": stats.norm()}.items():
    print(f"{nombre:18s} máx |cdf(ppf(u)) - u| = {np.abs(d.cdf(d.ppf(u)) - u).max():.1e}")

d = stats.rv_discrete(values=([0, 1, 2, 4], [1 / 8, 3 / 8, 1 / 4, 1 / 4]))
u = np.array([0.1, 0.125, 0.13, 0.5, 0.51, 0.75, 0.76, 0.99])
print("\nu        :", u)
print("ppf(u)   :", d.ppf(u))
print("cdf(ppf) :", d.cdf(d.ppf(u)), "  >= u siempre; igual solo cuando u es un nivel F(x_k)")
x = np.array([0.0, 0.5, 1.0, 1.7, 2.0, 3.9, 4.0])
print("x        :", x)
print("ppf(cdf) :", d.ppf(d.cdf(x)), "  <= x; igual solo en los átomos")

u = rng.random(2000)
e = stats.expon(scale=0.5)
print("\nbisección propia = ppf (exponencial):", np.allclose(cuantil(F_exp, u), e.ppf(u)))
print("bisección propia = ppf (discreta)   :", np.array_equal(cuantil(d.cdf, u), d.ppf(u)))
print("kstest de ppf(U) contra cdf:", stats.kstest(e.ppf(u), e.cdf))
print("ks_2samp de rvs frente a ppf(U):", stats.ks_2samp(e.rvs(size=2000, random_state=np.random.default_rng(3)), e.ppf(u)))

Inspect the discrete table: with u=0.125u = 0.125, exactly level F(0)F(0), ppf returns 00 rather than 11 (because of ≥\ge in the definition); with u=0.13u = 0.13, just above, it returns 11. cdf(ppf(u)) exceeds uu except at those levels, and ppf(cdf(x)) returns xx only when xx is an atom: at x=1.7x = 1.7 it returns 11, the previous atom. Both final Kolmogorov–Smirnov tests do not reject, as expected (their pp-values are large), because rvs and ppf(U) generate the same law differently: with an Generator from numpy, rvs calls standard_exponential, which uses the ziggurat method rather than inversion. (With an integer as random_state, scipy uses old RandomState, whose exponential is −ln⁡(1−U)-\ln(1 - U), making comparison almost circular.) And scipy has neither Cantor nor the figures’ mixed law: use custom bisection, working for any FF.

Common mistakes

Exercises

ProofInversion produces the correct law
Prove: Let FF be a distribution function with generalized inverse F−1(u)=inf⁡{x:F(x)≥u}F^{-1}(u) = \inf\{x : F(x) \ge u\}, and let U∼Unif⁡(0,1)U \sim \Unif(0, 1). Then F−1(U)F^{-1}(U) is a random variable with distribution function FF.
0
We identify the distribution function of X=F−1(U)X = F^{-1}(U) and separately justify that XX is measurable.

Step 1 of 4. What must be calculated to identify the law of XX?

ProofThe PIT is uniform if F is continuous
Prove: If XX has a continuous distribution function FF, then F(X)∼Unif⁡(0,1)F(X) \sim \Unif(0, 1). If FF has jumps, this can fail.
0
Calculate P(F(X)<u)\Pr(F(X) < u) for u∈(0,1)u \in (0, 1) using the duality between FF and F−1F^{-1}.

Step 1 of 4. For fixed u∈(0,1)u \in (0, 1), what event is equivalent to {F(X)≥u}\{F(X) \ge u\}?

CodeQuantile by bisection
Implement quantile(F, u, lo=-1e6, hi=1e6, iters=200), which returns F−1(u)=inf⁡{x:F(x)≥u}F^{-1}(u) = \inf\{x : F(x) \ge u\} for a distribution function F (a Python function taking a number and returning a number in [0,1][0, 1], increasing and right-continuous) and a level u in (0,1)(0, 1), using bisection on [[lo, hi]]. It must handle jumps (if u is exactly a level F(xk)F(x_k) it must return xkx_k, not the next atom) and flat stretches (at the level cc of a flat stretch it must return its left endpoint). Tests use a discrete law, a mixed one, one with a gap and an exponential.
def quantile(F, u, lo=-1e6, hi=1e6, iters=200):
  """Devuelve inf{x : F(x) >= u} por bisección. F es creciente y continua por la derecha, con F(lo) < u <= F(hi)."""
  # tu código: mantén el invariante F(lo) < u <= F(hi)
  return (lo + hi) / 2
Shift+Enter to run
NumericMedian of an exponential
Let XX be exponential with rate λ=2\lambda = 2, with F(x)=1−e−2xF(x) = 1 - e^{-2x} for x≥0x \ge 0. Calculate its median F−1(1/2)F^{-1}(1/2).
NumericThe Cantor function at 1/4
Let FF be the distribution function of the Cantor law from the lesson. Calculate F(1/4)F(1/4).
NumericThe PIT of a Bernoulli
Let X∼Bern⁡(0.3)X \sim \operatorname{Bern}(0.3), with P(X=0)=0.7\Pr(X = 0) = 0.7 and P(X=1)=0.3\Pr(X = 1) = 0.3. Calculate P(F(X)≤0.8)\Pr(F(X) \le 0.8), where FF is its distribution function. (If F(X)F(X) were uniform, the answer would be 0.80.8.)
QuizSame law, same variable?
If XX and YY have the same law, are they equal almost surely? Choose the correct counterexample.
QuizWhich are distribution functions?
Which of these functions F:R→[0,1]F : \R \to [0, 1] are distribution functions of some random variable?

More than one answer may be correct.

QuizFunctions of X squared
Let X∼N(0,1)X \sim \Normal(0, 1). Which of these variables are σ(X2)\sigma(X^2)-measurable, that is, functions of X2X^2?

More than one answer may be correct.

Summary

Key idea
A random variable is a measurable function, and its law is the probability it induces on R\R. The distribution function, increasing, right-continuous and with limits 00 and 11, determines the law, and the generalized inverse F−1F^{-1} turns a uniform variable into a sample from any law (inversion). The information revealed by XX is σ(X)\sigma(X), and what can be calculated from it consists of functions of XX (Doob and Dynkin).
  • A function ff is measurable if f−1(B)∈Ff^{-1}(B) \in \mathcal{F} for every BB in the target σ-algebra, and it suffices to check this on a generator. Continuous and monotone functions, sums, products, suprema and limits of measurable functions are measurable.
  • A random variable is a measurable function X:Ω→RX : \Omega \to \R. Its law PX(B)=P(X∈B)\Pr_X(B) = \Pr(X \in B) is a probability on R\R: the mass of Ω\Omega transported by XX.
  • A variable is not its law. UU and 1−U1 - U have the same law and are distinct; the law does not retain their relationship with other variables.
  • F(x)=P(X≤x)F(x) = \Pr(X \le x) is increasing and right-continuous, with limits 00 and 11; its jumps are the atoms, P(X=x)=F(x)−F(x−)\Pr(X = x) = F(x) - F(x^-), and it determines the law (π-λ). Every function with these three properties is a distribution function.
  • Laws decompose into discrete, absolutely continuous and singular continuous parts. The Cantor staircase is continuous and has no density: P(X∈C)=1\Pr(X \in C) = 1 with λ(C)=0\lambda(C) = 0.
  • F−1(u)=inf⁡{x:F(x)≥u}F^{-1}(u) = \inf\{x : F(x) \ge u\} satisfies F−1(u)≤x  ⟺  u≤F(x)F^{-1}(u) \le x \iff u \le F(x). Jumps of FF become flat stretches of F−1F^{-1}, and flat stretches become jumps.
  • Inversion: F−1(U)∼FF^{-1}(U) \sim F for uniform UU, with any FF. PIT: F(X)F(X) is uniform if and only if FF is continuous (in general P(F(X)<u)≤u\Pr(F(X) < u) \le u), and jumps are handled by randomizing within each jump.
  • σ(X)={X−1(B)}\sigma(X) = \{X^{-1}(B)\} is the smallest σ-algebra that makes XX measurable. YY is σ(X)\sigma(X)-measurable if and only if Y=g(X)Y = g(X) with Borel gg, so processing XX does not create information: σ(g(X))⊂σ(X)\sigma(g(X)) \subset \sigma(X).