Module contents
Lesson 19 of 24Core 90 min

The Chernoff method and large deviations

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.

Before you start

Motivation: how many tests are needed?

A security classifier, compiler or hash function undergoes nn independent tests, each failing with unknown probability pp. Two engineering questions look alike but differ.

Certification. All nn tests pass without failure. How many are needed to assert p<εp < \varepsilon with confidence 1−δ1 - \delta? If in fact p≥εp \ge \varepsilon, the probability of no failure is (1−p)n≤(1−ε)n≤e−εn(1 - p)^n \le (1 - \varepsilon)^n \le e^{-\varepsilon n}, because 1−x≤e−x1 - x \le e^{-x}. Requiring at most δ\delta gives

n≥log⁡(1/δ)ε.n \ge \frac{\log(1/\delta)}{\varepsilon}.

With ε=1 %\varepsilon = 1\,\% and δ=5 %\delta = 5\,\% this gives log⁡(20)/0.01=299.6\log(20)/0.01 = 299.6, or 300300 tests (exact (1−ε)n(1-\varepsilon)^n requires only 299299). This is the ‘rule of three’: log⁡20≈3\log 20 \approx 3, so nn clean tests bound pp by 3/n3/n.

Estimation. We want p^=Sn/n\hat p = S_n/n within ε=0.05\varepsilon = 0.05 of truth with confidence 99 %99\,\%. Chebyshev’s inequality gives P(∣p^−p∣≥ε)≤p(1−p)nε2≤14nε2\Pr(\abs{\hat p - p} \ge \varepsilon) \le \dfrac{p(1-p)}{n\varepsilon^2} \le \dfrac{1}{4n\varepsilon^2} and requires n≥1/(4ε2δ)=10 000n \ge 1/(4\varepsilon^2\delta) = 10\,000. This lesson’s bound requires 1 0601\,060. Exact binomial calculation in worst case p=1/2p = 1/2 says 681681 suffice. Chebyshev is off by an order of magnitude for a structural reason. With δ=10−9\delta = 10^{-9}, Chebyshev requires 101110^{11} tests and the exponential bound 4 2844\,284.

The difference is decay shape. Chebyshev uses only variance and gives a tail falling as 1/n1/n (polynomial); a mean’s true tail falls as e−cne^{-cn} (exponential). If confidence enters via 1/δ1/\delta in one bound and log⁡(1/δ)\log(1/\delta) 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λXe^{\lambda X} and optimizing λ\lambda; 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)\Pr(X \ge t), Markov, Chebyshev and Chernoff bounds, and the CLT’s normal approximation, on logarithmic scale against z=(t−μ)/σz = (t - \mu)/\sigma, threshold measured in standard deviations above the mean. Start with binomial Bin⁡(1000,0.01)\Bin(1000, 0.01), counting failures in 10001000 tests when p=1 %p = 1\,\%.

InteractiveTail-bound race
Tail P(X≥t)\Pr(X \ge t) versus each bound, on a logarithmic scale (Bin(1000, 0.01))
  • exact tail
  • Markov
  • Chebyshev
  • Chernoff
  • normal (CLT)
Error of each: log⁡10\log_{10}(approximation / exact)
exact
A valid bound always stays above 0. Chernoff grows slowly (the ratio is polynomial in zz); Chebyshev and Markov grow without stopping. The normal is not a bound and may cross below 0.
1000
0.01
6.00
Threshold tt (Bin(1000, 0.01))28.88
Exact tail P(X≥t)\Pr(X \ge 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, log⁡10\log_{10}(approximation / exact), so a valid bound is always above 0. The figure starts at z=6z = 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 nn to 1010: for which law does normal stay close? With pure normal, Chernoff loses a factor growing like zz. Finally choose Pareto: look for the blue curve and read the warning.

Four observations, proved in the rest of the lesson:

  1. Markov and Chebyshev decay as powers; the tail exponentially. On logarithmic scale the binomial or Poisson-sum tail drops almost linearly (or faster) as zz grows; Chebyshev 1/z21/z^2 flattens. Their gap grows without bound in the error panel.
  2. 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.
  3. The CLT normal is not a bound and is very wrong in distant tails. For large zz and a skewed law it can be orders of magnitude below the true tail. Asymptotic approximation does not control small probabilities.
  4. Pareto has no blue curve. The method requires E[eλX]\E[e^{\lambda X}] finite for some λ>0\lambda > 0.

Markov and Chebyshev: what they give and why they fall short

Two results from moments: for X≥0X \ge 0 and a>0a > 0, P(X≥a)≤E[X]/a\Pr(X \ge a) \le \E[X]/a (Markov); and for X∈L2X \in L^2 with mean μ\mu and variance σ2\sigma^2, P(∣X−μ∣≥t)≤σ2/t2\Pr(\abs{X - \mu} \ge t) \le \sigma^2/t^2 (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)\Pr(X \ge t) exceed the bound.

InteractiveTry to beat Markov
Law of X≥0X \ge 0 with four atoms (height = mass; the sum is always 1)
Probability: tail versus bounds
  • tail P(X≥t)\Pr(X \ge t)
  • Markov E[X]/t\E[X]/t
  • Cantelli
3.00
Mean E[X]\E[X]1.200
Variance Var⁡(X)\Var(X)1.460
Tail P(X≥t)\Pr(X \ge t)0.100
Markov E[X]/t\E[X]/t0.400
Tail / Markov ratio0.250
Best ratio at this tt0.000
Markov on X2X^2: E[X2]/t2\E[X^2]/t^20.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)\Pr(X \ge t) (orange) with Markov bound E[X]/t\E[X]/t (yellow) and Cantelli (blue), which also uses variance. The tail/Markov ratio never exceeds 1. Try ‘Two points’ and it reaches 11: 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)\Pr(X \ge t)/(\E[X]/t) equals 11 exactly when all mass is at {0,t}\{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≥0u \ge 0. If X−μ≥sX - \mu \ge s, then X−μ+u≥s+u>0X - \mu + u \ge s + u > 0 and squaring gives (X−μ+u)2≥(s+u)2(X - \mu + u)^2 \ge (s + u)^2. By Markov on nonnegative (X−μ+u)2(X - \mu + u)^2,

P(X−μ≥s)≤E[(X−μ+u)2](s+u)2=σ2+u2(s+u)2.\Pr(X - \mu \ge s) \le \frac{\E[(X - \mu + u)^2]}{(s + u)^2} = \frac{\sigma^2 + u^2}{(s + u)^2}.

The right side is minimized at u=σ2/su = \sigma^2/s, where it equals σ2/(σ2+s2)\sigma^2/(\sigma^2 + s^2).

∎

With s=3σs = 3\sigma it gives 1/101/10 versus Chebyshev’s 1/91/9, and is the best bound using only μ\mu and σ2\sigma^2 (tight, like Chebyshev). Yet all have a fundamental problem for averages. For Xˉn\bar X_n of nn iid variables with variance σ2\sigma^2, Chebyshev gives P(∣Xˉn−μ∣≥ε)≤σ2/(nε2)\Pr(\abs{\bar X_n - \mu} \ge \varepsilon) \le \sigma^2/(n\varepsilon^2), decreasing as 1/n1/n, while the CLT suggests e−nε2/(2σ2)e^{-n\varepsilon^2/(2\sigma^2)}. How capture all moments at once? The exponential: eλx=∑k≥0(λx)k/k!e^{\lambda x} = \sum_{k \ge 0} (\lambda x)^k/k! packs moments of all orders with weights adjusted by λ\lambda. Applying Markov to eλXe^{\lambda X} applies it to all powers at once; choosing the best λ\lambda chooses the best combination.

Chernoff’s method

Let XX be a real random variable. Write M(λ)=E[eλX]∈(0,+∞]M(\lambda) = \E[e^{\lambda X}] \in (0, +\infty] for its moment-generating function and ψ(λ)=log⁡M(λ)\psi(\lambda) = \log M(\lambda) for its cumulant-generating function, convex, equal to 00 at λ=0\lambda = 0, and satisfying ψ′(0)=μ\psi'(0) = \mu and ψ′′(0)=σ2\psi''(0) = \sigma^2 where they exist.

Proof

With λ>0\lambda > 0, function x↦eλxx \mapsto e^{\lambda x} is strictly increasing, so {X≥t}={eλX≥eλt}\{X \ge t\} = \{e^{\lambda X} \ge e^{\lambda t}\}. Variable eλXe^{\lambda X} is nonnegative and Markov gives P(X≥t)≤E[eλX]/eλt\Pr(X \ge t) \le \E[e^{\lambda X}]/e^{\lambda t}. With λ=0\lambda = 0 the bound is 11. Since it holds for every λ≥0\lambda \ge 0, it holds for the best: P(X≥t)≤inf⁡λe−(λt−ψ(λ))=exp⁡(−sup⁡λ{λt−ψ(λ)})\Pr(X \ge t) \le \inf_\lambda e^{-(\lambda t - \psi(\lambda))} = \exp(-\sup_\lambda\{\lambda t - \psi(\lambda)\}). Finally, Jensen’s inequality gives ψ(λ)≥λμ\psi(\lambda) \ge \lambda\mu for every λ\lambda; if λ<0\lambda < 0 and t≥μt \ge \mu, then λt−ψ(λ)≤λ(t−μ)≤0\lambda t - \psi(\lambda) \le \lambda(t - \mu) \le 0, no larger than 00 already attained at λ=0\lambda = 0.

∎

Three practical features. It is nonasymptotic: valid for every tt and law, without n→∞n \to \infty. Independence is not required; it only appears when calculating MM of a sum by factorization. All difficulty is choosing λ\lambda, a one-variable convex optimization problem: λ↦λt−ψ(λ)\lambda \mapsto \lambda t - \psi(\lambda) is concave because ψ\psi is convex. At an interior optimum the derivative vanishes, giving ψ′(λ∗)=t\psi'(\lambda^*) = t. Meaning: ψ′(λ)\psi'(\lambda) is the mean of the tilted law eλx−ψ(λ) P( ⁣dx)e^{\lambda x - \psi(\lambda)}\,P(\dd x) (exponential tilting), and optimal λ\lambda tilts until tt is no longer rare but its mean.

InteractiveOptimizing λ and the Legendre transform
Cumulant function ψ(λ)\psi(\lambda), line λt\lambda t and their gap
λ*
  • ψ(λ)\psi(\lambda)
  • line λt\lambda t
  • tangent to ψ\psi at λ\lambda
  • gap g(λ)g(\lambda)
Bound e−ng(λ)e^{-n g(\lambda)} (logarithmic scale, n=10n = 10)
bound above 1: vacuous
Rate function I(t)=sup⁡λ≥0{λt−ψ(λ)}I(t) = \sup_{\lambda \ge 0}\{\lambda t - \psi(\lambda)\} as tt moves
  • I(t)I(t)
  • (t−μ)2/(2σ2)(t-\mu)^2/(2\sigma^2)
0.45
0.60
10
Gap g(λ)=λt−ψ(λ)g(\lambda) = \lambda t - \psi(\lambda)0.113
Bound e−n g(λ)e^{-n\,g(\lambda)} for P(Xˉ10≥t)\Pr(\bar X_{10} \ge t)0.324
Best bound e−nI(t)e^{-nI(t)}0.147
λ∗\lambda^* and I(t)I(t)1.253 and 0.192
Tilted-law mean ψ′(λ)\psi'(\lambda)0.402
Main panel: cumulant ψ(λ)\psi(\lambda) (blue), line λt\lambda t (orange), and vertical gap g(λ)=λt−ψ(λ)g(\lambda) = \lambda t - \psi(\lambda) (purple); the dashed tangent has slope ψ′(λ)\psi'(\lambda). Second: bound e−ng(λ)e^{-ng(\lambda)} (purple), falling then rising. Move λ\lambda to the minimum or press ‘Go to optimal λ∗\lambda^*’: the tangent is parallel to the line, ψ′(λ∗)=t\psi'(\lambda^*) = t. Slide tt or press ‘Sweep tt’: the maximum gap in panel three is rate function I(t)I(t), zero at the mean and near (t−μ)2/(2σ2)(t - \mu)^2/(2\sigma^2) nearby. Change law: what happens at λ=1\lambda = 1 for exponential, or any λ>0\lambda > 0 for Pareto?

Five laws, five exponents

In the table λ∗\lambda^* solves ψ′(λ∗)=t\psi'(\lambda^*) = t for each law (one variable XX; for the average of nn iid copies replace P(X≥t)\Pr(X \ge t) by P(Xˉn≥t)\Pr(\bar X_n \ge t) and the bound by e−nI(t)e^{-nI(t)}, as below).

Law of XXψ(λ)\psi(\lambda)λ∗\lambda^*I(t)I(t)
N(μ,σ2)\Normal(\mu, \sigma^2)μλ+σ2λ2/2\mu\lambda + \sigma^2\lambda^2/2(t−μ)/σ2(t - \mu)/\sigma^2(t−μ)2/(2σ2)(t - \mu)^2/(2\sigma^2)
Pois⁡(μ)\Pois(\mu)μ(eλ−1)\mu(e^\lambda - 1)log⁡(t/μ)\log(t/\mu)tlog⁡tμ−t+μt\log\dfrac{t}{\mu} - t + \mu
Bern⁡(p)\Bern(p)log⁡(1−p+peλ)\log(1 - p + pe^\lambda)log⁡t(1−p)p(1−t)\log\dfrac{t(1-p)}{p(1-t)}tlog⁡tp+(1−t)log⁡1−t1−pt\log\dfrac{t}{p} + (1-t)\log\dfrac{1-t}{1-p}
Exp⁡(1)\operatorname{Exp}(1)−log⁡(1−λ)-\log(1 - \lambda), λ<1\lambda < 11−1/t1 - 1/tt−1−log⁡tt - 1 - \log t
Rademacher ±1\pm 1log⁡cosh⁡λ\log\cosh\lambdaartanh⁡t\operatorname{artanh} t1+t2log⁡(1+t)+1−t2log⁡(1−t)\tfrac{1+t}{2}\log(1+t) + \tfrac{1-t}{2}\log(1-t)

Two rows take one line each. For normal, λt−μλ−σ2λ2/2\lambda t - \mu\lambda - \sigma^2\lambda^2/2 is a parabola maximized at λ∗=(t−μ)/σ2\lambda^* = (t - \mu)/\sigma^2 with value (t−μ)2/(2σ2)(t - \mu)^2/(2\sigma^2), so P(X≥t)≤e−(t−μ)2/(2σ2)\Pr(X \ge t) \le e^{-(t - \mu)^2/(2\sigma^2)}. The true tail is Φˉ(z)=1−Φ(z)\bar\Phi(z) = 1 - \Phi(z) with z=(t−μ)/σz = (t - \mu)/\sigma, behaving by Mills ratio as e−z2/2/(z2π)e^{-z^2/2}/(z\sqrt{2\pi}): Chernoff gets exponent z2/2z^2/2 right and loses factor z2πz\sqrt{2\pi}. With z=5z = 5 that factor is 12.512.5; exact tail is 2.87×10−72.87 \times 10^{-7} and bound 3.73×10−63.73 \times 10^{-6}.

For a Bernoulli mean, ψ′(λ)=peλ/(1−p+peλ)=t\psi'(\lambda) = pe^\lambda/(1 - p + pe^\lambda) = t gives eλ∗=t(1−p)/(p(1−t))e^{\lambda^*} = t(1-p)/(p(1-t)). Then ψ(λ∗)=log⁡1−p1−t\psi(\lambda^*) = \log\frac{1-p}{1-t} and

I(t)=tlog⁡t(1−p)p(1−t)−log⁡1−p1−t=tlog⁡tp+(1−t)log⁡1−t1−p=KL⁡(t ∥ p),I(t) = t\log\frac{t(1-p)}{p(1-t)} - \log\frac{1-p}{1-t} = t\log\frac{t}{p} + (1-t)\log\frac{1-t}{1-p} = \KL(t \,\|\, p),

the Kullback-Leibler divergence between Bern⁡(t)\Bern(t) and Bern⁡(p)\Bern(p). Combinatorially: for nn tosses of an Bern⁡(p)\Bern(p) coin, the probability of a specific sequence of empirical frequency aa times the number (nna)≈enH(a)\binom{n}{na} \approx e^{nH(a)} of such sequences is e−nKL⁡(a ∥ p)e^{-n\KL(a\,\|\,p)} up to polynomial factors in nn (method of types). In information theory KL⁡(a ∥ p)\KL(a\,\|\,p) is the excess nats per symbol paid to encode source Bern⁡(a)\Bern(a) with an optimal code for Bern⁡(p)\Bern(p).

Averages of iid variables and Hoeffding’s bound

Let X1,…,XnX_1, \dots, X_n be independent and identically distributed with cumulant ψ\psi. Expectation of an independent product is the product of expectations, so ψSn(λ)=nψ(λ)\psi_{S_n}(\lambda) = n\psi(\lambda); applying the theorem to SnS_n with t=nat = na,

P(Xˉn≥a)=P(Sn≥na)≤exp⁡ ⁣(−n (λa−ψ(λ)))⟹P(Xˉn≥a)≤e−nI(a),\Pr(\bar X_n \ge a) = \Pr(S_n \ge na) \le \exp\!\big(-n\,(\lambda a - \psi(\lambda))\big) \quad\Longrightarrow\quad \Pr(\bar X_n \ge a) \le e^{-nI(a)},

with the same single-variable II: nn multiplies the exponent. This yields exponential tails. For Bernoulli, I(a)=KL⁡(a ∥ p)I(a) = \KL(a\,\|\,p); a simple inequality gives a bound without logarithms.

Proof

Let f(a)=KL⁡(a ∥ p)−2(a−p)2f(a) = \KL(a\,\|\,p) - 2(a-p)^2. Then f(p)=0f(p) = 0, f′(a)=log⁡ap−log⁡1−a1−p−4(a−p)f'(a) = \log\frac{a}{p} - \log\frac{1-a}{1-p} - 4(a - p), so f′(p)=0f'(p) = 0, and f′′(a)=1a(1−a)−4≥0f''(a) = \frac{1}{a(1-a)} - 4 \ge 0 because a(1−a)≤1/4a(1 - a) \le 1/4. A convex function with f(p)=f′(p)=0f(p) = f'(p) = 0 satisfies f≥0f \ge 0. The one-sided bound follows from e−nKL⁡≤e−2nε2e^{-n\KL} \le e^{-2n\varepsilon^2} with a=p+εa = p + \varepsilon (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 pp to ±ε\pm\varepsilon with confidence 1−δ1 - \delta is n≥log⁡(2/δ)/(2ε2)n \ge \log(2/\delta)/(2\varepsilon^2), giving the motivating 1 0601\,060. For a thousand coins P(∣p^−0.5∣≥0.05)≤2e−2⋅1000⋅0.0025=2e−5=0.0135\Pr(\abs{\hat p - 0.5} \ge 0.05) \le 2e^{-2\cdot 1000 \cdot 0.0025} = 2e^{-5} = 0.0135, versus Chebyshev’s 0.10.1; the exact tail is 0.00170.0017.

When the method does not apply

The theorem has no assumptions, but its conclusion may be vacuous: if M(λ)=+∞M(\lambda) = +\infty for every λ>0\lambda > 0, bound e−λtM(λ)e^{-\lambda t}M(\lambda) equals +∞+\infty and says nothing. This happens for heavy tails: Pareto of index α\alpha has P(X≥t)=t−α\Pr(X \ge t) = t^{-\alpha} and E[eλX]=∫1∞eλxαx−α−1  ⁣dx=∞\E[e^{\lambda X}] = \int_1^\infty e^{\lambda x}\alpha x^{-\alpha-1}\,\dd x = \infty for every λ>0\lambda > 0, even though α=3\alpha = 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(λ)<∞M(\lambda) < \infty for some λ>0\lambda > 0 essentially means the right tail falls at least exponentially. For heavy tails use finite-order moments: best order-k<αk < \alpha Markov bound is E[Xk]/tk=αα−k t−k\E[X^k]/t^k = \frac{\alpha}{\alpha - k}\,t^{-k}, decaying as t−kt^{-k} but never as t−αt^{-\alpha}. It is the dashed yellow curve for Pareto.

Multiplicative bounds

Hoeffding does not distinguish frequent and rare events: exponent 2nε22n\varepsilon^2 depends only on absolute distance ε\varepsilon, not pp. It is very poor for rare events. With n=1000n = 1000 and p=0.01p = 0.01, bounding P(Sn≥30)\Pr(S_n \ge 30) (i.e. ε=0.02\varepsilon = 0.02) by Hoeffding gives e−0.8=0.45e^{-0.8} = 0.45, uninformative when true probability is two ten-millionths. The multiplicative form measures relative deviation δ\delta from mean μ=E[Sn]\mu = \E[S_n] and is a randomized-algorithms tool.

Proof

Each summand’s generating function is E[eλXi]=1+pi(eλ−1)≤exp⁡(pi(eλ−1))\E[e^{\lambda X_i}] = 1 + p_i(e^\lambda - 1) \le \exp(p_i(e^\lambda - 1)), by 1+x≤ex1 + x \le e^x. Independence gives MX(λ)≤exp⁡(μ(eλ−1))M_X(\lambda) \le \exp(\mu(e^\lambda - 1)), the cumulant of Pois⁡(μ)\Pois(\mu): for the generating function, a Bernoulli sum is never worse than a Poisson of equal mean. With λ>0\lambda > 0, Markov gives P(X≥(1+δ)μ)≤exp⁡(μ(eλ−1)−λ(1+δ)μ)\Pr(X \ge (1+\delta)\mu) \le \exp(\mu(e^\lambda - 1) - \lambda(1+\delta)\mu), and λ=log⁡(1+δ)\lambda = \log(1 + \delta), zeroing the exponent derivative, gives exp⁡(μ(δ−(1+δ)log⁡(1+δ)))\exp(\mu(\delta - (1+\delta)\log(1+\delta))), the first bound. To simplify, f(δ)=log⁡(1+δ)−2δ2+δf(\delta) = \log(1 + \delta) - \frac{2\delta}{2 + \delta} satisfies f(0)=0f(0) = 0 and f′(δ)=δ2(1+δ)(2+δ)2≥0f'(\delta) = \frac{\delta^2}{(1+\delta)(2+\delta)^2} \ge 0, so log⁡(1+δ)≥2δ2+δ\log(1 + \delta) \ge \frac{2\delta}{2 + \delta} and (1+δ)log⁡(1+δ)−δ≥δ22+δ(1+\delta)\log(1+\delta) - \delta \ge \frac{\delta^2}{2 + \delta}.

For the lower tail use λ=log⁡(1−δ)<0\lambda = \log(1 - \delta) < 0: P(X≤(1−δ)μ)=P(eλX≥eλ(1−δ)μ)≤e−λ(1−δ)μMX(λ)≤exp⁡(μ(−δ−(1−δ)log⁡(1−δ)))\Pr(X \le (1-\delta)\mu) = \Pr(e^{\lambda X} \ge e^{\lambda(1-\delta)\mu}) \le e^{-\lambda(1-\delta)\mu}M_X(\lambda) \le \exp(\mu(-\delta - (1 - \delta)\log(1 - \delta))). And g(δ)=(1−δ)log⁡(1−δ)+δ−δ2/2g(\delta) = (1 - \delta)\log(1 - \delta) + \delta - \delta^2/2 satisfies g(0)=0g(0) = 0 and g′(δ)=−log⁡(1−δ)−δ≥0g'(\delta) = -\log(1-\delta) - \delta \ge 0, so (1−δ)log⁡(1−δ)≥−δ+δ2/2(1 - \delta)\log(1 - \delta) \ge -\delta + \delta^2/2 and the exponent is at most −μδ2/2-\mu\delta^2/2.

∎

With X∼Bin⁡(1000,0.01)X \sim \Bin(1000, 0.01), μ=10\mu = 10 and P(X≥30)\Pr(X \ge 30) this is case δ=2\delta = 2: (e2/27)10=2.36×10−6(e^2/27)^{10} = 2.36 \times 10^{-6}, versus exact 2.06×10−72.06 \times 10^{-7} (bound off by factor 1111, Hoeffding by millions). The simplified version gives e−4⋅10/4=4.5×10−5e^{-4\cdot 10/4} = 4.5 \times 10^{-5}, much looser: form δ2μ/(2+δ)\delta^2\mu/(2+\delta) is convenient but discards factor 2020 here. The bound depends neither on nn nor individual pip_i, only μ\mu.

The simplified form resembles Bernstein: for centered summands bounded by 11 and total variance v≤μv \le \mu, Bernstein gives P(X−μ≥s)≤exp⁡(−s2/(2v+2s/3))\Pr(X - \mu \ge s) \le \exp\big(-s^2/(2v + 2s/3)\big), which with s=δμs = \delta\mu becomes exp⁡(−δ2μ/(2+2δ/3))\exp\big(-\delta^2\mu/(2 + 2\delta/3)\big), 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)e^{-nJ(a)} with J>IJ > I still valid? No. To understand why, inspect II.

Proof

A supremum of affine functions of tt is convex. I(μ)=0I(\mu) = 0 by Jensen as before, and I≥0I \ge 0 by taking λ=0\lambda = 0. If λt\lambda_t solves ψ′(λt)=t\psi'(\lambda_t) = t, differentiating I(t)=λtt−ψ(λt)I(t) = \lambda_t t - \psi(\lambda_t) gives I′(t)=λt′t+λt−ψ′(λt)λt′=λtI'(t) = \lambda_t' t + \lambda_t - \psi'(\lambda_t)\lambda_t' = \lambda_t. Since λt\lambda_t is the inverse of ψ′\psi', differentiable with ψ′′>0\psi'' > 0 (the law is nonconstant), the inverse function theorem gives λt′=1/ψ′′(λt)\lambda_t' = 1/\psi''(\lambda_t). At t=μt = \mu, λμ=0\lambda_\mu = 0 and ψ′′(0)=σ2\psi''(0) = \sigma^2, giving I(μ)=I′(μ)=0I(\mu) = I'(\mu) = 0 and I′′(μ)=1/σ2I''(\mu) = 1/\sigma^2: Taylor expansion.

∎

The last equality says near the mean, the rate function is the CLT parabola. Exponential e−nI(a)e^{-nI(a)} with I(a)≈(a−μ)2/(2σ2)I(a) \approx (a - \mu)^2/(2\sigma^2) is Gaussian e−z2/2e^{-z^2/2} in variable z=n(a−μ)/σz = \sqrt{n}(a - \mu)/\sigma. Far from the mean II 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=μt = \mu, then diverging.

Now the result answering the section’s initial question.

Proof

The upper bound (for every nn) is Chernoff’s above. For the lower bound tilt the law. Let λ=λa>0\lambda = \lambda_a > 0 and QQ be the law with density  ⁣dQ/ ⁣dP=eλx−ψ(λ)\dd Q/\dd P = e^{\lambda x - \psi(\lambda)} relative to XiX_i, a probability by definition of ψ\psi. For iid XiX_i of law QQ, mean is ψ′(λ)=a\psi'(\lambda) = a and variance s2=ψ′′(λ)∈(0,∞)s^2 = \psi''(\lambda) \in (0, \infty). By change of measure,  ⁣dPn/ ⁣dQn=e−λSn+nψ(λ)\dd P_n/\dd Q_n = e^{-\lambda S_n + n\psi(\lambda)}, and for δ>0\delta > 0,

P(Xˉn≥a)≥P(a≤Xˉn<a+δ)=EQ[e−λSn+nψ(λ) 1[a≤Xˉn<a+δ]]≥e−n(λ(a+δ)−ψ(λ)) Q(a≤Xˉn<a+δ),\Pr(\bar X_n \ge a) \ge \Pr(a \le \bar X_n < a + \delta) = \E_Q\big[e^{-\lambda S_n + n\psi(\lambda)}\,\ind[a \le \bar X_n < a + \delta]\big] \ge e^{-n(\lambda(a + \delta) - \psi(\lambda))}\,Q(a \le \bar X_n < a + \delta),

because on the event −λSn=−λnXˉn≥−λn(a+δ)-\lambda S_n = -\lambda n\bar X_n \ge -\lambda n(a + \delta). Under QQ, the mean of Xˉn\bar X_n is exactly aa, so by the CLT, Q(a≤Xˉn<a+δ)=Q(0≤n(Xˉn−a)/s<δn/s)→1/2Q(a \le \bar X_n < a + \delta) = Q\big(0 \le \sqrt n(\bar X_n - a)/s < \delta\sqrt n/s\big) \to 1/2. Taking 1nlog⁡\frac1n\log and n→∞n \to \infty gives lim inf⁡1nlog⁡P(Xˉn≥a)≥−(λa−ψ(λ))−λδ=−I(a)−λδ\liminf \frac1n\log\Pr(\bar X_n \ge a) \ge -(\lambda a - \psi(\lambda)) - \lambda\delta = -I(a) - \lambda\delta. Let δ→0\delta \to 0.

∎

The proof teaches more: rare event {Xˉn≥a}\{\bar X_n \ge a\} occurs, when it does, in the cheapest way, as if XiX_i were drawn from tilted law QQ with mean aa. This is large-deviation intuition and importance sampling: estimate a rare probability by simulating under QQ, 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\R, Dembo and Zeitouni prove the large-deviation principle for Xˉn\bar X_n with rate function II without assumptions on λa\lambda_a or finiteness of ψ\psi near zero, although the limit may fail where II is discontinuous). Under additional conditions the Bahadur-Rao formula refines it: P(Xˉn≥a)∼e−nI(a)/(λaσa2πn)\Pr(\bar X_n \ge a) \sim e^{-nI(a)}/(\lambda_a\sigma_a\sqrt{2\pi n}), with σa2=ψ′′(λa)\sigma_a^2 = \psi''(\lambda_a). Prefactor n−1/2n^{-1/2} is the polynomial part Chernoff discards. For Bernoulli, I(a)=KL⁡(a ∥ p)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 −1nln⁡P(Xˉn≥a)-\frac{1}{n}\ln\Pr(\bar X_n \ge a) versus nn
I(a) = 0.087simulation no longer sees the event
  • exact exponent (nn multiple of 2, nana integer)
  • other nn (rounding nana)
  • I(a)I(a), the limit
  • Bahadur-Rao
  • simulation (hollow: fewer than 10 hits)
Rate function I(a)I(a) and the CLT parabola
p
  • I(a)=KL(a ∥ p)I(a) = \mathrm{KL}(a\,\|\,p)
  • (a−p)2/(2p(1−p))(a-p)^2/(2p(1-p)) (CLT)
0.30
0.50
Rate function I(a)=KL(a ∥ p)I(a) = \mathrm{KL}(a \,\|\, p)0.0872 nats
Exact exponent at n=600n = 6000.0920 (+5.5 %)
P(Xˉ600≥a)\Pr(\bar X_{600} \ge a) exact1.1×10⁻²⁴
Chernoff bound e−nI(a)e^{-nI(a)}1.9×10⁻²³
Simulation hits at n=600n = 6000 of 3000
nn with e−nI(a)≤10−6e^{-nI(a)} \le 10^{-6}159
Left: −1nlog⁡P(Xˉn≥a)-\frac1n\log\Pr(\bar X_n \ge a) for Bernoulli(pp) averages: black is exact (binomial sum), blue is limit I(a)=KL⁡(a ∥ p)I(a) = \KL(a\,\|\,p), orange points simulate 3000 trajectories. The curve descends toward I(a)I(a), always above it (Chernoff bound), slowly: at n=600n = 600 a few percent remains. The thick curve uses nn with integer nana; thin gray uses the rest, with sawteeth from rounding nana 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/30001/3000: this cannot estimate a rare event. Right: I(a)I(a) versus the CLT parabola. Move aa and pp: 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]\mu = \E[X] and decompose μ=E[X 1[X≤θμ]]+E[X 1[X>θμ]]\mu = \E[X\,\ind[X \le \theta\mu]] + \E[X\,\ind[X > \theta\mu]]. The first term is at most θμ\theta\mu. For the second Cauchy-Schwarz gives E[X 1[X>θμ]]≤E[X2] P(X>θμ)\E[X\,\ind[X > \theta\mu]] \le \sqrt{\E[X^2]\,\Pr(X > \theta\mu)}. Thus (1−θ)μ≤E[X2] P(X>θμ)(1 - \theta)\mu \le \sqrt{\E[X^2]\,\Pr(X > \theta\mu)}, and squaring both nonnegative sides yields the inequality.

∎

The second-moment method uses the bound with θ=0\theta = 0: if E[X2]≤(1+o(1)) E[X]2\E[X^2] \le (1 + o(1))\,\E[X]^2, then P(X>0)→1\Pr(X > 0) \to 1. It robustly restates a known argument. Chebyshev gives P(X=0)≤Var⁡(X)/E[X]2\Pr(X = 0) \le \Var(X)/\E[X]^2, Paley-Zygmund Var⁡(X)/E[X2]\Var(X)/\E[X^2], always better because E[X2]≥E[X]2\E[X^2] \ge \E[X]^2. Compare the figure readings.

InteractiveHow much mass remains above θ·E[X]?
The law of XX (Poisson(1.5)) and region {X>θE[X]}\{X > \theta\E[X]\}
μθμ
P(X>θE[X])\Pr(X > \theta\E[X]) versus the Paley–Zygmund bound
  • P(X>θE[X])\Pr(X > \theta\E[X])
  • (1−θ)2E[X]2/E[X2](1-\theta)^2\E[X]^2/\E[X^2]
1.5
0.30
E[X]\E[X] and E[X2]\E[X^2]1.500 and 3.750
P(X>θ E[X])\Pr(X > \theta\,\E[X]) exact, θ=0.30\theta = 0.300.7769
Paley–Zygmund bound0.2940
Bound on P(X=0)\Pr(X = 0): Chebyshev Var⁡/E[X]2\Var/\E[X]^20.6667
Bound on P(X=0)\Pr(X = 0): second moment Var⁡/E[X2]\Var/\E[X^2]0.4000
Left: law of X≥0X \ge 0 with region {X>θE[X]}\{X > \theta\E[X]\} shaded. Right: exact tail (black) versus Paley-Zygmund bound (blue) as θ\theta varies. The bound never exceeds the tail. With ‘Two points’ and θ=0\theta = 0 they touch. For lognormal, increasing σ\sigma sends E[X2]=eσ2\E[X^2] = e^{\sigma^2} soaring and the bound plunges although X>0X > 0 always: two moments do not reveal mass away from zero. With Poisson and θ=0\theta = 0, the bound is close when mm is small. What happens for large mm and θ>0\theta > 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)\Bin(1000, 0.01), and P(S≥30)\Pr(S \ge 30).

MethodValueFactor versus exact
Exact tail2.06×10−72.06 \times 10^{-7}11
Normal approximation (z=6.36z = 6.36)1.03×10−101.03 \times 10^{-10}1/20001/2000
Chernoff bound e−nKL⁡(0.03 ∥ 0.01)e^{-n\KL(0.03\,\|\,0.01)}1.92×10−61.92 \times 10^{-6}9.39.3
Hoeffding e−2n(0.02)2e^{-2n(0.02)^2}0.450.452×1062 \times 10^{6}
Bahadur-Rao (lattice)2.11×10−72.11 \times 10^{-7}1.031.03

Normal underestimates probability by factor 20002000: 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.39.3 but on the safe side; Bahadur-Rao, recovering the polynomial prefactor, by 3 %3\,\%.

Why does the CLT fail if it is a theorem? It says P(Sn≥nμ+zσn)→Φˉ(z)\Pr(S_n \ge n\mu + z\sigma\sqrt n) \to \bar\Phi(z) for each fixed zz, with absolute error O(1/n)\bigO(1/\sqrt n) by Berry-Esseen. Here that guarantee is 0.1480.148 (with Shevtsova’s constant 0.47480.4748), far above probability 2×10−72 \times 10^{-7}. Absolute error 0.150.15 says nothing about an event of probability 10−710^{-7}. Relative error matters; Cramér’s moderate-deviation theorem controls it: with ψ\psi finite near 00, P(Sn≥nμ+zσn)/Φˉ(z)→1\Pr(S_n \ge n\mu + z\sigma\sqrt n)/\bar\Phi(z) \to 1 uniformly over 0≤z=o(n1/6)0 \le z = o(n^{1/6}). Beyond that, the ratio has an exponential factor (Cramér series), whose first exponent term is κ3z3/(6σ3n)\kappa_3 z^3/(6\sigma^3\sqrt n) with κ3\kappa_3 the third cumulant. This gives n1/6n^{1/6}: the term is negligible only if z3≪nz^3 \ll \sqrt n. With n=1000n = 1000, n1/6=3.2n^{1/6} = 3.2, and z=6.4z = 6.4 lies well outside this region, especially with Bern⁡(0.01)\Bern(0.01)‘s strong skewness, coefficient κ3/σ3\kappa_3/\sigma^3 equal to 9.89.8. With a fair coin κ3=0\kappa_3 = 0 the term vanishes and normal at z=6.3z = 6.3 stays within 7 %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 ψ\psi.

Implementation from scratch

Start with the table’s cumulants, golden-section optimization of λ\lambda (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 99 and 2424. Normal λ∗\lambda^* is exactly t=5t = 5, Poisson’s is log⁡3=1.099\log 3 = 1.099, and binomial is close at 1.1191.119, as in formula log⁡t(1−p)p(1−t)\log\frac{t(1-p)}{p(1-t)} with t=0.03t = 0.03. Implementation detail: maximizar_concava evaluates ψ\psi only inside [0,λmax⁡][0, \lambda_{\max}], so exponential, with ψ=∞\psi = \infty from λ=1\lambda = 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/δ1/\delta (factor 10001000 whenever δ\delta drops three orders), Hoeffding as log⁡(1/δ)\log(1/\delta) (10601060 to 42844284 when 10−210^{-2} becomes 10−910^{-9}). At δ=10−9\delta = 10^{-9}, estimating a proportion to ±5 %\pm 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 20 00020\,000 simulations the naive method sees no event (expected 0.0040.004 hits), whereas simulation under tilted law Bin⁡(n,0.03)\Bin(n, 0.03) estimates 2.05×10−72.05 \times 10^{-7} with 2 %2\,\% error, versus exact 2.06×10−72.06 \times 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⁡\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 00 below about 10−30810^{-308}, whereas logsf preserves the value. Chernoff bound −nKL⁡=−72.2-n\KL = -72.2 is close to tail log −75.5-75.5: their difference 3.33.3 is the log of Bahadur-Rao prefactor λσ2πn\lambda\sigma\sqrt{2\pi n} (with lattice adjustment 1−e−λ1 - e^{-\lambda} instead of λ\lambda).

Common mistakes

Exercises

ProofFrom Markov to Chebyshev and Chernoff
Prove: Prove (a) Markov's inequality: if X≥0X \ge 0 and a>0a > 0, P(X≥a)≤E[X]/a\Pr(X \ge a) \le \E[X]/a; (b) Chebyshev's: if X∈L2X \in L^2 has mean μ\mu and variance σ2\sigma^2, P(∣X−μ∣≥t)≤σ2/t2\Pr(\abs{X - \mu} \ge t) \le \sigma^2/t^2; (c) Chernoff's bound: for every λ>0\lambda > 0, P(X≥t)≤e−λtE[eλX]\Pr(X \ge t) \le e^{-\lambda t}\E[e^{\lambda X}].
0
All three apply the same idea to different functions of XX.

Step 1 of 4. (a) What is Markov's key step?

ProofMultiplicative bound for Bernoulli sums
Prove: Let X1,…,XnX_1, \dots, X_n be independent with Xi∼Bern⁡(pi)X_i \sim \Bern(p_i), X=∑iXiX = \sum_i X_i and μ=E[X]\mu = \E[X]. Show that for every δ>0\delta > 0, P(X≥(1+δ)μ)≤(eδ/(1+δ)1+δ)μ≤exp⁡(−δ2μ/(2+δ))\Pr(X \ge (1 + \delta)\mu) \le \big(e^\delta/(1+\delta)^{1+\delta}\big)^\mu \le \exp(-\delta^2\mu/(2 + \delta)).
0
Apply Chernoff to the sum and bound each summand's generating function.

Step 1 of 3. How do you bound E[eλX]\E[e^{\lambda X}]?

ProofPaley-Zygmund
Prove: If X≥0X \ge 0 has E[X2]<∞\E[X^2] < \infty and E[X]=μ>0\E[X] = \mu > 0, then for every θ∈[0,1]\theta \in [0, 1], P(X>θμ)≥(1−θ)2μ2/E[X2]\Pr(X > \theta\mu) \ge (1 - \theta)^2\mu^2/\E[X^2].
0
Split expectation of XX according to whether XX is below or above the threshold.

Step 1 of 4. How do you start?

NumericOne thousand tosses and Chebyshev
A fair coin is tossed 10001000 times. Use Chebyshev's inequality to bound P(∣Sn/n−0.5∣≥0.05)\Pr(\abs{S_n/n - 0.5} \ge 0.05).
NumericOne thousand tosses and Chernoff-Hoeffding
For the same 10001000 fair-coin tosses, calculate bound 2e−2nε22e^{-2n\varepsilon^2} for P(∣Sn/n−0.5∣≥0.05)\Pr(\abs{S_n/n - 0.5} \ge 0.05).
NumericTests for certification
A system passes nn independent tests with no failure. You want to conclude with 99 %99\,\% confidence (δ=0.01\delta = 0.01) that its failure rate is below ε=0.005\varepsilon = 0.005. Using e−εn≤δe^{-\varepsilon n} \le \delta, what is the smallest sufficient integer nn?
NumericChernoff for a Poisson
Let X∼Pois⁡(10)X \sim \Pois(10). Calculate Chernoff bound e−μ(eμ/t)te^{-\mu}(e\mu/t)^t for P(X≥15)\Pr(X \ge 15).
NumericExponential rate function
For X∼Exp⁡(1)X \sim \operatorname{Exp}(1), ψ(λ)=−log⁡(1−λ)\psi(\lambda) = -\log(1 - \lambda) if λ<1\lambda < 1. Calculate I(3)=sup⁡λ{3λ−ψ(λ)}I(3) = \sup_{\lambda}\{3\lambda - \psi(\lambda)\}.
NumericAn audit without false alarms
A model independently fails each test with probability p=0.01p = 0.01. An auditor rejects it if nn cases show at least a 3 %3\,\% failure rate. What is the smallest nn for which Chernoff bound e−nKL⁡(0.03 ∥ 0.01)e^{-n\KL(0.03\,\|\,0.01)} guarantees unfair rejection probability at most 10−910^{-9}?
QuizWhy tilt to the threshold?
Cramér's lower bound changes to tilted law QQ with ψ′(λ)=a\psi'(\lambda) = a. Why precisely that λ\lambda?
QuizPareto without Chernoff
Why can the Chernoff method not use a Pareto variable with α=3\alpha = 3, which has finite mean and variance?
QuizA tool for a rare event
With S∼Bin⁡(1000,0.01)S \sim \Bin(1000, 0.01) you want a safe bound on P(S≥30)=2.06×10−7\Pr(S \ge 30) = 2.06\times 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)=sup⁡0≤λ≤λmax⁡{λt−ψ(λ)}I(t) = \sup_{0 \le \lambda \le \lambda_{\max}}\{\lambda t - \psi(\lambda)\}, with cgf the cumulant ψ\psi (a scalar function returning inf outside its domain). Do not use scipy: maximize concave λ↦λt−ψ(λ)\lambda \mapsto \lambda t - \psi(\lambda) by golden-section search or bisection on the numerical derivative. If tt does not exceed the mean, return 00 (supremum attained at λ=0\lambda = 0). Tests check closed forms for Bernoulli, Poisson, normal and exponential (for the latter pass lam_max just below 11).
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λXe^{\lambda X} and optimize λ\lambda to obtain P(X≥t)≤e−I(t)\Pr(X \ge t) \le e^{-I(t)} with II the cumulant’s Legendre transform: exponential rather than polynomial tails, valid for every nn, 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)\Pr(X \ge t) \le \inf_{\lambda \ge 0}e^{-\lambda t}M(\lambda) = e^{-I(t)}. For an average of nn iid variables, P(Xˉn≥a)≤e−nI(a)\Pr(\bar X_n \ge a) \le e^{-nI(a)} with the same II. The optimum satisfies ψ′(λ∗)=t\psi'(\lambda^*) = t: tilt until tt is the mean.
  • Examples. Normal: I=(t−μ)2/(2σ2)I = (t - \mu)^2/(2\sigma^2). Poisson: tlog⁡(t/μ)−t+μt\log(t/\mu) - t + \mu. Bernoulli: KL⁡(t ∥ p)\KL(t\,\|\,p), giving Hoeffding via Pinsker: 2e−2nε22e^{-2n\varepsilon^2} for both sides.
  • Multiplicative. For independent Bernoulli sums, P(X≥(1+δ)μ)≤(eδ/(1+δ)1+δ)μ≤e−δ2μ/(2+δ)\Pr(X \ge (1 + \delta)\mu) \le (e^\delta/(1+\delta)^{1+\delta})^\mu \le e^{-\delta^2\mu/(2+\delta)} and P(X≤(1−δ)μ)≤e−δ2μ/2\Pr(X \le (1-\delta)\mu) \le e^{-\delta^2\mu/2}: mean-sensitive, useful for rare events and randomized algorithms.
  • Cramér. 1nlog⁡P(Xˉn≥a)→−I(a)\frac1n\log\Pr(\bar X_n \ge a) \to -I(a): the exponent cannot improve. The proof tilts until aa is the mean and applies the CLT under the tilted law. Near the mean I≈(t−μ)2/(2σ2)I \approx (t - \mu)^2/(2\sigma^2); far away it departs from the parabola.
  • Paley-Zygmund. P(X>θE[X])≥(1−θ)2E[X]2/E[X2]\Pr(X > \theta\E[X]) \ge (1 - \theta)^2\E[X]^2/\E[X^2]: the second-moment method gives lower bounds and improves Chebyshev for P(X=0)\Pr(X = 0).
  • Caution. The CLT fails in distant tails (relative, not absolute error); Chernoff requires M(λ)<∞M(\lambda) < \infty for some λ>0\lambda > 0 (not Pareto); a two-sided event needs union-bound factor 22; a bound valid for every nn is not an asymptotic approximation.