Module contents
Lesson 10 of 19Advanced 115 min

The noisy-channel coding theorem

Prove Shannon's noisy-channel coding theorem using joint typicality, random codes, and Fano's inequality; examine separation and practical linear codes.

After this lesson you can

  • Define joint typicality and prove its three properties.
  • Reproduce random-coding achievability with joint-typicality decoding.
  • Prove the weak converse using Fano and data processing.
  • State source–channel separation and its practical limitations.
  • Implement Hamming (7,4) syndrome decoding and compare with capacity.

Before you start

Motivation: the 1948 surprise

The previous lesson showed the apparent price of reliability. On a binary symmetric channel with ε=0.11\varepsilon = 0.11, repeating each bit 25 times and voting by majority reduces bit error below 10−610^{-6} but leaves rate 0.040.04 bits per use. The pattern seems inevitable: with repetition error tends to zero only if rate does too. Before 1948 engineers assumed reliability and speed must trade off this way.

Shannon asserted the opposite with striking precision. Every channel has a number, its capacity C=max⁡pI(X;Y)C = \max_p I(X;Y), such that:

  • at any rate R<CR < C codes exist with arbitrarily small error probability without lowering rate;
  • at any rate R>CR > C no code achieves this.

For ε=0.11\varepsilon = 0.11, C=0.5C = 0.5: half a bit per use can be transmitted with error 10−610^{-6}, 10−1210^{-12}, or 10−10010^{-100}, twelve times faster than repetition. The price is not rate but block length: the code must group many bits and protect them together.

Most striking is the proof. Shannon constructed no code. He chose codewords at random and proved they work on average; therefore some must work. This early major example of the probabilistic method took half a century for its practical consequence: only in the 1990s did reasonably decodable codes truly approach the limit (turbo, LDPC, and later polar codes).

This lesson proves the theorem. Its central tool is joint typicality, extending lesson 4’s typical set to sequence pairs. It proves achievability via random coding and typicality decoding; the converse uses Fano’s inequality and data processing. We then see why separate compression and protection lose nothing asymptotically, build the first historical error-correcting code, Hamming (7,4), and measure concrete codes’ distance from Shannon’s boundary. As before log⁡\log is base-2 logarithm and information is in bits.

Channel codes

Fix a discrete memoryless channel (X,W,Y)(\mathcal{X}, W, \mathcal{Y}) which over nn uses acts as Wn(yn∣xn)=∏iW(yi∣xi)W^n(y^n \mid x^n) = \prod_i W(y_i \mid x_i).

Rate RR is achievable if a sequence of codes (⌈2nR⌉,n)(\lceil 2^{nR} \rceil, n) exists with λ(n)→0\lambda^{(n)} \to 0 as n→∞n \to \infty. Operational capacity is the supremum of achievable rates. The definition requires maximum error: the code must work for every message, not merely most. Average error gives the same capacity (shown by expurgation), but maximum is the desired guarantee.

Why does repetition fail? With NN copies, M=2M = 2 messages per block of NN uses and R=1/NR = 1/N. Error is the probability that most of the NN copies flip, tending exponentially to zero in NN, but rate also tends to zero. If instead each of kk bits is repeated NN times with fixed NN, rate 1/N1/N is fixed but the block fails if any of kk bits fails, with probability 1−(1−pN)k1 - (1 - p_N)^k tending to 1 as kk grows. Repetition protects bits separately; Shannon’s idea is to protect many jointly, so noise in nn uses flipping almost exactly nεn\varepsilon positions cannot confuse codewords.

We can now state the result.

The converse uses average error, which never exceeds maximum error, so says more: not even average error can vanish above CC. (Do not confuse this with the “strong converse” later, which says something different: error tends to 1.)

Intuition: how many noise balls fit?

Before the proof, its guiding counting argument. Consider the binary symmetric channel with uniform input. If xnx^n is sent, noise flips about nεn\varepsilon positions, so yny^n lands with high probability in a “ball” of about (nnε)≈2nh2(ε)\binom{n}{n\varepsilon} \approx 2^{n h_2(\varepsilon)} sequences around xnx^n. For the receiver to distinguish codewords their balls must not overlap. Output space has 2n2^n sequences, so at most

M≲2n2nh2(ε)=2n(1−h2(ε))=2nCM \lesssim \frac{2^n}{2^{n h_2(\varepsilon)}} = 2^{n(1 - h_2(\varepsilon))} = 2^{nC}

codewords fit, namely R≲CR \lesssim C. For a general channel with input pp, there are about 2nH(Y)2^{nH(Y)} typical outputs; each input generates a fan of about 2nH(Y∣X)2^{nH(Y \mid X)} typical outputs, and 2n(H(Y)−H(Y∣X))=2nI(X;Y)2^{n(H(Y) - H(Y \mid X))} = 2^{nI(X;Y)} disjoint fans fit. Choosing the best pp gives 2nC2^{nC}.

The surprising reverse direction is that the space can be filled nearly to this limit with almost disjoint balls, and random selection suffices.

InteractiveNoise spheres in Hamming space
A window with 48 of the M words
y
Volume budget, in bits
n = 200nR + log₂V = 197
n=50n=1000C1 − h₂(ε+δ)
  • mean error with n = 200
  • other lengths
  • capacity CC
  • threshold with slack δ\delta
  • sent-word ball
  • other balls
  • other balls containing y: 0
  • nRnR bits (words)
  • log⁡2V\log_2 V bits (ball)
0.42
200
0.11
0.030
Capacity CC0.500 bits
Ball radius rr28
Words M=2nRM = 2^{nR}2842^{84}
Ball volume VV2113.52^{113.5}
Mean coverage ρ\rho2−2.52^{−2.5}
Noise outside the ball0.0749
Mean error Pˉe\bar{P}_e0.2224
Between 1−h2(ε+δ)=0.4161 - h_2(\varepsilon + \delta) = 0.416 and C=0.500C = 0.500: at this length the budget may barely fit, but with this slack coverage ρ\rho grows exponentially with nn and the balls eventually cannot fit. The rate is achievable: reduce δ\delta (and increase nn to keep noise inside the ball).
Density map of {0,1}n\{0, 1\}^n: each disk occupies the same fraction of the window as its Hamming ball of radius r=⌊n(ε+δ)⌋r = \lfloor n(\varepsilon + \delta) \rfloor occupies in the space (not an isometric projection, impossible in nn dimensions, but a volume-faithful representation). The cross is received yy; other balls containing it, red, are confusions. Below, bit budget: nRnR to number words plus log⁡2V\log_2 V per ball must fit in nn. The error plot shows exact random-code error with ball decoding versus rate. Raise RR until disks overlap; then with RR left of the dashed aqua threshold 1−h2(ε+δ)1 - h_2(\varepsilon + \delta), raise nn and watch disks shrink; to its right they grow.

Three points the figure shows and the proof formalizes:

  1. The transition is abrupt and sharpens with nn. At fixed length error rises smoothly with rate. As nn grows, the curve becomes a step: near zero left of a threshold, near one right. “Mean coverage” ρ=(M−1)V/2n\rho = (M - 1)V/2^n is the expected number of other codewords inside the received ball, and log⁡2ρ≈n(R−(1−h2(ε+δ)))\log_2 \rho \approx n(R - (1 - h_2(\varepsilon + \delta))): exponential in nn with the difference’s sign.
  2. The slack threshold is not capacity but tends to it. The decoder needs a radius slightly greater than nεn\varepsilon to contain noise with high probability; slack δ\delta costs rate. When δ→0\delta \to 0 (and n→∞n \to \infty faster), threshold 1−h2(ε+δ)1 - h_2(\varepsilon + \delta) rises to CC. This is the role of joint-typicality δ\delta.
  3. With small nn, error is dominated by noise outside the ball, not confusion: with n=200n = 200, ε=0.11\varepsilon = 0.11, δ=0.03\delta = 0.03 and R=0.3R = 0.3, coverage is ρ≈2−26.5\rho \approx 2^{-26.5} (disks are invisible), but error is 0.0750.075 because noise exceeds weight r=28r = 28 with that probability. Practical lengths are therefore hundreds or thousands of bits.

Joint typicality

The AEP says an iid “typical” sequence has probability near 2−nH2^{-nH}. Decoding needs the same for pairs (xn,yn)(x^n, y^n): sent and received words must “fit” as the channel would produce them.

We use δ\delta for tolerance rather than lesson 4’s ε\varepsilon, to avoid confusion with the binary symmetric channel parameter. The first two conditions require each sequence to be separately typical; the third requires the pair to be typical. It does not follow from the first two: independently selected typical xnx^n and yny^n almost never form a typical pair, precisely property 3 below.

Proof
  1. By the weak law of large numbers −1nlog⁡p(Xn)=−1n∑ilog⁡p(Xi)→H(X)-\frac1n\log p(X^n) = -\frac1n\sum_i \log p(X_i) \to H(X) in probability, being an iid mean with expectation H(X)H(X); similarly for YnY^n and the pair, with expectations H(Y)H(Y) and H(X,Y)H(X, Y). Thus each condition’s failure probability tends to zero, and the union bound bounds failure of any by their sum, also tending to zero. Apply AEP three times.

  2. Each pair in Aδ(n)A_\delta^{(n)} has p(xn,yn)≥2−n(H(X,Y)+δ)p(x^n, y^n) \ge 2^{-n(H(X, Y) + \delta)} and total mass is at most 1:

1≥∑(xn,yn)∈Aδ(n)p(xn,yn)≥∣Aδ(n)∣ 2−n(H(X,Y)+δ).1 \ge \sum_{(x^n, y^n) \in A_\delta^{(n)}} p(x^n, y^n) \ge \abs{A_\delta^{(n)}}\, 2^{-n(H(X, Y) + \delta)} .
  1. Now the pair has product distribution p(xn)p(yn)p(x^n)p(y^n). In Aδ(n)A_\delta^{(n)} the first two conditions give p(xn)≤2−n(H(X)−δ)p(x^n) \le 2^{-n(H(X) - \delta)} and p(yn)≤2−n(H(Y)−δ)p(y^n) \le 2^{-n(H(Y) - \delta)}, and property 2 bounds the number of terms:
P((X~n,Y~n)∈Aδ(n))=∑Aδ(n)p(xn) p(yn)≤2n(H(X,Y)+δ) 2−n(H(X)−δ) 2−n(H(Y)−δ)=2−n(I(X;Y)−3δ),\Pr\big((\tilde{X}^n, \tilde{Y}^n) \in A_\delta^{(n)}\big) = \sum_{A_\delta^{(n)}} p(x^n)\,p(y^n) \le 2^{n(H(X, Y) + \delta)}\, 2^{-n(H(X) - \delta)}\, 2^{-n(H(Y) - \delta)} = 2^{-n(I(X;Y) - 3\delta)},

because H(X)+H(Y)−H(X,Y)=I(X;Y)H(X) + H(Y) - H(X, Y) = I(X;Y).

∎

Property 3 is the theorem’s heart. An unsent codeword has probability of appearing compatible with the received word of order 2−nI2^{-nI}. With 2nR2^{nR} other codewords the expected number of impostors is of order 2n(R−I)2^{n(R - I)}, tending to zero if R<IR < I. The same calculation with the definition’s lower bounds also gives P≥(1−δ) 2−n(I(X;Y)+3δ)\Pr \ge (1 - \delta)\,2^{-n(I(X;Y) + 3\delta)} for large nn, so exponent II is correct.

For a binary symmetric channel with uniform input everything is exact. Since p(xn)=p(yn)=2−np(x^n) = p(y^n) = 2^{-n} for every sequence, the first two conditions always hold and −1nlog⁡p(xn,yn)=1+h2(ε)+(k/n−ε)log⁡1−εε-\frac1n\log p(x^n, y^n) = 1 + h_2(\varepsilon) + (k/n - \varepsilon)\log\frac{1 - \varepsilon}{\varepsilon} depends only on number kk of differing positions. Under the joint distribution k∼Bin⁡(n,ε)k \sim \Bin(n, \varepsilon); for the independent pair k∼Bin⁡(n,1/2)k \sim \Bin(n, 1/2).

[ ]Exact joint typicality in a binary symmetric channelBrowser
import numpy as np
from math import comb, log2
from scipy.stats import binom

eps, delta = 0.11, 0.1
h = -eps * log2(eps) - (1 - eps) * log2(1 - eps)
I, HXY = 1 - h, 1 + h                       # entrada uniforme: I(X;Y) = C
# el par es conjuntamente típico si y solo si |k/n - eps| * log2((1-eps)/eps) < delta
ancho = delta / log2((1 - eps) / eps)
print(f"I(X;Y) = {I:.4f}, H(X,Y) = {HXY:.4f};  típico  <=>  |k/n - {eps}| < {ancho:.4f}\n")
print(f"{'n':>5} {'P(típico)':>10} {'log2 P(indep)/n':>16} {'-(I - 3δ)':>10} {'log2|A|/n':>10} {'H(X,Y)+δ':>9}")
for n in [50, 200, 1000, 2000]:
    k = np.arange(n + 1)
    tip = np.abs(k / n - eps) < ancho
    p_tip = binom.pmf(k, n, eps)[tip].sum()          # par generado por el canal
    p_ind = binom.pmf(k, n, 0.5)[tip].sum()          # x^n e y^n independientes
    tam = n + log2(sum(comb(n, int(j)) for j in k[tip]))   # 2^n entradas, cada una con sus y^n típicas
    print(f"{n:5d} {p_tip:10.4f} {log2(p_ind) / n:16.4f} {-(I - 3 * delta):10.4f} {tam / n:10.4f} {HXY + delta:9.4f}")

The three properties are visible: typical probability rises to 0.99930.9993 with n=1000n = 1000 (slowly: the law of large numbers is in no hurry), set size stays below 2n(H(X,Y)+δ)2^{n(H(X,Y) + \delta)}, and independent-pair typicality probability decays like 2−0.41n2^{-0.41 n}, far faster than bound 2−0.20n2^{-0.20n} guarantees. The bound is loose because 3δ3\delta is worst-case slack; as δ→0\delta \to 0, actual exponent tends to I=0.5I = 0.5.

Achievability: random codes

To avoid integer parts assume 2nR2^{nR} is an integer; otherwise take ⌈2nR⌉\lceil 2^{nR} \rceil and nothing changes.

Proof

Fix input distribution p(x)p(x) and tolerance δ>0\delta > 0; later choose capacity-achieving pp and small δ\delta.

Random construction. Generate M=2nRM = 2^{nR} independent codewords, each with iid symbols according to pp: P(C)=∏w=1M∏i=1np(xi(w))\Pr(\mathcal{C}) = \prod_{w=1}^{M}\prod_{i=1}^{n} p(x_i(w)). Reveal the code to sender and receiver.

Joint-typicality decoding. On receiving yny^n, declare w^\hat{w} if (xn(w^),yn)∈Aδ(n)(x^n(\hat w), y^n) \in A_\delta^{(n)} and no other codeword is jointly typical with yny^n. If none or more than one is, declare error.

Average over codes. Instead of analyzing one code, calculate average error over messages and random codes:

Pˉe=∑CP(C) Pe(n)(C)=1M∑w=1M∑CP(C) λw(C).\bar{P}_e = \sum_{\mathcal{C}} \Pr(\mathcal{C})\, P_e^{(n)}(\mathcal{C}) = \frac{1}{M}\sum_{w=1}^{M} \sum_{\mathcal{C}} \Pr(\mathcal{C})\, \lambda_w(\mathcal{C}).

The construction is symmetric in messages: average error over codes does not depend on ww. Thus Pˉe=P(E∣W=1)\bar{P}_e = \Pr(\mathcal{E} \mid W = 1), where E\mathcal{E} is the error event and probability is joint over code and channel.

Error events. Let Ei={(Xn(i),Yn)∈Aδ(n)}E_i = \{(X^n(i), Y^n) \in A_\delta^{(n)}\}, with YnY^n the output when Xn(1)X^n(1) is sent. Error occurs if the correct word is not typical with output or another is: E⊆E1c∪E2∪⋯∪EM\mathcal{E} \subseteq E_1^c \cup E_2 \cup \cdots \cup E_M. By the union bound,

Pˉe≤P(E1c)+∑i=2MP(Ei).\bar{P}_e \le \Pr(E_1^c) + \sum_{i=2}^{M} \Pr(E_i).
  • (Xn(1),Yn)(X^n(1), Y^n) is an iid pair under p(x)W(y∣x)p(x)W(y \mid x), so P(E1c)≤δ\Pr(E_1^c) \le \delta for large nn by property 1.
  • For i≥2i \ge 2, Xn(i)X^n(i) is independent of Xn(1)X^n(1) and hence YnY^n, which depends only on Xn(1)X^n(1) and noise. Also Xn(i)∼p(xn)X^n(i) \sim p(x^n) and Yn∼p(yn)Y^n \sim p(y^n). Property 3 applies: P(Ei)≤2−n(I(X;Y)−3δ)\Pr(E_i) \le 2^{-n(I(X;Y) - 3\delta)}.

Therefore

Pˉe≤δ+(2nR−1) 2−n(I(X;Y)−3δ)≤δ+2−n(I(X;Y)−R−3δ)≤2δ\bar{P}_e \le \delta + (2^{nR} - 1)\,2^{-n(I(X;Y) - 3\delta)} \le \delta + 2^{-n(I(X;Y) - R - 3\delta)} \le 2\delta

for large nn whenever R<I(X;Y)−3δR < I(X;Y) - 3\delta.

Choose pp and show existence. Take capacity-achieving p=p∗p = p^*, so I(X;Y)=CI(X;Y) = C, and δ\delta with R<C−3δR < C - 3\delta. If mean error over all codes is ≤2δ\le 2\delta, some code C∗\mathcal{C}^* has Pe(n)(C∗)≤2δP_e^{(n)}(\mathcal{C}^*) \le 2\delta: a mean cannot be less than every term.

Expurgation: average to maximum error. Pe(n)(C∗)=1M∑iλi≤2δP_e^{(n)}(\mathcal{C}^*) = \frac1M\sum_i\lambda_i \le 2\delta. By Markov, fewer than half the messages can have λi>4δ\lambda_i > 4\delta (otherwise the mean would exceed 12⋅4δ=2δ\frac12 \cdot 4\delta = 2\delta). Discard the worst half. A code remains with 2nR−12^{nR - 1} words, rate R−1nR - \frac1n, and λi≤4δ\lambda_i \le 4\delta for all. Removing words does not worsen those retained with the same decoder: output decoded as a discarded message was already an error in λi\lambda_i.

Since δ\delta is arbitrary and rate loss 1n\frac1n vanishes, every R<CR < C is achievable with arbitrarily small maximum error. (To finish with exactly 2nR2^{nR} words start with 2nR+12^{nR + 1}, rate R+1nR + \frac1n, still below C−3δC - 3\delta for large nn.)

∎

Two specialist refinements:

  • Error exponent. The argument gives only Pˉe→0\bar P_e \to 0, without a rate. Gallager (1965) refined the union bound and proved average random-ensemble error under maximum-likelihood decoding satisfies Pˉe≤2−nEr(R)\bar P_e \le 2^{-nE_r(R)}, with exponent Er(R)>0E_r(R) > 0 for every R<CR < C vanishing at R=CR = C. Near capacity the exponent is small and very long blocks are needed.
  • Random linear codes. On the binary symmetric channel a random linear code (random generator matrix) suffices to reach capacity (Elias, 1955). Linearity lowers encoding and storage cost, but not optimal decoding: maximum-likelihood decoding of a general linear code is NP-hard (Berlekamp, McEliece and van Tilborg, 1978).

The converse: above capacity is impossible

The negative half needs a lemma: however nn channel uses are organized, information conveyed is at most nCnC.

Proof

By chain rule and memorylessness, H(Yn∣Xn)=∑iH(Yi∣Yi−1,Xn)=∑iH(Yi∣Xi)H(Y^n \mid X^n) = \sum_i H(Y_i \mid Y^{i-1}, X^n) = \sum_i H(Y_i \mid X_i), because given XiX_i output YiY_i is independent of everything else. By subadditivity H(Yn)≤∑iH(Yi)H(Y^n) \le \sum_i H(Y_i). Hence

I(Xn;Yn)=H(Yn)−∑iH(Yi∣Xi)≤∑i(H(Yi)−H(Yi∣Xi))=∑iI(Xi;Yi)≤nC.I(X^n; Y^n) = H(Y^n) - \sum_i H(Y_i \mid X_i) \le \sum_i \big(H(Y_i) - H(Y_i \mid X_i)\big) = \sum_i I(X_i; Y_i) \le nC .∎

Equality I(Xn;Yn)=∑iI(Xi;Yi)I(X^n;Y^n) = \sum_i I(X_i;Y_i) is not generally true even for a memoryless channel: code symbols are dependent and so are outputs. Only the inequality holds, and it suffices.

Proof

Let WW be uniform on {1,…,2nR}\{1, \dots, 2^{nR}\}, Xn=f(W)X^n = f(W), YnY^n the output, and W^=g(Yn)\hat W = g(Y^n). They form Markov chain W→Xn→Yn→W^W \to X^n \to Y^n \to \hat W. Then

nR=H(W)=H(W∣W^)+I(W;W^)≤(1+Pe(n) nR)+I(Xn;Yn)≤1+Pe(n) nR+nC.nR = H(W) = H(W \mid \hat W) + I(W; \hat W) \le \big(1 + P_e^{(n)}\, nR\big) + I(X^n; Y^n) \le 1 + P_e^{(n)}\, nR + nC .

The first term is bounded by Fano, H(W∣W^)≤h2(Pe(n))+Pe(n)log⁡(2nR−1)≤1+Pe(n) nRH(W \mid \hat W) \le h_2(P_e^{(n)}) + P_e^{(n)}\log(2^{nR} - 1) \le 1 + P_e^{(n)}\, nR; the second by data processing, I(W;W^)≤I(Xn;Yn)I(W; \hat W) \le I(X^n; Y^n); the last step is the lemma. Divide by nRnR and rearrange.

∎

With ε=0.11\varepsilon = 0.11 (C=0.5001C = 0.5001) and R=0.6R = 0.6, the bound gives Pe(n)≥0.1665−10.6nP_e^{(n)} \ge 0.1665 - \frac{1}{0.6n}: at least one in six blocks fails regardless of code length. The bound is weak in two named senses.

  • Strong converse. For discrete memoryless channels above capacity error not only fails to vanish: it tends to one, exponentially (Wolfowitz, 1957). Boundary R=CR = C is a cliff, like the figure’s step.
  • Finite length. The theorem is asymptotic. Polyanskiy, Poor and Verdú (2010) gave a second-order correction: the maximum message count at block error PeP_e and length nn satisfies
log⁡M∗(n,Pe)=nC−nV Q−1(Pe)+O(log⁡n),\log M^*(n, P_e) = nC - \sqrt{nV}\,Q^{-1}(P_e) + \bigO(\log n),

where Q−1Q^{-1} is the inverse standard-normal tail and VV channel dispersion, the variance of information density log⁡W(Y∣X)q(Y)\log\frac{W(Y \mid X)}{q(Y)} under optimal input. For the binary symmetric channel V=ε(1−ε)log⁡21−εεV = \varepsilon(1 - \varepsilon)\log^2\frac{1 - \varepsilon}{\varepsilon}. With ε=0.11\varepsilon = 0.11 and Pe=10−3P_e = 10^{-3}, the approximation (including term +12log⁡n+\frac12\log n, correct for BSC up to O(1)\bigO(1)) gives maximum rate 0.240.24 at n=100n = 100 (48% of CC), 0.410.41 at n=1000n = 1000 (83%), and 0.470.47 at n=104n = 10^4 (94%). Capacity is approached as 1/n1/\sqrt{n}, important in low-latency systems.

Source–channel separation

So far messages were uniform. In practice one sends a redundant source: text, image, or audio. Must one design a single source-to-channel code, or can one compress first (lessons 4–7) and protect the compressed result with a channel code? Shannon showed the modular second option loses nothing asymptotically.

Proof

Achievability. By AEP the source typical set has at most 2n(H(V)+δ)2^{n(H(\mathcal{V}) + \delta)} sequences and probability tending to 1. Index it with n(H(V)+δ)n(H(\mathcal{V}) + \delta) bits (the source coding theorem) and transmit the index with a rate-R=H(V)+δ<CR = H(\mathcal{V}) + \delta < C channel code. Error occurs only if the source is atypical or the channel fails; both probabilities vanish.

Converse. Chain Vn→Xn→Yn→V^nV^n \to X^n \to Y^n \to \hat V^n is Markov. By Fano on alphabet Vn\mathcal{V}^n and data processing,

H(Vn)=H(Vn∣V^n)+I(Vn;V^n)≤1+Pe(n) nlog⁡∣V∣+I(Xn;Yn)≤1+Pe(n) nlog⁡∣V∣+nC.H(V^n) = H(V^n \mid \hat V^n) + I(V^n; \hat V^n) \le 1 + P_e^{(n)}\, n\log\abs{\mathcal{V}} + I(X^n; Y^n) \le 1 + P_e^{(n)}\, n\log\abs{\mathcal{V}} + nC .

For a stationary process H(Vn)/nH(V^n)/n decreases to H(V)H(\mathcal{V}), so H(V)≤1n+Pe(n)log⁡∣V∣+CH(\mathcal{V}) \le \frac1n + P_e^{(n)}\log\abs{\mathcal{V}} + C. If Pe(n)→0P_e^{(n)} \to 0, H(V)≤CH(\mathcal{V}) \le C follows.

∎

The engineering lesson: the interface between compression and protection can be uniform bits. The compressor need not know the channel and the channel code need not know the source; this is why internet, mobile telephony, and storage use layers. But the theorem has qualifications.

  • Finite length and latency. Separation is optimal in the infinite-block limit. At finite length second-order source and channel penalties add, and joint coding can win (Kostina and Verdú, 2013 quantified this using dispersion). Speech, control, and real-time systems cannot use long blocks.
  • Uncoded transmission can be optimal. A Bernoulli source (1/2)(1/2) sent uncoded over a binary symmetric channel arrives with fraction ε\varepsilon erroneous bits. By rate–distortion theory (lesson 14), minimum Hamming distortion with one channel use per symbol is DD satisfying 1−h2(D)=C=1−h2(ε)1 - h_2(D) = C = 1 - h_2(\varepsilon), namely D=εD = \varepsilon: uncoded transmission is already optimal at zero delay. The same holds for a Gaussian source over a Gaussian channel (Goblick, 1965; Gastpar, Rimoldi and Vetterli, 2003 characterized when). Separation matches that optimum with very long blocks.
  • Fragility of compressed streams. A variable-length compressed code is fragile: a wrong bit desynchronizes Huffman decoding and damages multiple symbols; in lesson 7’s arithmetic coding it can destroy everything afterward. Separation assumes channel coding reduces residual error to zero; otherwise damage is amplified.
  • Multiuser networks. For broadcast or multiple-access channels with correlated sources, separation is not generally optimal.

The next cell builds the chain: compress text with Huffman (lesson 5), protect bits with Hamming (7,4), send through a binary symmetric channel with ε=0.01\varepsilon = 0.01, and measure reception.

[ ]Source–channel separation in practiceBrowser
import heapq, difflib
import numpy as np
from collections import Counter
from math import log2

texto = ("En mil novecientos cuarenta y ocho Claude Shannon publicó un artículo que separó para siempre "
         "dos problemas: describir una fuente con el menor número de bits y transmitir esos bits por un canal "
         "ruidoso sin errores. La primera mitad se resuelve comprimiendo hasta la entropía; la segunda, "
         "añadiendo redundancia bien elegida hasta acercarse a la capacidad. Lo sorprendente es que, para "
         "bloques largos, hacer las dos cosas por separado no cuesta nada: el diseño modular es óptimo. "
         "Para bloques cortos, o cuando el retardo importa, la historia es distinta.")

def huffman(frec):
    """Código de Huffman binario: devuelve {símbolo: cadena de bits}."""
    heap = [(f, i, {s: ""}) for i, (s, f) in enumerate(frec.items())]
    heapq.heapify(heap)
    cont = len(heap)
    while len(heap) > 1:
        f1, _, a = heapq.heappop(heap)
        f2, _, b = heapq.heappop(heap)
        heapq.heappush(heap, (f1 + f2, cont, {s: "0" + c for s, c in a.items()} | {s: "1" + c for s, c in b.items()}))
        cont += 1
    return heap[0][2]

def a_bits(txt, codigo):
    return np.array([int(b) for ch in txt for b in codigo[ch]], dtype=np.uint8)

def de_bits(bits, codigo):
    inverso, salida, actual = {c: s for s, c in codigo.items()}, [], ""
    for b in bits:
        actual += "1" if b else "0"
        if actual in inverso:
            salida.append(inverso[actual])
            actual = ""
    return "".join(salida)

frec = Counter(texto)
codigo = huffman(frec)
p = np.array(list(frec.values())) / len(texto)
H = -(p * np.log2(p)).sum()
bits = a_bits(texto, codigo)
assert de_bits(bits, codigo) == texto
print(f"{len(texto)} caracteres, {len(frec)} símbolos; H empírica = {H:.3f} bits/carácter, "
      f"Huffman = {len(bits) / len(texto):.3f} bits/carácter")

# Hamming (7,4): columnas de G = palabras de los datos unitarios; H tiene la columna j = j en binario
G = np.array([[1,1,1,0,0,0,0], [1,0,0,1,1,0,0], [0,1,0,1,0,1,0], [1,1,0,1,0,0,1]], dtype=np.uint8)
H74 = np.array([[(j >> i) & 1 for j in range(1, 8)] for i in range(3)], dtype=np.uint8)
assert not (G @ H74.T % 2).any()
DATOS = [2, 4, 5, 6]                              # posiciones 3, 5, 6, 7 (desde 0)

def proteger(b):
    relleno = (-len(b)) % 4
    d = np.concatenate([b, np.zeros(relleno, np.uint8)]).reshape(-1, 4)
    return (d @ G % 2).ravel(), relleno

def corregir(r, relleno):
    r = r.reshape(-1, 7).copy()
    pos = (r @ H74.T % 2) @ np.array([1, 2, 4])  # síndrome = posición del error
    f = np.nonzero(pos)[0]
    r[f, pos[f] - 1] ^= 1
    d = r[:, DATOS].ravel()
    return d[:len(d) - relleno] if relleno else d

rng = np.random.default_rng(1)
canal = lambda x, eps: x ^ (rng.random(len(x)) < eps).astype(np.uint8)

eps = 0.01
cod, rel = proteger(bits)
casos = [("sin protección", canal(bits, eps), len(bits)), ("con Hamming (7,4)", corregir(canal(cod, eps), rel), len(cod))]
for nombre, rx, usos in casos:
    dec = de_bits(rx, codigo)
    sim = difflib.SequenceMatcher(None, texto, dec, autojunk=False).ratio()
    print(f"\n{nombre}: {usos} usos del canal ({len(texto) / usos:.3f} caracteres por uso), "
          f"{int((rx != bits).sum())} bits mal tras el canal, similitud del texto {sim:.3f}")
    print("  «" + dec[:150] + "...»")
C = 1 + eps * log2(eps) + (1 - eps) * log2(1 - eps)
print(f"\nlímite de separación: C / H = {C:.3f} / {H:.3f} = {C / H:.3f} caracteres por uso")

# propagación: un único bit invertido en el flujo comprimido
danos = []
for i in rng.choice(len(bits), size=100, replace=False):
    b = bits.copy(); b[i] ^= 1
    m = difflib.SequenceMatcher(None, texto, de_bits(b, codigo), autojunk=False)
    danos.append(len(texto) - sum(bl.size for bl in m.get_matching_blocks()))
print(f"un solo bit invertido daña de media {np.mean(danos):.2f} caracteres (máximo {max(danos)}); "
      f"con 8 bits fijos por carácter dañaría exactamente uno")

Without protection about twenty erroneous bits make text readable but typo-filled, each bad bit damaging about three characters on average because Huffman briefly desynchronizes. Hamming (7,4) preserves almost everything (remaining failures are two-error blocks), at 7 transmitted bits per 4. Unprotected rate exceeds the separation limit C/HC/H characters per use and thus cannot be reliable; Hamming reaches 61% of that limit and still errs. A near-capacity code would close both gaps; a language model instead of a letter-frequency table would reduce HH from 4.2 bits per character to little over one (lesson 8), almost quadrupling the limit.

Linear codes

Random coding proves good codes exist, but a book of 2nR2^{nR} arbitrary words does not fit in memory or decode reasonably fast. The first transformative structure is linearity.

Work over field F2={0,1}\mathbb{F}_2 = \{0, 1\}, with exclusive-or addition and conjunction multiplication (Boolean algebra read as arithmetic modulo 2). Usual linear algebra—rank, kernel, Gaussian elimination—works over F2\mathbb{F}_2, except 1+1=01 + 1 = 0, so subtraction is addition.

Many texts use row vectors, c=uG\vb{c} = \vb{u}\mat{G} with G\mat{G} of size k×nk \times n, the transpose of ours. We retain this platform’s column vectors. That H\mat{H} has rank n−kn - k and kernel dimension kk is rank–nullity.

Weight and distance. Weight wt⁡(x)\operatorname{wt}(\vb{x}) counts ones; Hamming distance d(x,y)=wt⁡(x+y)d(\vb{x}, \vb{y}) = \operatorname{wt}(\vb{x} + \vb{y}) counts differing positions. The code’s minimum distance is d=min⁡c≠c′d(c,c′)d = \min_{\vb{c} \ne \vb{c}'} d(\vb{c}, \vb{c}'). By linearity c+c′\vb{c} + \vb{c}' is another codeword, so dd is the smallest nonzero codeword weight: examine 2k−12^k - 1 words instead of (2k2)\binom{2^k}{2} pairs. A distance-dd code corrects any pattern of up to t=⌊(d−1)/2⌋t = \lfloor (d - 1)/2 \rfloor errors (radius-tt balls around words are disjoint) and detects up to d−1d - 1. In terms of H\mat{H}, since Hc=∑j:cj=1hj\mat{H}\vb{c} = \sum_{j : c_j = 1} \vb{h}_j minimum distance is the smallest number of columns of H\mat{H} summing to zero.

Syndrome. If c\vb{c} is sent and the channel adds error pattern e\vb{e}, the receiver gets r=c+e\vb{r} = \vb{c} + \vb{e} and

s=Hr=Hc+He=He.\vb{s} = \mat{H}\vb{r} = \mat{H}\vb{c} + \mat{H}\vb{e} = \mat{H}\vb{e}.

The syndrome s∈F2n−k\vb{s} \in \mathbb{F}_2^{n-k} depends only on error, not the message. Patterns with one syndrome form a coset e+C\vb{e} + \mathcal{C}, of which there are 2n−k2^{n-k}. In the binary symmetric channel with ε<1/2\varepsilon < 1/2, a weight-ww pattern has probability εw(1−ε)n−w\varepsilon^w(1 - \varepsilon)^{n - w}, decreasing in ww. Maximum-likelihood decoding therefore chooses the minimum-weight pattern in the coset of s\vb{s} (its leader) and corrects c^=r+e^\hat{\vb{c}} = \vb{r} + \hat{\vb{e}}. The table has 2n−k2^{n-k} entries rather than 2k2^k codewords to compare: a major advantage at high rates, but still exponential.

Hamming (7,4)

At Bell Labs Hamming was tired of relay calculators aborting weekend jobs after detecting an error they could not correct. His 1950 answer is a code whose parity-check columns are all nonzero vectors in F23\mathbb{F}_2^3, ordered as binary numbers 1 through 7:

H=[101010101100110001111].\mat{H} = \begin{bmatrix} 1 & 0 & 1 & 0 & 1 & 0 & 1 \\ 0 & 1 & 1 & 0 & 0 & 1 & 1 \\ 0 & 0 & 0 & 1 & 1 & 1 & 1 \end{bmatrix}.

Columns 1, 2, and 4 form the identity, so rank is 3 and code dimension 7−3=47 - 3 = 4. Positions 1, 2, and 4 are parity; 3, 5, 6, and 7 are data. No columns are zero or repeated, so no two sum to zero; columns 1, 2, and 3 do. Minimum distance is d=3d = 3 and the code corrects one error. The elegance: an error at position jj has syndrome column jj, which is jj written in binary. The syndrome says not only that an error occurred, but where.

InteractiveHamming (7,4) in three circles
s₁: odd ✗s₂: even ✓s₃: odd ✗0p₁ · 11p₂ · 21d₁ · 30p₃ · 41d₂ · 51d₃ · 61d₄ · 7
1234567
c0110011
e0000100
r0110111
ĉ0110011
Parity-check matrix H: column j is j in binary
s₁ = 11010101
s₂ = 00110011
s₃ = 10001111
s=Hr=He(mod2)\vb{s} = \mat{H}\vb{r} = \mat{H}\vb{e} \pmod 2: the syndrome depends only on the error, never on the data.
Data to send
Errors introduced1
Syndrome (s3s2s1)(s_3 s_2 s_1)101₂ = 5
Position corrected5 (d₂)
Decoded data1 0 1 1
One error: the failing circles are exactly those containing position 5, and the syndrome read in binary is that number. The decoder corrects it and recovers the data.
Each circle is a row of H\mat{H}: a parity check requiring an even number of ones inside. Four data bits (d1,…,d4d_1, \dots, d_4, blue) lie at intersections and each parity bit completes its circle. Click any bit to flip it in the channel: failing dashed circles form the syndrome, identifying the position (green ring) and matching a column of H\mat{H}. Try a parity-bit error, then d4d_4 (in all three circles), then introduce two errors: what does the decoder do?

With two errors at positions ii and jj, syndrome i⊕ji \oplus j in binary identifies a third position, which the decoder “corrects”: the block leaves with three errors. This is not an algorithm defect but maximum-likelihood strategy: two errors are less likely than one with the same syndrome, so correcting one is rational. Three errors forming a codeword, such as positions 1, 2, and 3, give zero syndrome and go undetected.

Hamming is perfect. Each codeword has a radius-1 ball of 1+7=81 + 7 = 8 elements. The 16 balls are disjoint and 16⋅8=128=2716 \cdot 8 = 128 = 2^7: they exactly fill the space. Generally, a code correcting tt errors obeys the sphere-packing (Hamming) bound M V(n,t)≤2nM\,V(n, t) \le 2^n, where V(n,t)=∑i≤t(ni)V(n, t) = \sum_{i \le t}\binom{n}{i} is ball volume: the first figure’s count with radius tt instead of nεn\varepsilon. The Hamming family [2m−1, 2m−1−m][2^m - 1,\, 2^m - 1 - m] attains equality for every mm, so its decoder corrects exactly weight-0 or weight-1 patterns.

[ ]Hamming (7,4) from scratchBrowser
import numpy as np
from itertools import product

H = np.array([[(j >> i) & 1 for j in range(1, 8)] for i in range(3)])   # columna j = j en binario
DATOS, PARIDAD = [3, 5, 6, 7], [1, 2, 4]                               # posiciones, desde 1

def codificar(d):
    c = np.zeros(7, dtype=int)
    c[np.array(DATOS) - 1] = d
    for p in PARIDAD:          # cada paridad completa la de su círculo: las posiciones q con el bit de p
        c[p - 1] = c[[q - 1 for q in range(1, 8) if q & p and q != p]].sum() % 2
    return c

G = np.column_stack([codificar(u) for u in np.eye(4, dtype=int)])        # 7 x 4: c = G d
print("G =\n", G)
print("H G = 0 (mod 2):", not (H @ G % 2).any())

def decodificar(r):
    pos = (H @ r % 2) @ [1, 2, 4]          # el síndrome, leído en binario
    c = r.copy()
    if pos:
        c[pos - 1] ^= 1
    return c[np.array(DATOS) - 1], pos

d = np.array([1, 0, 1, 1])
c = G @ d % 2
for j in range(7):
    e = np.eye(7, dtype=int)[j]
    d_hat, pos = decodificar((c + e) % 2)
    assert pos == j + 1 and (d_hat == d).all()
print("los 7 errores simples se corrigen y el síndrome es la posición")

# distancia mínima: el menor peso de una palabra no nula
pesos = [int((G @ np.array(u) % 2).sum()) for u in product([0, 1], repeat=4) if any(u)]
print("distancia mínima:", min(pesos), "  distribución de pesos:", np.bincount(pesos, minlength=8))

# enumeración exacta de los 128 patrones de error (por linealidad, da igual qué palabra se envíe)
eps = 0.01
P_B = p_b = 0.0
for e in product([0, 1], repeat=7):
    e = np.array(e)
    w = e.sum()
    d_hat, _ = decodificar((c + e) % 2)
    prob = eps**w * (1 - eps) ** (7 - w)
    P_B += prob * (d_hat != d).any()
    p_b += prob * (d_hat != d).mean()
print(f"eps = {eps}: error de bloque {P_B:.6f} (fórmula {1 - (1 - eps)**7 - 7 * eps * (1 - eps)**6:.6f}), "
      f"error por bit {p_b:.6f}")

The weight distribution (1 word of weight 0, 7 of weight 3, 7 of weight 4, 1 of weight 7) confirms d=3d = 3. Exact block error 1−(1−ε)7−7ε(1−ε)61 - (1 - \varepsilon)^7 - 7\varepsilon(1 - \varepsilon)^6 is probability of two or more errors; bit error is lower because a wrong block does not spoil all four data bits.

Experiment: Shannon’s boundary

We can measure both the theorem’s promise and concrete codes’ performance. For a binary symmetric channel, rate versus error probability has two regions. With block error the boundary is line R=CR = C, but asymptotic: above CC the theorem prohibits error tending to zero with growing block length, not moderate error for a particular short code. For bit error pbp_b the boundary shifts: tolerating errors in fraction pbp_b of bits permits lossy compression before channel coding at 1−h2(pb)1 - h_2(p_b) bits per bit (rate–distortion, lesson 14), and maximum rate becomes

R(pb)=C1−h2(pb),R(p_b) = \frac{C}{1 - h_2(p_b)},

matching CC when pb→0p_b \to 0. This is a figure in MacKay’s first chapter. Unlike the block boundary it holds at any length: if kk uniform data bits U1,…,UkU_1, \dots, U_k become U^1,…,U^k\hat U_1, \dots, \hat U_k after nn uses, bitwise Fano and concavity of h2h_2 give ∑iH(Ui∣U^i)≤∑ih2(pi)≤k h2(pb)\sum_i H(U_i \mid \hat U_i) \le \sum_i h_2(p_i) \le k\,h_2(p_b), then k−k h2(pb)≤I(Uk;U^k)≤nCk - k\,h_2(p_b) \le I(U^k; \hat U^k) \le nC, namely R (1−h2(pb))≤CR\,(1 - h_2(p_b)) \le C.

InteractiveShannon's boundary
CimpossibleachievableuncodedR3R5H(7,4)H(15,11)
  • repetition (R₃ = 3 copies...)
  • Hamming
  • random linear (15, k), ML decoding
  • random ensemble, n = 1000
  • boundary R=C/(1−h2(pb))R = C/(1 - h_2(p_b))
0.100
Error probability
Capacity CC0.5310 bits
Rate R=k/nR = k/n0.5714
Bit error pbp_b0.0669
Minimum distance dd3
R/CR/C107.6 %
Maximum rate at this pbp_b0.8222
Allowing fraction pbp_b of erroneous bits, the boundary is R=C/(1−h2(pb))R = C / (1 - h_2(p_b)), slightly right of CC, for any length. At its pbp_b, this code uses 69% of the rate Shannon permits.
Rate versus error probability (log scale) on a binary symmetric channel. Points are exact, not simulated: repetition (binomial formula), Hamming (7,4) and (15,11), and seven random linear (15,k)(15, k) codes with maximum-likelihood decoding, enumerating 2152^{15} error patterns. Red is impossible: for bit error at any length; for block error as n→∞n \to \infty. The dashed violet curve is mean block error of random length-1000 codes with the first figure's ball decoder and best slack δ\delta per rate (an upper bound for bit error). Change ε\varepsilon and error type, then choose a code to see the fraction of capacity used. At ε=0.1\varepsilon = 0.1, where is Hamming (7,4) in block error?

Observe:

  • Repetition hugs the R=0R = 0 axis. Each point improves error by dividing rate; none approaches the boundary.
  • Hamming (7,4) can exceed capacity. With ε=0.1\varepsilon = 0.1, C=0.531<4/7C = 0.531 < 4/7. For block error it lies in the shaded region without contradiction: error 0.150.15 is moderate and with n=7n = 7 even the weak converse gives no positive bound (1−C/R−1/(nR)<01 - C/R - 1/(nR) < 0). What cannot exist is a family at rate 4/74/7 with block error tending to zero as length grows; the strong converse makes it tend to 1. For bit error (pb=0.067p_b = 0.067), whose boundary holds at every length, it lies in the achievable region far from the boundary.
  • Short random codes are mediocre. With n=15n = 15, a random linear code at Hamming (15,11)‘s rate is usually worse: structure wins at short lengths. The theorem promises random codes are good for large nn, confirmed by the violet curve with n=1000n = 1000: it reaches error 10−610^{-6} at 70% of capacity, far to the right of short codes.
  • Long Hamming is not the answer. Rates [2m−1,2m−1−m][2^m - 1, 2^m - 1 - m] tend to 1, but only one error per block is corrected; with fixed ε\varepsilon errors per block grow like nεn\varepsilon and block error tends to 1. Approaching capacity requires correction ability to grow linearly with nn.

The next cell simulates the experiment with nonlinear codes too: arbitrary codeword tables and brute-force decoding (minimum distance to every word, maximum likelihood on a binary symmetric channel).

[ ]Random codes versus Hamming on a binary symmetric channelBrowser
import numpy as np
from math import log2

rng = np.random.default_rng(0)
POP = np.array([bin(i).count("1") for i in range(1 << 16)], dtype=np.uint8)

def popcount(x):
    """Número de unos de cada entero (hasta 32 bits) de un array."""
    x = np.asarray(x, dtype=np.uint32)
    return POP[x & 0xFFFF].astype(np.int32) + POP[x >> 16]

def bsc(palabras, n, eps):
    """Pasa por un BSC(eps) palabras de n bits guardadas como enteros."""
    ruido = (rng.random((len(palabras), n)) < eps) @ (1 << np.arange(n))
    return palabras ^ ruido

class CodigoTabla:
    """Código dado por su tabla de 2^k palabras; decodificación de distancia mínima por fuerza bruta."""
    def __init__(self, nombre, n, palabras):
        self.nombre, self.n = nombre, n
        self.palabras = np.asarray(palabras, dtype=np.int64)
        self.k = int(log2(len(self.palabras)))
        self.R = self.k / n
    def decodificar(self, y):
        return popcount(y[:, None] ^ self.palabras[None, :]).argmin(axis=1)
    def dmin(self):
        d = popcount(self.palabras[:, None] ^ self.palabras[None, :])
        return int(d[~np.eye(len(d), dtype=bool)].min())

def repeticion(N):
    return CodigoTabla(f"repetición {N}", N, [0, (1 << N) - 1])

def hamming74():
    palabras = []
    for m in range(16):
        c = [0] * 7
        for pos, i in zip([3, 5, 6, 7], range(4)):
            c[pos - 1] = (m >> i) & 1
        for p in [1, 2, 4]:
            c[p - 1] = sum(c[q - 1] for q in range(1, 8) if q & p and q != p) % 2
        palabras.append(sum(b << i for i, b in enumerate(c)))
    return CodigoTabla("Hamming (7,4)", 7, palabras)

def aleatorio(n, k):
    return CodigoTabla(f"aleatorio ({n},{k})", n, rng.integers(0, 1 << n, size=1 << k))

def simular(codigo, eps, mensajes=10000):
    m = rng.integers(0, 1 << codigo.k, size=mensajes)
    m_hat = codigo.decodificar(bsc(codigo.palabras[m], codigo.n, eps))
    return np.mean(m_hat != m), popcount(m_hat ^ m).sum() / (mensajes * codigo.k)

codigos = [repeticion(3), hamming74(), aleatorio(16, 8), aleatorio(20, 10)]
EPS = [0.01, 0.05, 0.1]
print(f"{'código':18s} {'R':>6s} {'d':>3s}" + "".join(f"   eps={e:<4}  P_B     p_b " for e in EPS))
for c in codigos:
    fila = f"{c.nombre:18s} {c.R:6.3f} {c.dmin():3d}"
    for eps in EPS:
        B, b = simular(c, eps)
        fila += f"   {B:9.2e} {b:9.2e}"
    print(fila)
print("capacidad:", "   ".join(f"eps={e}: C = {1 + e * log2(e) + (1 - e) * log2(1 - e):.3f}" for e in EPS))
[ ]Random-code error falls slowly with nBrowser
eps = 0.05
C = 1 + eps * log2(eps) + (1 - eps) * log2(1 - eps)
print(f"códigos aleatorios de tasa 1/2 en un BSC({eps}); C = {C:.3f}")
print(f"{'n':>3s} {'P_B medio (3 códigos)':>22s} {'mejor':>8s} {'d mínima':>9s}")
for n in [8, 12, 16, 20]:
    res = []
    for _ in range(3):
        c = aleatorio(n, n // 2)
        res.append((simular(c, eps, mensajes=4000)[0], c.dmin()))
    P = np.array([r[0] for r in res])
    print(f"{n:3d} {P.mean():22.4f} {P.min():8.4f} {str([r[1] for r in res]):>9s}")

Two simulation lessons. First, at rate 1/21/2 and with n≤20n \le 20, random codes are worse than higher-rate Hamming (7,4). Column dd explains why: unstructured random codes almost always have word pairs at distance 0 or 1. This is the birthday paradox, not bad luck: with 2n/22^{n/2} words drawn from 2n2^n, exact duplication probability is already 1−e−1/2≈0.391 - e^{-1/2} \approx 0.39. At short lengths few bad pairs dominate; at long lengths they matter less relative to well-separated pairs, so the theorem’s average works. Second, block error falls with nn, slowly; reaching 10−610^{-6} at rate 1/21/2 on this channel (C=0.71C = 0.71) needs hundreds of bits, and a table of 2n/22^{n/2} hundreds-bit words cannot even be written. This is the gap between theorem and real system.

Beyond: codes approaching capacity

For four decades algebraic codes (BCH, Reed–Solomon, convolutional with Viterbi decoding) stayed several decibels from capacity on channels of interest. The breakthrough was a different idea: give up optimal decoding and use approximate iterative decoding on sparsely structured codes.

LDPC. A low-density parity-check code is linear with very few ones per row and column of H\mat{H} (Gallager, 1962). Its bipartite Tanner graph has a node per bit, a node per check, and an edge per one of H\mat{H}. Decoding is belief propagation on that factor graph: each bit sends checks its current belief (a likelihood ratio), each check responds with what parity implies about each bit given others, and the process iterates. Cost per iteration is linear in nn. The graph has cycles, so inference is not exact, but with sparse random H\mat{H} cycles are long and it works nearly as if absent. LDPC codes were forgotten until MacKay and Neal (1996) rediscovered them; in 2001 Chung, Forney, Richardson and Urbanke designed one 0.0045 dB from Shannon’s Gaussian-channel limit with 10710^7-bit blocks.

Turbo. Berrou, Glavieux and Thitimajshima (1993) concatenated two convolutional codes through an interleaver and decoded by exchanging information between soft decoders. They came within one decibel of capacity when consensus held that practically impossible. Turbo decoding was later understood as belief propagation on a loopy graph.

Polar. Arıkan (2009) gave the first explicit construction proven to achieve binary symmetric memoryless channel capacity with O(nlog⁡n)\bigO(n \log n) encoding and decoding. Polarization combines two channel copies through transformation 2×22 \times 2 recursively: the resulting nn synthetic channels become nearly perfect or nearly useless, with near-perfect fraction tending to CC. Data use only good channels. For erasure channel BEC(α)\mathrm{BEC}(\alpha) recursion is explicit: erasure probability zz becomes a worse channel with 2z−z22z - z^2 and a better one with z2z^2.

[ ]Erasure-channel polarizationBrowser
import numpy as np
import matplotlib.pyplot as plt

alfa = 0.5
z = np.array([alfa])
fracciones = {}
for nivel in range(1, 17):
    z = np.stack([2 * z - z**2, z**2], axis=1).ravel()   # canal peor y canal mejor de cada par
    if nivel in (4, 8, 12, 16):
        fracciones[nivel] = z.copy()
for nivel, zs in fracciones.items():
    print(f"n = 2^{nivel:<2d}: media de z = {zs.mean():.4f};  buenos (z < 1e-3) {np.mean(zs < 1e-3):.3f}, "
          f"malos (z > 1 - 1e-3) {np.mean(zs > 1 - 1e-3):.3f}, intermedios {np.mean((zs >= 1e-3) & (zs <= 1 - 1e-3)):.3f}")

for nivel, zs in fracciones.items():
    plt.plot(np.linspace(0, 1, len(zs)), np.sort(zs), label=f"n = 2^{nivel}")
plt.axvline(1 - alfa, color="gray", ls="--", lw=1)
plt.xlabel("fracción de canales sintéticos (ordenados)")
plt.ylabel("probabilidad de borrado z")
plt.legend(); plt.show()

Mean erasure probability is exactly preserved ((2z−z2)+z22=z\frac{(2z - z^2) + z^2}{2} = z) but moves toward extremes: with n=216n = 2^{16}, nearly 45% of synthetic channels have erasure probability below 10−310^{-3}, and the fraction tends to 1−α=C1 - \alpha = C. Convergence is slow, explaining why polar codes need improved decoders (list decoding with cyclic redundancy checks) to compete at short lengths.

Today LDPC protects data in DVB-S2 satellite television, Wi-Fi, and the 5G NR data channel; polar codes protect 5G NR control channels. The 1948 theorem took fifty years to become engineering, and its final tool, belief propagation, is the same approximate inference studied in graphical models.

Using libraries

Production does not write per-message decoding loops: batch vectorization, matrices over F2\mathbb{F}_2 represented as small integers, and exact formulas are used where available. NumPy and SciPy suffice for most of this lesson; modern LDPC, polar, and turbo codes have specialized libraries such as C++ AFF3CT or TensorFlow-based Sionna implementing iterative decoders and GPU error simulations.

[ ]Vectorized Hamming (15,11) and finite-length approximationBrowser
import numpy as np
from scipy.stats import binom, norm

m = 4
n, k = 2**m - 1, 2**m - 1 - m
H = ((np.arange(1, n + 1)[None, :] >> np.arange(m)[:, None]) & 1).astype(np.uint8)
pesos = 1 << np.arange(m)

rng = np.random.default_rng(0)
eps, N = 0.02, 200_000
E = (rng.random((N, n)) < eps).astype(np.uint8)     # lineal: basta enviar la palabra nula
S = (E @ H.T % 2) @ pesos                            # todos los síndromes de golpe
resto = E.copy()
f = np.nonzero(S)[0]
resto[f, S[f] - 1] ^= 1                              # corrige la posición indicada
P_B_sim = resto.any(axis=1).mean()
P_B = binom.sf(1, n, eps)                            # código perfecto: falla si y solo si hay 2 o más errores
print(f"Hamming ({n},{k}), eps = {eps}: error de bloque simulado {P_B_sim:.5f}, exacto {P_B:.5f}")

# aproximación normal de Polyanskiy, Poor y Verdú para el BSC
def h2(p):
    return -p * np.log2(p) - (1 - p) * np.log2(1 - p)

def tasa_max(n, eps, Pe):
    C = 1 - h2(eps)
    V = eps * (1 - eps) * np.log2((1 - eps) / eps) ** 2     # dispersión del canal
    return C - np.sqrt(V / n) * norm.isf(Pe) + 0.5 * np.log2(n) / n

eps = 0.11
print(f"\nBSC({eps}), C = {1 - h2(eps):.4f}: tasa máxima aproximada con error de bloque Pe")
for n_ in [100, 1000, 10_000]:
    print(f"  n = {n_:6d}:  Pe = 1e-3 -> {tasa_max(n_, eps, 1e-3):.3f}   Pe = 1e-6 -> {tasa_max(n_, eps, 1e-6):.3f}")

Two hundred thousand words decode in one matrix operation and simulation agrees with exact formula P(Bin⁡(15,ε)≥2)\Pr(\Bin(15, \varepsilon) \ge 2). The final table shows finite-length reliability cost: with n=1000n = 1000, demanding 10−610^{-6} instead of 10−310^{-3} reduces maximum rate from 0.410.41 to 0.360.36, a cut no code can avoid.

Common mistakes

Exercises

NumericHamming (7,4) block error
Calculate the block error probability of Hamming (7,4) with syndrome decoding on a binary symmetric channel with ε=0.01\varepsilon = 0.01.
QuizFar from capacity
With ε=0.01\varepsilon = 0.01, capacity is C≈0.919C \approx 0.919 and Hamming (7,4) transmits at 4/7≈0.5714/7 \approx 0.571 with block error 0.0020.002. Which statement is correct?
ProofIndependent pairs are almost never typical
Prove: If X~n\tilde X^n and Y~n\tilde Y^n are independent, with X~n∼p(xn)\tilde X^n \sim p(x^n) and Y~n∼p(yn)\tilde Y^n \sim p(y^n) (the marginals of p(xn,yn)p(x^n, y^n)), then P((X~n,Y~n)∈Aδ(n))≤2−n(I(X;Y)−3δ)\Pr\big((\tilde X^n, \tilde Y^n) \in A_\delta^{(n)}\big) \le 2^{-n(I(X;Y) - 3\delta)}.
0
Use the definition of Aδ(n)A_\delta^{(n)} and the bound ∣Aδ(n)∣≤2n(H(X,Y)+δ)\abs{A_\delta^{(n)}} \le 2^{n(H(X,Y) + \delta)}.

Step 1 of 4. How do you write the probability to be bounded?

ProofThe weak converse
Prove: Every (2nR,n)(2^{nR}, n) code for a discrete memoryless channel of capacity CC satisfies Pe(n)≥1−CR−1nRP_e^{(n)} \ge 1 - \frac{C}{R} - \frac{1}{nR}.
0
Let WW be uniform on {1,…,2nR}\{1, \dots, 2^{nR}\}, Xn=f(W)X^n = f(W), YnY^n the channel output and W^=g(Yn)\hat W = g(Y^n), with Pe(n)=P(W^≠W)P_e^{(n)} = \Pr(\hat W \ne W).

Step 1 of 5. Where do you start?

NumericThe error floor above capacity
A code of length n=1000n = 1000 transmits at rate R=0.6R = 0.6 over a binary symmetric channel with ε=0.11\varepsilon = 0.11. What lower bound does the weak converse give for its average error?
NumericHow many symbols per use?
A memoryless Bernoulli(0.1)(0.1) source is transmitted over a binary symmetric channel with ε=0.05\varepsilon = 0.05. According to the separation theorem, what is the largest number of source symbols per channel use that can be transmitted with error tending to zero (the supremum)?
QuizFrom average to maximum error
A random coding argument produces a code with M=2100M = 2^{100} codewords and average error Pe=1M∑iλi≤0.01P_e = \frac1M \sum_i \lambda_i \le 0.01. What can be guaranteed?
NumericPacking spheres
A binary code of length n=10n = 10 corrects any single error. According to the sphere-packing bound, how many codewords can it have at most?
QuizTrue or false
Which of these statements are true?

More than one answer may be correct.

CodeSyndrome decoding for any linear code
Implement decodificar_sindrome(H, R). H is an m×nm \times n parity-check matrix of zeros and ones and R an N×nN \times n matrix of received words, one per row. Return the N×nN \times n matrix of corrected words: for each row r\vb{r}, calculate its syndrome Hr mod 2\mat{H}\vb{r} \bmod 2, find the minimum-weight error pattern with that syndrome (its coset leader), and return r+e^ mod 2\vb{r} + \hat{\vb{e}} \bmod 2. Build the syndrome → leader table just once, visiting patterns in increasing weight order. You may assume n≤16n \le 16.
import numpy as np
from itertools import combinations

def decodificar_sindrome(H, R):
  """Corrige cada fila de R con el líder de coclase de su síndrome."""
  H = np.asarray(H, dtype=np.int64) % 2
  R = np.atleast_2d(np.asarray(R, dtype=np.int64)) % 2
  m, n = H.shape
  # tu código: tabla {síndrome: patrón de error de peso mínimo} y corrección de cada fila
  return R.copy()
Shift+Enter to run

Summary

Key idea
Every channel has a capacity C=max⁡pI(X;Y)C = \max_p I(X;Y): below it, error can be made arbitrarily small without lowering the rate, at the cost of long blocks; above it, this is impossible. The proof chooses the code randomly, and the distance between that argument and a decodable code is the history of coding theory.
  • An (M,n)(M, n) code has rate R=log⁡M/nR = \log M / n. Repetition gives zero error only at zero rate; Shannon gives zero error at a fixed rate by protecting many bits at once.
  • Two sequences are jointly typical if each and the pair have the expected probability. The transmitted and received pair is typical with probability tending to 1; an independent pair, with probability ≤2−n(I−3δ)\le 2^{-n(I - 3\delta)}.
  • Achievability: iid words according to p∗p^*, joint-typicality decoding, the union bound, averaging over codes to infer that a good one exists, and expurgation to move from average to maximum error.
  • Converse: Fano, data processing, and I(Xn;Yn)≤nCI(X^n;Y^n) \le nC give Pe≥1−C/R−1/(nR)P_e \ge 1 - C/R - 1/(nR). The strong converse drives error to 1, and at finite length the maximum rate is approximately C−V/n Q−1(Pe)C - \sqrt{V/n}\,Q^{-1}(P_e).
  • Separation: compressing to entropy and protecting up to capacity is optimal if H<CH < C, in the limit; with short blocks, latency, or fragile compressed streams, it ceases to be optimal.
  • A linear code is the kernel of a matrix H\mat{H} over F2\mathbb{F}_2; the syndrome Hr=He\mat{H}\vb{r} = \mat{H}\vb{e} depends only on the error. Hamming (7,4) is perfect: its syndrome is the error position in binary.
  • Codes approaching capacity (LDPC, turbo, polar) combine long blocks, sparse structure, and iterative message-passing decoding.