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 and give it a fixed input. Output is a random number, and you want the probability it exceeds a threshold: . But the σ-algebra lesson showed is evaluated only on elements of . Set 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.
- Measurable functions. Those carrying events back to events through preimages. Nearly everything you program is measurable; the generator criterion checks it with one calculation.
- A random variable’s law. A random variable is a measurable function, and its law remembers only how it distributes probability on . Very different variables can have the same law; confusing variable and law is the course’s most common conceptual error.
- The distribution function and its inverse. A function from the line to describes an entire law. Its generalized inverse turns a uniform number into a sample from any law. This powers simulation; a modern generative model is the same idea with replaced by a network.
- as information. The σ-algebra generated by comprises questions answers, and the Doob–Dynkin lemma says what can be computed from is exactly functions of .
Measurable functions
A function between sets with σ-algebras must respect them. The requirement concerns preimages, because they interact well with complements and unions: and . (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
() is trivial because . () Let . It is a σ-algebra on : , and preimages preserve complements and countable unions, which also preserves. It contains by hypothesis, hence .
∎This is the preceding lesson’s “smallest σ-algebra containing ” argument, used constantly. Known generators of yield practical consequences.
Proof
(a) Rays generate . (b) is , , or depending on whether contains and . (c) If is continuous, preimages of open sets are open, and open sets generate . If is monotone, the preimage of a ray is an interval, hence Borel. (d) .
∎Measurable functions are closed under operations used to pass to limits, the reason for “σ” in σ-algebra.
Proof
For pair , the preimage of box is , and boxes generate . Thus is measurable, and and are its compositions with continuous functions and (likewise maximum and absolute value). For suprema, and . Hence and are measurable. Finally if and only if a rational exists with , so , and its complement is the set where the limit exists.
∎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 and legitimate: they mean and , and those sets belong to . This answers the motivating question: if is a random vector and is continuous (or a composition of sums, products, and matrices, which are continuous), then is a random variable, and makes sense for every .
A random variable is a function: it assigns a number to each outcome . But rarely matters to us. We care how probability is distributed among values of . That is a measure on .
Proof
and . If are disjoint Borel sets, preimages are disjoint events and , so countable additivity of gives it for .
∎Law as transported mass
Think of with Lebesgue measure as a sand bar of total mass spread uniformly. Function moves each grain to its new location in , and the law is the resulting sand distribution. Where is nearly flat, many grains land together and sand piles up (high density, and an atom if fully flat). Where is steep, grains spread apart and sand thins.
Two examples are solved by hand. With on ,
whose derivative blows up at , where is flat. If equals on a segment of length of , the law has an atom at with (exactly if does not equal elsewhere). Density at is generally sum over preimages of (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 has law ; the next cell calculates it using exact fractions, checks properties of seen shortly, and verifies the earlier warning’s practical rule: a function is measurable for a partition if constant on its atoms.
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: and are different variables on the same space with exactly the same law; they agree only when , with probability .
A variable is not its law
A law is a measure on ; a variable is a function on . Forgetting the difference causes logical, not computational, errors.
- and have the same law, and . If , also , and except on a null event.
- Variables on different spaces can share a law: a coin toss and die parity are and live on different .
- Even with shared , the law does not remember how relates to other variables: and with have the same marginals and very different joint laws. The joint law is another measure, on .
For what follows remember that everything depending only on (probabilities of events and expectations defined with the Lebesgue integral) depends only on . Thus can be forgotten: given any probability on , space with has . A “distribution” is a probability on , and theory next describes it with a function.
The distribution function
A measure on is huge, but rays suffice to give its values on all : that is the previous lesson’s uniqueness theorem.
Proof
(1) If , . (2) If , events decrease to , and probability continuity from above gives . If they increase to , and . Since is monotone, the limit is sequence-independent. (3) If , events decrease to (a point lies in all exactly when ), and continuity again gives . If strictly, increases to , so and difference is . The interval formula is . Finally, a monotone function has one-sided limits everywhere and its discontinuities are jumps (one-sided limits and monotone functions), and for each there are at most jumps of size at least , because all jumps sum to at most . A countable union of finite sets is countable.
∎(Some texts use convention , left-continuous. Here is used because and because scipy, numpy and other software use it.)
Uniqueness is already proved. Variables with the same have the same law: rays form a π-system generating , 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 and the platform tells you its law.
Everything drawn under three conditions (increasing, equals and 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 , already constructed.
Three kinds of laws
The preceding figure mixes ramps, jumps and gaps. Name them.
- A law is discrete if with and on countably many atoms . jumps at each by and grows only through jumps: isolated atoms form stairs flat between them, but atoms can be dense (e.g. all rationals), in which case is strictly increasing and discontinuous on a dense set.
- A law is absolutely continuous if a density exists with . Then is continuous and differentiable where is continuous, with . The precise concept and Radon–Nikodym theorem appear in the density lesson.
- A law is singular continuous if is continuous (no atoms) but lives on a Lebesgue-null set. It may appear pathological; the next section constructs one.
Every law is a mixture of one part of each kind, with (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 applied to a Gaussian, concentrating half the mass at atom 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 , length zero and uncountable. On with Lebesgue measure, let be the -th binary digit of (each is an indicator of a finite interval union, hence measurable), and
It is measurable as the limit of measurable partial sums. In words: read binary digits of and rewrite as ternary digits or . The result lives in .
Proof
For each , falls in one of intervals of (of length ): interval corresponding to the first binary digits of , because . Each occurs with probability , and since intervals are disjoint, for each. In particular almost surely (indeed, always).
No atoms. A point lies in at most one for every , so for every , i.e. . Thus has no jumps and is continuous.
Constant on gaps. If is a removed interval, because , so .
No density. If existed with for every Borel set , taking would give . But , and the integral of a nonnegative function over a null set is zero (proved in the Lebesgue-integral lesson). Contradiction.
∎View construction of as the limit of distribution functions of the uniform on , polygonal with increasing segments: because both assign mass to each . This is the “staircase”: is continuous and rises from to , but everywhere outside , a full-measure set. Thus : the fundamental theorem of calculus fails for , continuous and increasing but not absolutely continuous.
Two more facts. First: for its binary image is , so (an exercise). Second: map agrees with the generalized inverse of (except at dyadic , 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 has an ordinary inverse , and is the -quantile. When 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 , some has ) and bounded below (since , for sufficiently negative ), so . The infimum is attained by right continuity: . This yields the section’s tool.
Proof
() If , then belongs to the set whose infimum is taken, so . () If , monotonicity and attainment of the infimum give .
∎Everything following comes from this equivalence, saying and form a Galois correspondence. In particular:
- is increasing and left-continuous (if , then , and for every , hence and ).
- , with equality if is continuous. (For we have , so .)
- (if ), with strict inequality exactly when is constant on an interval with .
- Exchange. A jump of at , from to , is a flat segment of : for every . A flat segment of , with on , is a jump of from to at level , with value at that level (hence left continuity). Geometrically, the graph of is that of reflected across the diagonal, vertical segments filled and horizontal ones cut.
Examples worth memorizing. Exponential with rate , , has . Cauchy, , has . Bernoulli with parameter has if and if . The median is , and portfolio Value at Risk at level is a quantile of its loss distribution.
Inverse sampling and the probability integral transform
We can now prove the lesson’s most practical result and the remaining existence theorem.
Proof
is increasing, hence Borel, and is a random variable. By duality, for every ,
where the final equality uses and uniformity of . Thus is the distribution function of ; the reverse implication is the properties theorem.
∎The meaning matters. With one uniform number and one monotone function we construct a random variable of any law on . This is inverse sampling, the first nonuniform random-variable generator in Monte Carlo simulation (inverse has closed form for exponential, Cauchy, Weibull, logistic, Pareto and every finite discrete law). When 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, , i.e. . Thus , at most because for .
(b) If is continuous, (already seen). Thus for every , the uniform CDF (and ).
(c) If jumps at from to , then takes value with probability , and a uniform variable has no atoms. For the randomized version fix and let , so . If , then . If , then , and equality occurs only on a null event. If (possible only if jumps at ), is uniform on and . Thus
If does not jump at , then and the calculation is direct.
∎This checks calibration. If the model says has CDF at every time , and prediction is good, values 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 , hence the randomized version for discrete or mixed data.
: what 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 , so is a σ-algebra. If is -measurable, each is in by definition.
∎Events of are those decidable by someone knowing : is true or false according to . On finite atoms of are level sets , and is the set of all their unions, the σ-algebra lesson’s diagram. A natural question: which other variables can be computed knowing only ? Exactly functions of .
Proof
() For Borel , . () Proceed in three standard measure-theoretic stages.
Indicators. If with , a Borel set exists with , and then .
Simple functions. If with , use functions from the preceding stage and .
General. Let . Each is -measurable, takes finitely many values and converges to at every . By the preceding stage with Borel . Let be the set of where converges: it is Borel by the operations theorem, and is Borel. For each , sequence converges, i.e. , and .
∎In a finite space this is a table. If is constant on each level , the table assigning the value of on that level is . Otherwise two outcomes have the same and different : is insufficient to calculate . The next cell constructs that table; the figure explores combinations.
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")Three recurring readings of the lemma. Processing creates no information: if , then . For example , but not conversely: 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 will be -measurable, hence by Doob–Dynkin for Borel , what regression estimates. Filtrations are increasing families: if is information after observations, , and an adapted process has its variable at time as .
Implementation from scratch: a universal sampler
The inverse theorem is implemented almost unchanged. The only ingredient is computing for arbitrary , safest by bisection: maintain invariant and each step keeps the satisfying half. Jumps and flat segments work unchanged because it uses only that is increasing and the infimum attained (hence comparison rather than ). Validate with Kolmogorov–Smirnov distance of empirical CDF , here only a diagnostic: for a sample of size from the correct law, is of order (its 95th percentile is ).
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 . For the discrete law frequencies reproduce masses and values are exactly atoms; for the mixed law atom frequency approaches ; for Cantor no sample falls in the middle third. The last line shows what happens with the “inverse” obtained by interpolating the table , the first attempt when inverting a plot: it invents intermediate values absent from the law and Kolmogorov–Smirnov distance jumps to , about seventy times the generalized inverse ().
The second experiment checks PIT with samples not from our sampler, avoiding a circular check.
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 ( and ; for mixed it is exactly atom size because never falls in ); randomization brings it to noise level like the continuous laws. The last line is theorem part (a): , and simulation gives frequency .
The library version
scipy.stats implements this theory exactly: cdf is , ppf (“percent point function”) is generalized inverse , and rvs generates samples. Check identities and in the continuous case and their weakening to theorem inequalities in the discrete case, and that previous bisection reproduces ppf in both.
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 , exactly level , ppf returns rather than (because of in the definition); with , just above, it returns . cdf(ppf(u)) exceeds except at those levels, and ppf(cdf(x)) returns only when is an atom: at it returns , the previous atom. Both final Kolmogorov–Smirnov tests do not reject, as expected (their -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 , making comparison almost circular.) And scipy has neither Cantor nor the figures’ mixed law: use custom bisection, working for any .
Common mistakes
Exercises
Step 1 of 4. What must be calculated to identify the law of ?
Step 1 of 4. For fixed , what event is equivalent to ?
quantile(F, u, lo=-1e6, hi=1e6, iters=200), which returns for a distribution function F (a Python function taking a number and returning a number in , increasing and right-continuous) and a level u in , using bisection on lo, hi. It must handle jumps (if u is exactly a level it must return , not the next atom) and flat stretches (at the level 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) / 2More than one answer may be correct.
More than one answer may be correct.
Summary
- A function is measurable if for every 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 . Its law is a probability on : the mass of transported by .
- A variable is not its law. and have the same law and are distinct; the law does not retain their relationship with other variables.
- is increasing and right-continuous, with limits and ; its jumps are the atoms, , 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: with .
- satisfies . Jumps of become flat stretches of , and flat stretches become jumps.
- Inversion: for uniform , with any . PIT: is uniform if and only if is continuous (in general ), and jumps are handled by randomizing within each jump.
- is the smallest σ-algebra that makes measurable. is -measurable if and only if with Borel , so processing does not create information: .