Laws of large numbers
Why average loss on a test set estimates risk, and when it does not. Prove the weak and strong laws, study Kolmogorov’s 0-1 law and cases where the average fails to converge (Cauchy, St Petersburg), and extend the result to uniform convergence of the empirical distribution function using Glivenko–Cantelli and the DKW inequality.
After this lesson you can
- Prove the weak law with Chebyshev and the strong law with the fourth moment and Borel–Cantelli.
- State Etemadi’s strong law and Kolmogorov’s 0-1 law.
- Identify distributions whose averages fail to converge or converge very slowly.
- Prove the Glivenko–Cantelli theorem and apply the DKW inequality to construct confidence bands for the distribution function.
Before you start
Motivation: test error estimates risk, but with what guarantee?
You train a model, evaluate it on unseen examples and obtain mean loss . You write in the report as if it were the model quality. Behind this is a probabilistic claim: mean loss on test examples, , resembles risk , expected loss under the real data distribution. This is the law of large numbers, underpinning every average: an evaluation, a stochastic gradient, a Monte Carlo integral or the frequency of an event in a log.
But the claim has fine print, which this lesson reads in full. Four questions will be answered with proofs and simulations.
- In what sense does resemble ? Using convergence modes from the previous lesson: in probability (weak law) or almost surely (strong law).
- Under what assumptions? Independence, identical distribution and an existing expectation. Which can be relaxed?
- How quickly? The law alone says nothing about rate. With finite variance error falls as ; without it convergence may be arbitrarily slow.
- When does it fail? Some distributions have averages that converge to nothing; these are not just laboratory examples. Service latencies, portfolio losses and heavy-tailed gradients can resemble them.
A preliminary calculation sets the bar. If losses lie in , then and Chebyshev’s inequality gives, for test examples, . This real quantitative guarantee takes one line to prove. It can be improved: in the Hoeffding lesson the same question is answered with . All this assumes are independent of the model; if you chose the model by inspecting the test set, are no longer an independent sample and the law does not apply. Uniform convergence in the Glivenko-Cantelli section and learning theory module addresses this problem.
Throughout, are real random variables on the same probability space, and . The existence of an infinite sequence of independent variables with prescribed laws follows from the Kolmogorov extension theorem in lesson 7; here it is assumed.
Intuition: a race of means
Before proving anything, inspect average behavior. The figure runs 200 trajectories of up to , using logarithmic scale to fit all observations from first to last.
What you should have seen:
- With Bernoulli and exponential, error falls as . Measured log-log slope is . Gaining one decimal digit requires multiplying by , a rule valid whenever variance is finite.
- With Pareto the mean converges, but at another rate. Expectation is and variance infinite. Slope is , not ; the variance cone does not exist and trajectories jump: one enormous summand shifts them suddenly and takes time for the mean to absorb. With and , over half the trajectories remain outside the band.
- With Pareto there is no limit. Expectation is infinite and the average grows as . The largest summand accounts for an appreciable fraction of the sum, measuring the problem’s severity.
- With Cauchy there is no trend either. The 5–95% band does not narrow, median error is constant, and the mean of observations is no better than one. We will prove this.
- Weak and strong laws are different readings. With the exponential, and , about 30% of trajectories are outside the band at that (weak law), but nearly 60% leave it at some later time, between and (strong law; beyond little is added). Both tend to as rises; the second does so more slowly because it controls the whole trajectory tail.
Weak law of large numbers
The weak law of large numbers (WLLN) says that under suitable assumptions in probability: for every , . The simplest version takes one line to prove, and that line gives more than promised.
Proof
By linearity, , so . By the variance of a sum, , because covariances vanish. Thus . Applying Chebyshev’s inequality to gives the second bound.
∎Note what was not used: independence, identical distribution, or even bounds on moments beyond the second. We gained a quantitative fact, , giving required sample size: the motivating bound.
What if there is no variance? Chebyshev fails, but finite expectation alone still suffices. The technique is truncation: cut each at a level where it has variance, apply Chebyshev to the truncated part and show truncation almost never acts.
Proof
Fix and . For each define truncated variables (depending on , omitted in the notation), and . There are three things to check.
The truncated mean approaches . Since is integrable, the dominated convergence theorem gives . For sufficiently large , .
The truncated part satisfies the law by Chebyshev. Since , we have . The are iid, so
Truncation almost never acts. , tending to as (again by dominated convergence, since is integrable).
If , and , then . Thus for large ,
and, since the first term tends to ,
The left side does not depend on arbitrary : it equals .
∎Truncation returns throughout limit theory. This proof also leaves a clue for later: what was actually used is not , but and convergence of truncated means. Feller showed is necessary and sufficient for to tend to in probability. Thus some laws without finite expectation satisfy the weak law with suitable centering, as in the next section’s example. St Petersburg does not satisfy the condition ( oscillates between and ), but Feller’s version for normalizations other than recovers it with , as shown below.
Strong law of large numbers
The weak law says that for each large , is unlikely to be far from . It does not say a particular trajectory, as grows, eventually stays near forever: each might have different bad trajectories. The strong law of large numbers (SLLN) asserts the latter: almost surely. The figure showed the difference between and .
With a fourth moment: Borel-Cantelli
The shortest proof uses stronger assumptions and teaches the mechanism. First calculate a moment of the sum.
Order of magnitude matters more than the constant: grows as , not . Almost all combinations of indices cancel. The strong law follows.
Proof
Without loss of generality (replace by , which still has finite fourth moment because ). By Markov’s inequality applied to and the preceding bound, for each ,
The series converges, so . By the first Borel-Cantelli lemma, : almost surely except for finitely many . Take and the countable union of null events : almost surely for every , that is, .
∎Notice why this works here but not with Chebyshev: Chebyshev’s bound forms a harmonic series and diverges, so Borel-Cantelli says nothing. The strong law needs tails summable in , or a trick avoiding that requirement. With a fourth moment the tail falls as , which suffices. Etemadi supplies the general trick.
With only finite mean: Etemadi
The theorem used in practice requires neither a fourth moment nor even variance.
Proof
Forward direction (Etemadi). Applying the argument separately to and (still identically distributed and pairwise independent), it suffices to assume .
Step 1: truncate. Let and . Since , Borel-Cantelli gives that almost surely except for finitely many ; thus . It suffices to show .
Step 2: means. By monotone convergence, , and the Cesàro mean of a convergent sequence converges: .
Step 3: a geometric subsequence. Fix and . The variance of a sum of pairwise independent variables is the sum of variances, so by Chebyshev, for ,
Since and implies , the inner sum is at most . It remains to bound . For , , so that quantity is at most . By Borel-Cantelli (taking ), almost surely; with step 2, almost surely.
Step 4: monotonicity. Since , increases in . For ,
and . Thus almost surely. Taking and the countable intersection yields .
Converse. If on a positive-probability event , then on , , so occurs only finitely often. But , and if the series diverges: by the second Borel-Cantelli lemma (the are independent), occurs infinitely often almost surely. Contradiction; hence .
∎Three comments. First, Etemadi proves the strong law with only pairwise independence, much weaker than joint independence, in less space than Kolmogorov’s classical proof. Second, the converse says finite expectation is not a technical convenience: it is exactly the condition for an iid average to converge almost surely to a number. Third, the strong law implies the weak law (almost-sure convergence implies convergence in probability), but not conversely: the next example and St Petersburg paradox show this.
Kolmogorov’s zero-one law
The previous two theorems say when the average converges. Could it do so with probability , or converge to a random limit? Not for independent sequences, due to a very general symmetry property.
Tail events include “series converges”, “ infinitely often”, and “ converges”. The last is not obvious. For each fixed , and , so and have the same and . The second is measurable with respect to for every , hence and are -measurable. These events and variables obey a sharp dichotomy.
Proof
Let and . By independence of the family, and are independent (the π-λ theorem groups independent variables into independent σ-algebras). Since , every is independent of for every . Thus is independent of the family , a π-system (the increase) generating ; by π-λ, is independent of all . But , so is independent of itself: , and .
For an -measurable variable, each belongs to and has probability or . Function is increasing and takes only those values, so it jumps from to at some point , and almost surely.
∎Applied to and , the zero-one law says both are almost-sure constants. Therefore the average of independent variables either converges almost surely to a constant or almost surely does not converge; it never converges with intermediate probability or to a random value. Together with Etemadi’s converse, iid variables have a complete dichotomy:
| Condition | Behavior of |
|---|---|
| converges almost surely to constant | |
| almost surely does not converge to any finite limit |
There is no middle ground. This depends on independence: without it, a single random and sequence for every yield , converging to a random limit. The final section returns to this case.
When it fails: heavy tails
Etemadi’s converse says that without finite expectation there is no law of large numbers. Consider three concrete failures, from bluntest to subtlest.
Cauchy: averaging improves nothing
The standard Cauchy law has density and characteristic function (the characteristic function of lesson 13). For iid Cauchy , the mean’s characteristic function is
the same. By uniqueness, is Cauchy for every : averaging a thousand observations does not narrow its distribution at all. If in probability, it would converge in distribution to constant , which a Cauchy is not. This is what the figure showed. The mean of Cauchy data poorly estimates the center; the sample median does converge.
Pareto: the exponent decides
The Pareto law of index has for . Its expectation is if and infinite if ; variance is finite only if . It is the canonical heavy-tail model and divides behaviors as follows.
Proof
For each , bounded variables are iid with finite expectation , and by the strong law almost surely. Since , it follows almost surely. By monotone convergence as (taking integer and the countable intersection).
∎The strong law is a proof tool here, not merely a theorem. At what rate? For the sum (centered if ) grows as (the stable-law regime in the CLT lesson), and the average as . For this exponent is (growing); for it is (error decreases, but slower than ); approaching from the right makes convergence slower, with exponent tending to . This answers the third motivating question: the law of large numbers has no universal rate. With finite moments, , the Marcinkiewicz-Zygmund law guarantees almost surely; with one recovers order (apart from factor , by the iterated logarithm law), while alone yields only convergence.
The table summarizes these cases, with the figure’s estimated slope:
| Law | Weak law | Strong law | Typical size of | ||
|---|---|---|---|---|---|
| Bernoulli, exponential | finite | finite | yes | yes | |
| Student with 2 degrees of freedom | infinite | yes | yes | slightly slower than | |
| Pareto | infinite | yes | yes | ||
| Pareto | infinite | infinite | no | no: | grows as |
| Cauchy | does not exist | infinite | no | no | constant: |
St Petersburg: a game with infinite value and finite price
In the St Petersburg game a fair coin is tossed until heads appears. If this occurs at toss (with ), the player receives euros. Each level contributes exactly to expectation, and there are infinitely many: . The paradox is that nobody would pay a fortune to play. What does the law of large numbers, which does not apply, say?
What you should have seen:
- Mean winnings grow without bound, as . About levels are already “filled” (those with prizes below ), each contributing about per game. Higher levels are so rare they appear in jumps. With typical mean winnings are around , or plus a constant near .
- One prize can make up most of the sum. Its fraction of the sum jumps when the highlighted player has an exceptional game.
- With a finite bankroll, things return to normal. Bounded prize has expectation : each level contributes , and levels jointly contribute . With fair value is and the mean converges to it; a real casino’s finite bankroll is the paradox’s practical solution.
Proof
For part 2. For , . For each , . As the are independent, the second Borel-Cantelli lemma says occurs infinitely often almost surely. Since , , so . With and the countable intersection, is infinite.
∎Part 1 is quantitative: the fair price for games is per game. Part 2 explains the red bars: with , ratio does not behave almost surely like a constant. Better normalization does not solve this: Chow and Robbins (1961) showed that for iid nonnegative infinite-mean variables, no deterministic sequence achieves almost surely.
Glivenko-Cantelli: the strong law uniformly
So far the law estimates one number, an expectation. What if we want an entire distribution? The cumulative distribution function is infinite-dimensional, and an indicator’s expectation estimates it pointwise.
For each fixed , averages variables , iid Bernoulli with parameter . The strong law gives almost surely for each . But for each is weak: an uncountable union of null events can have positive probability, and we do not even know is a random variable. (It is: right continuity makes the supremum over equal the supremum over countable .) Glivenko-Cantelli moves from pointwise to all points at once.
Proof
Fix and choose with . Let , for and , with convention , . By right continuity , and by definition of infimum . Thus for every .
By the strong law applied to indicators and (there are only ), almost surely
Let . By monotonicity of and ,
Thus and almost surely. With , and the countable intersection, almost surely.
∎Notice the result. The strong law for average fails for Cauchy, but Glivenko-Cantelli still applies: indicators are bounded and have no moment problem. Estimating a distribution is much more robust than estimating its mean. This is also the first example of uniform convergence over a class of functions (here indicators ); learning theory generalizes it to classes of finite Vapnik-Chervonenkis dimension.
DKW: the first nonasymptotic uniform bound
Glivenko-Cantelli gives no rate; a statistician needs a guaranteed band width around for given . The answer is the most-used result of one-dimensional empirical process theory.
Dvoretzky, Kiefer and Wolfowitz proved it in 1956 with an unspecified constant in the factor before the exponential; Massart (1990) proved is valid and optimal. The delicate proof is outside this lesson; we use the result. To understand its contribution, consider what available tools yield.
Three consequences are used constantly:
- Confidence band. With , setting equal gives . This band is simultaneous and assumes nothing about .
- Sample size. To obtain with probability at least , suffices. For example, with and , : observations suffice.
- An almost-sure rate for Glivenko-Cantelli. With , and, by Borel-Cantelli, almost surely except for finitely many . The true order, given by Chung and Smirnov’s iterated logarithm law, is ; DKW loses very little.
What you should have seen:
- depends on the sample and , not . For continuous , are uniform on (the probability integral transform) and is the same functional of these uniforms. Thus DKW and its band work for any , including Cauchy; with atoms, is stochastically smaller and the inequality still holds.
- The band narrows as , like everything in this lesson. Reading stays of order for all , underlying the Kolmogorov-Smirnov test.
- The bound is nearly exact. With simulated coverage is about for , for and for : as promised up to simulation error. The limit of is the Kolmogorov series , whose first term is exactly the DKW bound. Only when is large is the tail thinner: with exact coverage is for and slightly higher for small (around or with or , as in the code cell).
Beyond iid: a preview
Everything above assumes independence. Time series, Markov-chain data and losses from learning processes violate it. Three useful facts, without full proofs:
Vanishing correlation. The finite-variance weak-law proof used only uncorrelatedness. It extends to stationary processes with autocovariance : then (the average of a sequence tending to tends to ), and Chebyshev gives in probability. What is lost is effective sample size: for an autoregressive process with coefficient , , so observations with are worth about independent ones.
Ergodic averages. Birkhoff’s ergodic theorem generalizes the strong law to stationary ergodic processes: time averages converge almost surely to expectation. “Ergodic” excludes the earlier counterexample for all : here the tail is nontrivial, the zero-one law fails and the time average converges to a random variable, not ensemble expectation . In practice an irreducible positive-recurrent Markov chain is ergodic; the stochastic-processes module develops this and justifies MCMC.
Ensemble versus time average. The strong law applied to logarithms prevents confusion. Consider capital multiplied at each step by or with equal probability. Expected factor per step is and . But the strong law applied to the factor’s yields almost surely: the typical trajectory decays exponentially. With , . A handful of extremely lucky trajectories sustain expectation, and no individual lives in the ensemble average. The multiplicative-processes module develops this.
Implementation from scratch
We will build three things with NumPy: strong-law simulations for several distributions (checking the fourth moment and rate slope), a heavy-tail diagnostic examining moving-mean instability, and the empirical distribution function with its DKW band and simulated coverage.
import numpy as np
from scipy.stats import binom
# 1) E[S^4] = n m4 + 3 n (n-1) σ⁴, exacto para Bernoulli(p) centrada (no hace falta simular)
p = 0.3
for n in (5, 50, 500):
k = np.arange(n + 1)
exacto = (binom.pmf(k, n, p) * (k - n * p) ** 4).sum()
s2 = p * (1 - p)
m4 = p * (1 - p) * (1 - 3 * p * (1 - p)) # momento central de orden 4 de una Bernoulli
formula = n * m4 + 3 * n * (n - 1) * s2**2
print(f"n={n:4d} E[S^4] exacto={exacto:12.4f} fórmula={formula:12.4f} cota 3 n² m4={3*n*n*m4:12.2f}")
# 2) Velocidad: pendiente log-log del error mediano de las medias acumuladas
rng = np.random.default_rng(0)
SAMPLERS = {
"Bernoulli(0.3)": (lambda size: (rng.random(size) < 0.3).astype(float), 0.3),
"Exponencial(1)": (lambda size: rng.exponential(1.0, size), 1.0),
"Pareto(1.5)": (lambda size: rng.pareto(1.5, size) + 1.0, 3.0),
"Pareto(0.8)": (lambda size: rng.pareto(0.8, size) + 1.0, None),
"Cauchy": (lambda size: rng.standard_cauchy(size), None),
}
R, N = 100, 10_000
ns = np.unique(np.logspace(1.5, 4, 20).astype(int))
print()
for name, (draw, mu) in SAMPLERS.items():
x = draw((R, N))
medias = np.cumsum(x, axis=1)[:, ns - 1] / ns # X̄_n de cada trayectoria
centro = 0.0 if mu is None else mu # si no hay media, se mide |X̄_n|
err = np.median(np.abs(medias - centro), axis=0)
pend = np.polyfit(np.log(ns), np.log(err), 1)[0]
print(f"{name:15s} error mediano en n=10⁴: {err[-1]:10.4f} pendiente log-log: {pend:+.2f}")The first part confirms the fourth-moment formula with exact arithmetic (the binomial permits it), and bound is loose but of the right order. The second reproduces the figure: for finite-variance laws, about for Pareto , for Pareto (the theoretical limit is , and at the prior regime is still visible), and for Cauchy.
Now a practical diagnostic. Given a column to average (latencies, losses, rewards), how can you suspect an unreliable mean? Three cheap signals: the largest value’s share of the sum, moving-mean drift and Hill’s tail-index estimator.
import numpy as np
def peso_maximo(x):
"""Fracción de Σ|x_i| que aporta el mayor |x_i|: si no es despreciable, la media no se ha estabilizado."""
a = np.abs(x)
return a.max() / a.sum()
def deriva(x, tramos=10):
"""Mayor cambio de la media acumulada entre puntos de control, en unidades de la mediana de |x|."""
n = len(x)
m = np.cumsum(x) / np.arange(1, n + 1)
pts = m[np.linspace(n // tramos, n, tramos).astype(int) - 1]
return np.abs(np.diff(pts)).max() / np.median(np.abs(x))
def hill(x, k):
"""Estimador de Hill del índice de cola α con los k mayores |x|, y su error estándar aproximado α/√k."""
a = np.sort(np.abs(x))[::-1]
alfa = 1.0 / np.mean(np.log(a[:k] / a[k]))
return alfa, alfa / np.sqrt(k)
def veredicto(alfa, se, umbral):
if alfa + 2 * se < umbral:
return "no"
if alfa - 2 * se > umbral:
return "sí"
return "dudoso"
rng = np.random.default_rng(4)
n, k = 100_000, 500
muestras = {
"Normal": rng.standard_normal(n),
"Exponencial": rng.exponential(1.0, n),
"t de Student (2 g.l.)": rng.standard_t(2, n),
"Pareto(1.5)": rng.pareto(1.5, n) + 1,
"Pareto(0.8)": rng.pareto(0.8, n) + 1,
"Cauchy": rng.standard_cauchy(n),
}
print(f"{'ley':22s} {'mayor/suma':>10s} {'deriva':>8s} {'α̂ de Hill':>16s} ¿media finita? ¿varianza finita?")
for nombre, x in muestras.items():
alfa, se = hill(x, k)
print(f"{nombre:22s} {100*peso_maximo(x):9.3f}% {deriva(x):8.3f} {alfa:9.2f} ± {2*se:4.2f} {veredicto(alfa, se, 1):>13s} {veredicto(alfa, se, 2):>15s}")Read this table carefully, not blindly. Light-tailed laws have maximum share of order and negligible drift; Pareto and Cauchy reveal themselves through huge drift and a maximum weighing between and of the entire sum. Hill correctly classifies Pareto (infinite mean) and Pareto (finite mean, infinite variance), and honestly recognizes it cannot distinguish Cauchy () from a finite-mean law or () from finite variance: confidence intervals touch the threshold. Another seed changes the numbers (especially Pareto’s highly variable maximum share); that variability is the information.
Finally, the empirical distribution, DKW band and coverage check:
import numpy as np
from scipy import stats
def ecdf(x):
"""Devuelve F_n como función: F_n(t) = #{x_i <= t} / n, vectorizada en t."""
xs = np.sort(np.asarray(x, dtype=float))
n = len(xs)
return lambda t: np.searchsorted(xs, t, side="right") / n
def dkw_eps(n, delta):
return np.sqrt(np.log(2 / delta) / (2 * n))
def dkw_band(x, delta):
"""Banda de confianza 1 − δ para F: devuelve t ↦ (inferior, superior), recortada a [0, 1]."""
F, eps = ecdf(x), dkw_eps(len(x), delta)
return lambda t: (np.clip(F(t) - eps, 0, 1), np.clip(F(t) + eps, 0, 1))
def distancia_ks(x, cdf):
"""D_n = sup_x |F_n(x) − F(x)|: basta mirar en los saltos, justo antes y justo después. x: (..., n)."""
u = cdf(np.sort(x, axis=-1))
n = u.shape[-1]
i = np.arange(1, n + 1)
return np.maximum((i / n - u).max(axis=-1), (u - (i - 1) / n).max(axis=-1))
rng = np.random.default_rng(0)
x = rng.standard_normal(200)
t = np.array([-1.0, 0.0, 1.0])
inf, sup = dkw_band(x, 0.05)(t)
print("F_n(-1, 0, 1) =", ecdf(x)(t))
print("banda al 95 % en 0 =", (round(float(inf[1]), 3), round(float(sup[1]), 3)), " (F(0) = 0.5)")
print("D_n de la muestra =", round(float(distancia_ks(x, stats.norm.cdf)), 4), " ε_n =", round(float(dkw_eps(200, 0.05)), 4))
# cobertura: la banda contiene a F entera si y solo si D_n <= ε_n
reps = 3000
print(f"\n{'n':>6s} {'δ':>6s} {'ε_n':>8s} {'cobertura simulada':>20s} {'garantía 1−δ':>14s}")
for n in (20, 100, 1000):
D = distancia_ks(rng.standard_normal((reps, n)), stats.norm.cdf)
for delta in (0.5, 0.1, 0.05, 0.01):
eps = dkw_eps(n, delta)
print(f"{n:6d} {delta:6.2f} {eps:8.4f} {100*(D <= eps).mean():19.1f}% {100*(1-delta):13.1f}%")The identity justifying the loop matters: “ fits in the band” is the same as , so coverage is and simulated without drawing. Coverage is always near or above the promise, clearly loose only for . With replicates Monte Carlo error is about percentage points, so coverage slightly below the guarantee ( for ) would be noise, not inequality failure.
With libraries
SciPy provides the exact distribution of (scipy.stats.kstwo) and the Kolmogorov-Smirnov test (scipy.stats.kstest). This measures DKW slack, invisible in asymptotics.
import numpy as np
from scipy import stats
n = 100
print(f"{'t':>6s} {'P(D_n>t) exacta':>16s} {'cota 2e^(-2nt²)':>16s} {'cociente':>9s}")
for t in (0.05, 0.08, 0.10, 0.12, 0.15, 0.20):
exacta = stats.kstwo.sf(t, n)
cota = 2 * np.exp(-2 * n * t * t)
print(f"{t:6.2f} {exacta:16.5f} {cota:16.5f} {cota / exacta:9.2f}")
# el test de Kolmogorov-Smirnov es esta misma comparación: p-valor = P(D_n > D_observado)
rng = np.random.default_rng(1)
x = rng.standard_normal(n)
res = stats.kstest(x, "norm")
print(f"\nkstest: D_n = {res.statistic:.4f}, p-valor = {res.pvalue:.4f} (= kstwo.sf: {stats.kstwo.sf(res.statistic, n):.4f})")
# n mínimo por DKW para una precisión dada, y n real según la ley exacta
eps, delta = 0.05, 0.05
n_dkw = int(np.ceil(np.log(2 / delta) / (2 * eps**2)))
n_ex = next(m for m in range(10, 2000) if stats.kstwo.sf(eps, m) <= delta)
print(f"\nPara ε = {eps} y δ = {delta}: DKW pide n = {n_dkw}; la ley exacta de D_n basta con n = {n_ex}")With the DKW bound is between and times the exact tail throughout the table (and vacuous, above , for small ). It is an excellent tail bound, where it is used. The final calculation quantifies the price of lacking the exact law: for , DKW requires observations and the exact law , seven fewer.
One final calculation, for multiplicative processes, fixes the distinction between ensemble and time averages:
import numpy as np
from scipy.stats import binom
subida, bajada, n = 1.5, 0.6, 100
media_conjunto = (0.5 * subida + 0.5 * bajada) ** n
crec_log = 0.5 * np.log(subida) + 0.5 * np.log(bajada)
print(f"E[W_n] = 1.05^{n} = {media_conjunto:.1f}")
print(f"crecimiento temporal por paso (ley fuerte sobre ln): {crec_log:+.4f} -> W_n ~ {np.exp(crec_log * n):.4f}")
# W_n < 1 si y solo si el número de subidas k es menor que n·(-ln 0.6)/(ln 1.5 - ln 0.6)
k_crit = n * (-np.log(bajada)) / (np.log(subida) - np.log(bajada))
p_pierde = binom.cdf(np.ceil(k_crit) - 1, n, 0.5)
print(f"P(W_{n} < 1) = {p_pierde:.4f}")
rng = np.random.default_rng(0)
k = rng.binomial(n, 0.5, size=200_000)
W = subida**k * bajada ** (n - k)
print(f"media muestral de W_{n}: {W.mean():.1f} (la media verdadera es {media_conjunto:.1f}) mediana: {np.median(W):.4f}")Look at the last line: median is (almost everything is lost), and the sample mean with replicates is around , half the true expectation , because it is sustained by trajectories so rare the sample barely sees them. This is the previous section’s lesson from the other side: with heavy tails, the sample average poorly measures expectation.
Common mistakes
Exercises
Step 1 of 4. What is and what must be bounded?
Step 1 of 4. What is the first step?
More than one answer may be correct.
More than one answer may be correct.
ecdf(x) receives sample x and returns function F such that F(t) is the empirical distribution function at t (a scalar or NumPy array), i.e. the fraction of data less than or equal to t. dkw_band(x, delta) returns function band such that band(t) is the pair (inferior, superior) of DKW band bounds at level , i.e. with , clipped to . Tests check values and simulated coverage.import numpy as np
def ecdf(x):
# devuelve una función F(t) = fracción de datos <= t, vectorizada en t
pass
def dkw_band(x, delta):
# devuelve una función band(t) -> (inferior, superior), recortada a [0, 1]
pass