Markov and Chebyshev give polynomial tails; applying Markov to e^(λX) and optimizing over λ yields exponential tails. This is Chernoff’s method, whose optimal form is the Legendre transform of the cumulant: Cramér’s exact large-deviation exponent. Complete the picture with multiplicative bounds and the second-moment method for lower bounds.
After this lesson you can
Derive Chernoff’s method and calculate bounds for binomial, Poisson, Gaussian and gamma laws.
Interpret the optimal bound as the Legendre transform of the cumulant and state Cramér’s theorem.
Apply multiplicative Chernoff bounds to analyze randomized algorithms.
Obtain lower bounds using the Paley–Zygmund inequality.
Compare non-asymptotic bounds with the CLT approximation in far tails.
A security classifier, compiler or hash function undergoes n independent tests, each failing with unknown probability p. Two engineering questions look alike but differ.
Certification. All n tests pass without failure. How many are needed to assert p<ε with confidence 1−δ? If in fact p≥ε, the probability of no failure is (1−p)n≤(1−ε)n≤e−εn, because 1−x≤e−x. Requiring at most δ gives
n≥εlog(1/δ).
With ε=1% and δ=5% this gives log(20)/0.01=299.6, or 300 tests (exact (1−ε)n requires only 299). This is the ‘rule of three’: log20≈3, so n clean tests bound p by 3/n.
Estimation. We want p^=Sn/n within ε=0.05 of truth with confidence 99%. Chebyshev’s inequality gives P(∣p^−p∣≥ε)≤nε2p(1−p)≤4nε21 and requires n≥1/(4ε2δ)=10000. This lesson’s bound requires 1060. Exact binomial calculation in worst case p=1/2 says 681 suffice. Chebyshev is off by an order of magnitude for a structural reason. With δ=10−9, Chebyshev requires 1011 tests and the exponential bound 4284.
The difference is decay shape. Chebyshev uses only variance and gives a tail falling as 1/n (polynomial); a mean’s true tail falls as e−cn (exponential). If confidence enters via 1/δ in one bound and log(1/δ) in the other, strengthening a guarantee is explosively expensive in one case and almost free in the other. This underlies machine-learning generalization bounds and randomized-algorithm analysis: the Chernoff method, applying Markov to eλX and optimizing λ; its optimal form, the cumulant’s Legendre transform; and Cramér’s theorem, showing this exponent is the exact decay rate, not a loose bound. Finally, lower bounds (Paley-Zygmund) and an honest comparison with the central limit theorem in distant tails.
Intuition: three decay rates
Before formulas, a race. The figure plots a law’s exact tail P(X≥t), Markov, Chebyshev and Chernoff bounds, and the CLT’s normal approximation, on logarithmic scale against z=(t−μ)/σ, threshold measured in standard deviations above the mean. Start with binomial Bin(1000,0.01), counting failures in 1000 tests when p=1%.
InteractiveTail-bound race
Tail P(X≥t) versus each bound, on a logarithmic scale (Bin(1000, 0.01))
exact tail
Markov
Chebyshev
Chernoff
normal (CLT)
Error of each: log10(approximation / exact)
A valid bound always stays above 0. Chernoff grows slowly (the ratio is polynomial in z); Chebyshev and Markov grow without stopping. The normal is not a bound and may cross below 0.
Threshold t (Bin(1000, 0.01))28.88
Exact tail P(X≥t)6.4×10⁻⁷
Markov0.346 ×5.4×10⁵
Chebyshev0.0278 ×4.3×10⁴
Chernoff6.6×10⁻⁶ ×10
Normal approximation (CLT)9.9×10⁻¹⁰ ×0.00154
The normal underestimates this tail by a factor of 648.
First panel: exact tail (black) versus Markov (yellow), Chebyshev (orange), Chernoff (blue) and CLT normal (magenta); second: each error in digits, log10(approximation / exact), so a valid bound is always above 0. The figure starts at z=6: compare readings. Chebyshev and Markov are five or six orders above, Chernoff one, and normal falls below the true tail. By what factor? Switch to Poisson and exponential sums, and lower n to 10: for which law does normal stay close? With pure normal, Chernoff loses a factor growing like z. Finally choose Pareto: look for the blue curve and read the warning.
Four observations, proved in the rest of the lesson:
Markov and Chebyshev decay as powers; the tail exponentially. On logarithmic scale the binomial or Poisson-sum tail drops almost linearly (or faster) as z grows; Chebyshev 1/z2 flattens. Their gap grows without bound in the error panel.
Chernoff nearly parallels the exact tail. Its error grows very slowly: it gets the exponent right even if its prefactor is off. Cramér makes this a theorem.
The CLT normal is not a bound and is very wrong in distant tails. For large z and a skewed law it can be orders of magnitude below the true tail. Asymptotic approximation does not control small probabilities.
Pareto has no blue curve. The method requires E[eλX] finite for some λ>0.
Markov and Chebyshev: what they give and why they fall short
Two results from moments: for X≥0 and a>0, P(X≥a)≤E[X]/a (Markov); and for X∈L2 with mean μ and variance σ2, P(∣X−μ∣≥t)≤σ2/t2 (Chebyshev). Both are tight within laws with those moments, making them poor when we know more. The next game demonstrates: build four-atom laws and try to make P(X≥t) exceed the bound.
InteractiveTry to beat Markov
Law of X≥0 with four atoms (height = mass; the sum is always 1)
Probability: tail versus bounds
tail P(X≥t)
Markov E[X]/t
Cantelli
Mean E[X]1.200
Variance Var(X)1.460
Tail P(X≥t)0.100
Markov E[X]/t0.400
Tail / Markov ratio0.250
Best ratio at this t0.000
Markov on X2: E[X2]/t20.322
Cantelli (uses variance)0.311
Drag the four points: horizontal position changes an atom's location, vertical position its mass (other masses rescale to sum to 1). The lower bar compares tail P(X≥t) (orange) with Markov bound E[X]/t (yellow) and Cantelli (blue), which also uses variance. The tail/Markov ratio never exceeds 1. Try ‘Two points’ and it reaches 1: where is all the mass? Try ‘Near the mean’ and see how far Markov is, and how Cantelli gets close. What additional information improves the bound?
Two lessons. First, ratio P(X≥t)/(E[X]/t) equals 1 exactly when all mass is at {0,t}, strictly less for any other distribution. Markov is tight in the worst case and loose in nearly all others. Second, for a law concentrated around its mean, Markov ignores that information. More moments change the picture. Cantelli’s useful Chebyshev variant handles one-sided tails.
Proof
Let u≥0. If X−μ≥s, then X−μ+u≥s+u>0 and squaring gives (X−μ+u)2≥(s+u)2. By Markov on nonnegative (X−μ+u)2,
P(X−μ≥s)≤(s+u)2E[(X−μ+u)2]=(s+u)2σ2+u2.
The right side is minimized at u=σ2/s, where it equals σ2/(σ2+s2).
∎
With s=3σ it gives 1/10 versus Chebyshev’s 1/9, and is the best bound using only μ and σ2 (tight, like Chebyshev). Yet all have a fundamental problem for averages. For Xˉn of n iid variables with variance σ2, Chebyshev gives P(Xˉn−μ≥ε)≤σ2/(nε2), decreasing as 1/n, while the CLT suggests e−nε2/(2σ2). How capture all moments at once? The exponential: eλx=∑k≥0(λx)k/k! packs moments of all orders with weights adjusted by λ. Applying Markov to eλX applies it to all powers at once; choosing the best λ chooses the best combination.
Chernoff’s method
Let X be a real random variable. Write M(λ)=E[eλX]∈(0,+∞] for its moment-generating function and ψ(λ)=logM(λ) for its cumulant-generating function, convex, equal to 0 at λ=0, and satisfying ψ′(0)=μ and ψ′′(0)=σ2 where they exist.
Proof
With λ>0, function x↦eλx is strictly increasing, so {X≥t}={eλX≥eλt}. Variable eλX is nonnegative and Markov gives P(X≥t)≤E[eλX]/eλt. With λ=0 the bound is 1. Since it holds for every λ≥0, it holds for the best: P(X≥t)≤infλe−(λt−ψ(λ))=exp(−supλ{λt−ψ(λ)}). Finally, Jensen’s inequality gives ψ(λ)≥λμ for every λ; if λ<0 and t≥μ, then λt−ψ(λ)≤λ(t−μ)≤0, no larger than 0 already attained at λ=0.
∎
Three practical features. It is nonasymptotic: valid for every t and law, without n→∞. Independence is not required; it only appears when calculating M of a sum by factorization. All difficulty is choosing λ, a one-variable convex optimization problem: λ↦λt−ψ(λ) is concave because ψ is convex. At an interior optimum the derivative vanishes, giving ψ′(λ∗)=t. Meaning: ψ′(λ) is the mean of the tilted law eλx−ψ(λ)P(dx) (exponential tilting), and optimal λ tilts until t is no longer rare but its mean.
InteractiveOptimizing λ and the Legendre transform
Cumulant function ψ(λ), line λt and their gap
ψ(λ)
line λt
tangent to ψ at λ
gap g(λ)
Bound e−ng(λ) (logarithmic scale, n=10)
Rate function I(t)=supλ≥0{λt−ψ(λ)} as t moves
I(t)
(t−μ)2/(2σ2)
Gap g(λ)=λt−ψ(λ)0.113
Bound e−ng(λ) for P(Xˉ10≥t)0.324
Best bound e−nI(t)0.147
λ∗ and I(t)1.253 and 0.192
Tilted-law mean ψ′(λ)0.402
Main panel: cumulant ψ(λ) (blue), line λt (orange), and vertical gap g(λ)=λt−ψ(λ) (purple); the dashed tangent has slope ψ′(λ). Second: bound e−ng(λ) (purple), falling then rising. Move λ to the minimum or press ‘Go to optimal λ∗’: the tangent is parallel to the line, ψ′(λ∗)=t. Slide t or press ‘Sweep t’: the maximum gap in panel three is rate function I(t), zero at the mean and near (t−μ)2/(2σ2) nearby. Change law: what happens at λ=1 for exponential, or any λ>0 for Pareto?
Five laws, five exponents
In the table λ∗ solves ψ′(λ∗)=t for each law (one variable X; for the average of n iid copies replace P(X≥t) by P(Xˉn≥t) and the bound by e−nI(t), as below).
Law of X
ψ(λ)
λ∗
I(t)
N(μ,σ2)
μλ+σ2λ2/2
(t−μ)/σ2
(t−μ)2/(2σ2)
Pois(μ)
μ(eλ−1)
log(t/μ)
tlogμt−t+μ
Bern(p)
log(1−p+peλ)
logp(1−t)t(1−p)
tlogpt+(1−t)log1−p1−t
Exp(1)
−log(1−λ), λ<1
1−1/t
t−1−logt
Rademacher ±1
logcoshλ
artanht
21+tlog(1+t)+21−tlog(1−t)
Two rows take one line each. For normal, λt−μλ−σ2λ2/2 is a parabola maximized at λ∗=(t−μ)/σ2 with value (t−μ)2/(2σ2), so P(X≥t)≤e−(t−μ)2/(2σ2). The true tail is Φˉ(z)=1−Φ(z) with z=(t−μ)/σ, behaving by Mills ratio as e−z2/2/(z2π): Chernoff gets exponent z2/2 right and loses factor z2π. With z=5 that factor is 12.5; exact tail is 2.87×10−7 and bound 3.73×10−6.
For a Bernoulli mean, ψ′(λ)=peλ/(1−p+peλ)=t gives eλ∗=t(1−p)/(p(1−t)). Then ψ(λ∗)=log1−t1−p and
the Kullback-Leibler divergence between Bern(t) and Bern(p). Combinatorially: for n tosses of an Bern(p) coin, the probability of a specific sequence of empirical frequency a times the number (nan)≈enH(a) of such sequences is e−nKL(a∥p) up to polynomial factors in n (method of types). In information theory KL(a∥p) is the excess nats per symbol paid to encode source Bern(a) with an optimal code for Bern(p).
Averages of iid variables and Hoeffding’s bound
Let X1,…,Xn be independent and identically distributed with cumulant ψ. Expectation of an independent product is the product of expectations, so ψSn(λ)=nψ(λ); applying the theorem to Sn with t=na,
with the same single-variable I: n multiplies the exponent. This yields exponential tails. For Bernoulli, I(a)=KL(a∥p); a simple inequality gives a bound without logarithms.
Proof
Let f(a)=KL(a∥p)−2(a−p)2. Then f(p)=0, f′(a)=logpa−log1−p1−a−4(a−p), so f′(p)=0, and f′′(a)=a(1−a)1−4≥0 because a(1−a)≤1/4. A convex function with f(p)=f′(p)=0 satisfies f≥0. The one-sided bound follows from e−nKL≤e−2nε2 with a=p+ε (the left tail is symmetric on exchanging successes and failures), and the two-sided bound from adding both via the union bound.
∎
This is Hoeffding for Bernoulli; the next lesson proves the general bounded-variable version (Hoeffding). Required sample size to estimate p to ±ε with confidence 1−δ is n≥log(2/δ)/(2ε2), giving the motivating 1060. For a thousand coins P(∣p^−0.5∣≥0.05)≤2e−2⋅1000⋅0.0025=2e−5=0.0135, versus Chebyshev’s 0.1; the exact tail is 0.0017.
When the method does not apply
The theorem has no assumptions, but its conclusion may be vacuous: if M(λ)=+∞ for every λ>0, bound e−λtM(λ) equals +∞ and says nothing. This happens for heavy tails: Pareto of index α has P(X≥t)=t−α and E[eλX]=∫1∞eλxαx−α−1dx=∞ for every λ>0, even though α=3 gives finite mean and variance. This is a limit of reality, not method: the true tail falls as a power and no exponential bound can hold. Indeed M(λ)<∞ for some λ>0 essentially means the right tail falls at least exponentially. For heavy tails use finite-order moments: best order-k<α Markov bound is E[Xk]/tk=α−kαt−k, decaying as t−k but never as t−α. It is the dashed yellow curve for Pareto.
Multiplicative bounds
Hoeffding does not distinguish frequent and rare events: exponent 2nε2 depends only on absolute distance ε, not p. It is very poor for rare events. With n=1000 and p=0.01, bounding P(Sn≥30) (i.e. ε=0.02) by Hoeffding gives e−0.8=0.45, uninformative when true probability is two ten-millionths. The multiplicative form measures relative deviation δ from mean μ=E[Sn] and is a randomized-algorithms tool.
Proof
Each summand’s generating function is E[eλXi]=1+pi(eλ−1)≤exp(pi(eλ−1)), by 1+x≤ex. Independence gives MX(λ)≤exp(μ(eλ−1)), the cumulant of Pois(μ): for the generating function, a Bernoulli sum is never worse than a Poisson of equal mean. With λ>0, Markov gives P(X≥(1+δ)μ)≤exp(μ(eλ−1)−λ(1+δ)μ), and λ=log(1+δ), zeroing the exponent derivative, gives exp(μ(δ−(1+δ)log(1+δ))), the first bound. To simplify, f(δ)=log(1+δ)−2+δ2δ satisfies f(0)=0 and f′(δ)=(1+δ)(2+δ)2δ2≥0, so log(1+δ)≥2+δ2δ and (1+δ)log(1+δ)−δ≥2+δδ2.
For the lower tail use λ=log(1−δ)<0: P(X≤(1−δ)μ)=P(eλX≥eλ(1−δ)μ)≤e−λ(1−δ)μMX(λ)≤exp(μ(−δ−(1−δ)log(1−δ))). And g(δ)=(1−δ)log(1−δ)+δ−δ2/2 satisfies g(0)=0 and g′(δ)=−log(1−δ)−δ≥0, so (1−δ)log(1−δ)≥−δ+δ2/2 and the exponent is at most −μδ2/2.
∎
With X∼Bin(1000,0.01), μ=10 and P(X≥30) this is case δ=2: (e2/27)10=2.36×10−6, versus exact 2.06×10−7 (bound off by factor 11, Hoeffding by millions). The simplified version gives e−4⋅10/4=4.5×10−5, much looser: form δ2μ/(2+δ) is convenient but discards factor 20 here. The bound depends neither on n nor individual pi, only μ.
The simplified form resembles Bernstein: for centered summands bounded by 1 and total variance v≤μ, Bernstein gives P(X−μ≥s)≤exp(−s2/(2v+2s/3)), which with s=δμ becomes exp(−δ2μ/(2+2δ/3)), nearly the same exponent. Both depend on variance, not only range as Hoeffding does.
Rate function and Cramér’s theorem
So far Chernoff is a bound. Can its exponent improve: is e−nJ(a) with J>I still valid? No. To understand why, inspect I.
Proof
A supremum of affine functions of t is convex. I(μ)=0 by Jensen as before, and I≥0 by taking λ=0. If λt solves ψ′(λt)=t, differentiating I(t)=λtt−ψ(λt) gives I′(t)=λt′t+λt−ψ′(λt)λt′=λt. Since λt is the inverse of ψ′, differentiable with ψ′′>0 (the law is nonconstant), the inverse function theorem gives λt′=1/ψ′′(λt). At t=μ, λμ=0 and ψ′′(0)=σ2, giving I(μ)=I′(μ)=0 and I′′(μ)=1/σ2: Taylor expansion.
∎
The last equality says near the mean, the rate function is the CLT parabola. Exponential e−nI(a) with I(a)≈(a−μ)2/(2σ2) is Gaussian e−z2/2 in variable z=n(a−μ)/σ. Far from the mean I departs from the parabola; this difference (skewness and cumulants of order three and above) is what the CLT loses. The previous figure showed the blue curve and dashed parabola touching at t=μ, then diverging.
Now the result answering the section’s initial question.
Proof
The upper bound (for every n) is Chernoff’s above. For the lower bound tilt the law. Let λ=λa>0 and Q be the law with density dQ/dP=eλx−ψ(λ) relative to Xi, a probability by definition of ψ. For iid Xi of law Q, mean is ψ′(λ)=a and variance s2=ψ′′(λ)∈(0,∞). By change of measure, dPn/dQn=e−λSn+nψ(λ), and for δ>0,
because on the event −λSn=−λnXˉn≥−λn(a+δ). Under Q, the mean of Xˉn is exactly a, so by the CLT, Q(a≤Xˉn<a+δ)=Q(0≤n(Xˉn−a)/s<δn/s)→1/2. Taking n1log and n→∞ gives liminfn1logP(Xˉn≥a)≥−(λa−ψ(λ))−λδ=−I(a)−λδ. Let δ→0.
∎
The proof teaches more: rare event {Xˉn≥a} occurs, when it does, in the cheapest way, as if Xi were drawn from tilted law Q with mean a. This is large-deviation intuition and importance sampling: estimate a rare probability by simulating under Q, where the event is typical, then correct with the likelihood ratio. You will do this in code.
Cramér’s theorem is more general (in R, Dembo and Zeitouni prove the large-deviation principle for Xˉn with rate function I without assumptions on λa or finiteness of ψ near zero, although the limit may fail where I is discontinuous). Under additional conditions the Bahadur-Rao formula refines it: P(Xˉn≥a)∼e−nI(a)/(λaσa2πn), with σa2=ψ′′(λa). Prefactor n−1/2 is the polynomial part Chernoff discards. For Bernoulli, I(a)=KL(a∥p) is the simplest Sanov theorem case, extending Cramér from means to entire empirical distributions.
InteractiveThe large-deviation exponent
Exponent −n1lnP(Xˉn≥a) versus n
exact exponent (n multiple of 2, na integer)
other n (rounding na)
I(a), the limit
Bahadur-Rao
simulation (hollow: fewer than 10 hits)
Rate function I(a) and the CLT parabola
I(a)=KL(a∥p)
(a−p)2/(2p(1−p)) (CLT)
Rate function I(a)=KL(a∥p)0.0872 nats
Exact exponent at n=6000.0920 (+5.5 %)
P(Xˉ600≥a) exact1.1×10⁻²⁴
Chernoff bound e−nI(a)1.9×10⁻²³
Simulation hits at n=6000 of 3000
n with e−nI(a)≤10−6159
Left: −n1logP(Xˉn≥a) for Bernoulli(p) averages: black is exact (binomial sum), blue is limit I(a)=KL(a∥p), orange points simulate 3000 trajectories. The curve descends toward I(a), always above it (Chernoff bound), slowly: at n=600 a few percent remains. The thick curve uses n with integer na; thin gray uses the rest, with sawteeth from rounding na up. Enable Bahadur-Rao correction (purple) to see it closely match black. Simulation runs out of hits (hollow points, then none) once probability falls below 1/3000: this cannot estimate a rare event. Right: I(a) versus the CLT parabola. Move a and p: when do they diverge?
Lower bounds: Paley-Zygmund and the second-moment method
Chernoff, Markov and Chebyshev are upper probability bounds. Proving something occurs with positive probability (a random graph contains a triangle, random search finds a solution) needs the opposite: a lower bound. The tool is Paley-Zygmund.
Proof
Write μ=E[X] and decompose μ=E[X1[X≤θμ]]+E[X1[X>θμ]]. The first term is at most θμ. For the second Cauchy-Schwarz gives E[X1[X>θμ]]≤E[X2]P(X>θμ). Thus (1−θ)μ≤E[X2]P(X>θμ), and squaring both nonnegative sides yields the inequality.
∎
The second-moment method uses the bound with θ=0: if E[X2]≤(1+o(1))E[X]2, then P(X>0)→1. It robustly restates a known argument. Chebyshev gives P(X=0)≤Var(X)/E[X]2, Paley-Zygmund Var(X)/E[X2], always better because E[X2]≥E[X]2. Compare the figure readings.
InteractiveHow much mass remains above θ·E[X]?
The law of X (Poisson(1.5)) and region {X>θE[X]}
P(X>θE[X]) versus the Paley–Zygmund bound
P(X>θE[X])
(1−θ)2E[X]2/E[X2]
E[X] and E[X2]1.500 and 3.750
P(X>θE[X]) exact, θ=0.300.7769
Paley–Zygmund bound0.2940
Bound on P(X=0): Chebyshev Var/E[X]20.6667
Bound on P(X=0): second moment Var/E[X2]0.4000
Left: law of X≥0 with region {X>θE[X]} shaded. Right: exact tail (black) versus Paley-Zygmund bound (blue) as θ varies. The bound never exceeds the tail. With ‘Two points’ and θ=0 they touch. For lognormal, increasing σ sends E[X2]=eσ2 soaring and the bound plunges although X>0 always: two moments do not reveal mass away from zero. With Poisson and θ=0, the bound is close when m is small. What happens for large m and θ>0 when the law concentrates around its mean?
Chernoff versus CLT for rare events
The lesson began with normal approximation diverging from the true tail. Quantify it for the same binomial, Bin(1000,0.01), and P(S≥30).
Method
Value
Factor versus exact
Exact tail
2.06×10−7
1
Normal approximation (z=6.36)
1.03×10−10
1/2000
Chernoff bound e−nKL(0.03∥0.01)
1.92×10−6
9.3
Hoeffding e−2n(0.02)2
0.45
2×106
Bahadur-Rao (lattice)
2.11×10−7
1.03
Normal underestimates probability by factor 2000: a model relying on the CLT would call ‘impossible’ an event occurring once per five million batches of a thousand tests. In security, where those tests are run, this distinguishes seeing a failure from missing it. Chernoff is off by factor 9.3 but on the safe side; Bahadur-Rao, recovering the polynomial prefactor, by 3%.
Why does the CLT fail if it is a theorem? It says P(Sn≥nμ+zσn)→Φˉ(z) for each fixedz, with absolute error O(1/n) by Berry-Esseen. Here that guarantee is 0.148 (with Shevtsova’s constant 0.4748), far above probability 2×10−7. Absolute error 0.15 says nothing about an event of probability 10−7. Relative error matters; Cramér’s moderate-deviation theorem controls it: with ψ finite near 0, P(Sn≥nμ+zσn)/Φˉ(z)→1 uniformly over 0≤z=o(n1/6). Beyond that, the ratio has an exponential factor (Cramér series), whose first exponent term is κ3z3/(6σ3n) with κ3 the third cumulant. This gives n1/6: the term is negligible only if z3≪n. With n=1000, n1/6=3.2, and z=6.4 lies well outside this region, especially with Bern(0.01)‘s strong skewness, coefficient κ3/σ3 equal to 9.8. With a fair coin κ3=0 the term vanishes and normal at z=6.3 stays within 7%.
The CLT concerns the distribution’s center; Chernoff and Cramér concern its tails. When rare events matter, as in security, reliability or risk estimation, use a nonasymptotic bound or saddlepoint approximation (Lugannani-Rice) built from ψ.
Implementation from scratch
Start with the table’s cumulants, golden-section optimization of λ (a concave one-variable function requiring no derivatives), and four bounds compared with exact scipy.stats tails.
[ ]Tail-bound calculatorBrowser
import numpy as np
from math import log, exp, sqrt, ceil, inf
from scipy import stats
# cumulantes psi(lambda) = ln E[e^{lambda X}] (inf fuera del dominio)
def cgf_bernoulli(p): return lambda l: float(np.log1p(p * np.expm1(l)))
def cgf_poisson(m): return lambda l: float(m * np.expm1(l))
def cgf_normal(mu, s2): return lambda l: mu * l + 0.5 * s2 * l * l
def cgf_gamma(k, theta=1.0):
return lambda l: -k * float(np.log1p(-l / theta)) if l < theta else inf
def suma(psi, n): return lambda l: n * psi(l) # la cumulante es aditiva
def maximizar_concava(f, lo, hi, tol=1e-12):
"""Máximo de una función cóncava en [lo, hi] por sección áurea."""
g = (sqrt(5) - 1) / 2
a, b = lo, hi
c, d = b - g * (b - a), a + g * (b - a)
fc, fd = f(c), f(d)
while b - a > tol * (1 + abs(a) + abs(b)):
if fc > fd:
b, d, fd = d, c, fc
c = b - g * (b - a); fc = f(c)
else:
a, c, fc = c, d, fd
d = a + g * (b - a); fd = f(d)
x = 0.5 * (a + b)
return x, f(x)
def chernoff(psi, t, lam_max=50.0):
"""Cota de Chernoff exp(-I(t)) y el lambda óptimo, con I(t) = sup_{0<=l<=lam_max} (l t - psi(l))."""
lam, val = maximizar_concava(lambda l: l * t - psi(l), 0.0, lam_max)
return exp(-max(val, 0.0)), lam
def markov(media, t): return min(1.0, media / t)
def chebyshev(media, var, t): return min(1.0, var / (t - media) ** 2)
def cantelli(media, var, t): return var / (var + (t - media) ** 2)
casos = [
("Bin(1000, 0.01), t = 30", 10.0, 9.9, suma(cgf_bernoulli(0.01), 1000), 50.0, stats.binom.sf(29, 1000, 0.01)),
("Poisson(10), t = 30", 10.0, 10.0, cgf_poisson(10), 50.0, stats.poisson.sf(29, 10)),
("Normal(0, 1), t = 5 ", 0.0, 1.0, cgf_normal(0, 1), 50.0, stats.norm.sf(5)),
("Gamma(5, 1), t = 25", 5.0, 5.0, cgf_gamma(5), 1 - 1e-9, stats.gamma.sf(25, 5)),
]
print(f"{'':27s}{'exacta':>10s}{'Markov':>10s}{'Chebyshev':>10s}{'Cantelli':>10s}{'Chernoff':>10s}{'lambda*':>10s}")
for nombre, mu, v, psi, lmax, ex in casos:
t = float(nombre.split("=")[-1])
cota, lam = chernoff(psi, t, lmax)
mk = markov(mu, t) if mu > 0 else float("nan") # Markov exige X >= 0: no aplica a la normal
print(f"{nombre:27s}{ex:10.2e}{mk:10.2e}{chebyshev(mu, v, t):10.2e}{cantelli(mu, v, t):10.2e}{cota:10.2e}{lam:10.3f}")
The table confirms the first figure’s race across four laws. Markov and Chebyshev are five or six orders off; Chernoff by a factor between 9 and 24. Normal λ∗ is exactly t=5, Poisson’s is log3=1.099, and binomial is close at 1.119, as in formula logp(1−t)t(1−p) with t=0.03. Implementation detail: maximizar_concava evaluates ψ only inside [0,λmax], so exponential, with ψ=∞ from λ=1 onward, works by passing lam_max just below the boundary.
Now the motivating application: sample sizes, comparing three rules to exact calculation.
[ ]How many tests are neededBrowser
def n_certificar(eps, delta): return ceil(log(1 / delta) / eps)
def n_chebyshev(eps, delta): return ceil(1 / (4 * eps**2 * delta))
def n_hoeffding(eps, delta): return ceil(log(2 / delta) / (2 * eps**2))
def cola2(n, p, eps):
"""P(|S/n - p| >= eps) exacta, con la binomial."""
k_hi = ceil(n * (p + eps) - 1e-9); k_lo = np.floor(n * (p - eps) + 1e-9)
return stats.binom.sf(k_hi - 1, n, p) + stats.binom.cdf(k_lo, n, p)
def n_exacto(eps, delta, p=0.5, nmax=3000):
"""Menor n a partir del cual la cola bilateral es <= delta (con p = 1/2, el peor caso)."""
malos = [n for n in range(1, nmax) if cola2(n, p, eps) > delta]
return malos[-1] + 1
print("certificar p < 1 % con confianza 95 %: n =", n_certificar(0.01, 0.05),
" (con (1-eps)^n exacto:", ceil(log(0.05) / log(0.99)), ")")
for delta in [0.01, 1e-3, 1e-6, 1e-9]:
print(f"estimar p +- 0.05 con confianza {1 - delta:.9f}: Chebyshev {n_chebyshev(0.05, delta):>12,}"
f" Hoeffding {n_hoeffding(0.05, delta):>6,}", " exacto", n_exacto(0.05, delta) if delta >= 1e-3 else "")
Chebyshev grows as 1/δ (factor 1000 whenever δ drops three orders), Hoeffding as log(1/δ) (1060 to 4284 when 10−2 becomes 10−9). At δ=10−9, estimating a proportion to ±5% with near-certain confidence costs thousands, not one hundred billion tests.
Now the rate function, calculated numerically and checked against the table’s formulas, and importance sampling exploiting Cramér’s proof.
[ ]Rate function and exponential tiltingBrowser
def tasa(psi, t, lam_max=50.0):
"""I(t) = sup_{lambda >= 0} (lambda t - psi(lambda)) por sección áurea."""
lam, val = maximizar_concava(lambda l: l * t - psi(l), 0.0, lam_max)
return max(val, 0.0)
def kl_bern(a, p): return a * log(a / p) + (1 - a) * log((1 - a) / (1 - p))
print("Bernoulli(0.3): t, I numérica, KL(t || p)")
for t in [0.3, 0.5, 0.8, 0.95]:
print(f" {t:5.2f} {tasa(cgf_bernoulli(0.3), t):.10f} {kl_bern(t, 0.3) if t > 0.3 else 0:.10f}")
print("Exponencial(1): I(t) = t - 1 - ln t")
for t in [1.5, 3, 6]:
print(f" {t:5.2f} {tasa(cgf_gamma(1), t, 1 - 1e-9):.10f} {t - 1 - log(t):.10f}")
# Muestreo por importancia: P(Bin(1000, 0.01) >= 30), un suceso de probabilidad ~2e-7
rng = np.random.default_rng(7)
n, p, k = 1000, 0.01, 30
a = k / n
exacta = stats.binom.sf(k - 1, n, p)
N = 20000
ingenuo = rng.binomial(n, p, size=N)
print(f"\nexacta {exacta:.3e}; Monte Carlo ingenuo: {np.mean(ingenuo >= k):.3e} ({int(np.sum(ingenuo >= k))} aciertos de {N})")
K = rng.binomial(n, a, size=N) # ley inclinada: Bin(n, a) tiene media k
w = (p / a) ** K * ((1 - p) / (1 - a)) ** (n - K) # dP/dQ evaluado en la muestra
z = w * (K >= k)
print(f"importancia (ley inclinada): {z.mean():.3e} +- {z.std() / sqrt(N):.1e} ({int(np.sum(K >= k))} aciertos de {N})")
Numerical rate functions match closed forms to ten figures. Importance sampling says it all: with 20000 simulations the naive method sees no event (expected 0.004 hits), whereas simulation under tilted law Bin(n,0.03) estimates 2.05×10−7 with 2% error, versus exact 2.06×10−7. Cramér’s theorem in code.
With libraries
scipy provides scalar optimization and relative entropy functions, allowing three checks of Bernoulli’s rate function: optimization with scipy.optimize, golden section, and formula KL with scipy.special.rel_entr.
[ ]Rate function with SciPyBrowser
from scipy import optimize, special
def tasa_scipy(psi, t, lam_max=50.0):
r = optimize.minimize_scalar(lambda l: psi(l) - l * t, bounds=(0, lam_max), method="bounded",
options={"xatol": 1e-12})
return -r.fun
psi = cgf_bernoulli(0.3)
print("t scipy.optimize sección áurea rel_entr")
for t in [0.5, 0.8]:
print(f"{t} {tasa_scipy(psi, t):.10f} {tasa(psi, t):.10f} "
f"{special.rel_entr(t, 0.3) + special.rel_entr(1 - t, 0.7):.10f}")
# la cola exacta en escala logarítmica evita el desbordamiento en colas muy lejanas
print("\nlog P(Bin(10000, 0.5) >= 5600) =", stats.binom.logsf(5599, 10000, 0.5),
" cota de Chernoff: ", -10000 * kl_bern(0.56, 0.5))
For very small probabilities always use logsf: sf returns 0 below about 10−308, whereas logsf preserves the value. Chernoff bound −nKL=−72.2 is close to tail log −75.5: their difference 3.3 is the log of Bahadur-Rao prefactor λσ2πn (with lattice adjustment 1−e−λ instead of λ).
Common mistakes
Exercises
ProofFrom Markov to Chebyshev and Chernoff
Prove: Prove (a) Markov's inequality: if X≥0 and a>0, P(X≥a)≤E[X]/a; (b) Chebyshev's: if X∈L2 has mean μ and variance σ2, P(∣X−μ∣≥t)≤σ2/t2; (c) Chernoff's bound: for every λ>0, P(X≥t)≤e−λtE[eλX].
0
All three apply the same idea to different functions of X.
Step 1 of 4. (a) What is Markov's key step?
ProofMultiplicative bound for Bernoulli sums
Prove: Let X1,…,Xn be independent with Xi∼Bern(pi), X=∑iXi and μ=E[X]. Show that for every δ>0, P(X≥(1+δ)μ)≤(eδ/(1+δ)1+δ)μ≤exp(−δ2μ/(2+δ)).
0
Apply Chernoff to the sum and bound each summand's generating function.
Step 1 of 3. How do you bound E[eλX]?
ProofPaley-Zygmund
Prove: If X≥0 has E[X2]<∞ and E[X]=μ>0, then for every θ∈[0,1], P(X>θμ)≥(1−θ)2μ2/E[X2].
0
Split expectation of X according to whether X is below or above the threshold.
Step 1 of 4. How do you start?
NumericOne thousand tosses and Chebyshev
A fair coin is tossed 1000 times. Use Chebyshev's inequality to bound P(∣Sn/n−0.5∣≥0.05).
NumericOne thousand tosses and Chernoff-Hoeffding
For the same 1000 fair-coin tosses, calculate bound 2e−2nε2 for P(∣Sn/n−0.5∣≥0.05).
NumericTests for certification
A system passes n independent tests with no failure. You want to conclude with 99% confidence (δ=0.01) that its failure rate is below ε=0.005. Using e−εn≤δ, what is the smallest sufficient integer n?
NumericChernoff for a Poisson
Let X∼Pois(10). Calculate Chernoff bound e−μ(eμ/t)t for P(X≥15).
NumericExponential rate function
For X∼Exp(1), ψ(λ)=−log(1−λ) if λ<1. Calculate I(3)=supλ{3λ−ψ(λ)}.
NumericAn audit without false alarms
A model independently fails each test with probability p=0.01. An auditor rejects it if n cases show at least a 3% failure rate. What is the smallest n for which Chernoff bound e−nKL(0.03∥0.01) guarantees unfair rejection probability at most 10−9?
QuizWhy tilt to the threshold?
Cramér's lower bound changes to tilted law Q with ψ′(λ)=a. Why precisely that λ?
QuizPareto without Chernoff
Why can the Chernoff method not use a Pareto variable with α=3, which has finite mean and variance?
QuizA tool for a rare event
With S∼Bin(1000,0.01) you want a safe bound on P(S≥30)=2.06×10−7. Which tool gives the right order of magnitude without underestimating?
QuizWhat holds and what does not
Which statements are true?
More than one answer may be correct.
CodeNumerical rate function
Implement rate_function(cgf, t, lam_max=50.0) returning I(t)=sup0≤λ≤λmax{λt−ψ(λ)}, with cgf the cumulant ψ (a scalar function returning inf outside its domain). Do not use scipy: maximize concave λ↦λt−ψ(λ) by golden-section search or bisection on the numerical derivative. If t does not exceed the mean, return 0 (supremum attained at λ=0). Tests check closed forms for Bernoulli, Poisson, normal and exponential (for the latter pass lam_max just below 1).
import numpy as np
def rate_function(cgf, t, lam_max=50.0):
"""I(t) = sup_{0 <= lam <= lam_max} (lam * t - cgf(lam)), con 0 como mínimo valor."""
# tu código: sección áurea sobre g(lam) = lam * t - cgf(lam) en [0, lam_max]
return 0.0
Shift+Enter to run
Summary
Key idea
Apply Markov to eλX and optimize λ to obtain P(X≥t)≤e−I(t) with I the cumulant’s Legendre transform: exponential rather than polynomial tails, valid for every n, with an exact exponent by Cramér. The CLT is unsuitable for rare events; use the second moment for lower bounds.
Chernoff.P(X≥t)≤infλ≥0e−λtM(λ)=e−I(t). For an average of n iid variables, P(Xˉn≥a)≤e−nI(a) with the same I. The optimum satisfies ψ′(λ∗)=t: tilt until t is the mean.
Examples. Normal: I=(t−μ)2/(2σ2). Poisson: tlog(t/μ)−t+μ. Bernoulli: KL(t∥p), giving Hoeffding via Pinsker: 2e−2nε2 for both sides.
Multiplicative. For independent Bernoulli sums, P(X≥(1+δ)μ)≤(eδ/(1+δ)1+δ)μ≤e−δ2μ/(2+δ) and P(X≤(1−δ)μ)≤e−δ2μ/2: mean-sensitive, useful for rare events and randomized algorithms.
Cramér.n1logP(Xˉn≥a)→−I(a): the exponent cannot improve. The proof tilts until a is the mean and applies the CLT under the tilted law. Near the mean I≈(t−μ)2/(2σ2); far away it departs from the parabola.
Paley-Zygmund.P(X>θE[X])≥(1−θ)2E[X]2/E[X2]: the second-moment method gives lower bounds and improves Chebyshev for P(X=0).
Caution. The CLT fails in distant tails (relative, not absolute error); Chernoff requires M(λ)<∞ for some λ>0 (not Pareto); a two-sided event needs union-bound factor 2; a bound valid for every n is not an asymptotic approximation.