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 , repeating each bit 25 times and voting by majority reduces bit error below but leaves rate 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 , such that:
- at any rate codes exist with arbitrarily small error probability without lowering rate;
- at any rate no code achieves this.
For , : half a bit per use can be transmitted with error , , or , 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 is base-2 logarithm and information is in bits.
Channel codes
Fix a discrete memoryless channel which over uses acts as .
Rate is achievable if a sequence of codes exists with as . 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 copies, messages per block of uses and . Error is the probability that most of the copies flip, tending exponentially to zero in , but rate also tends to zero. If instead each of bits is repeated times with fixed , rate is fixed but the block fails if any of bits fails, with probability tending to 1 as grows. Repetition protects bits separately; Shannon’s idea is to protect many jointly, so noise in uses flipping almost exactly 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 . (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 is sent, noise flips about positions, so lands with high probability in a “ball” of about sequences around . For the receiver to distinguish codewords their balls must not overlap. Output space has sequences, so at most
codewords fit, namely . For a general channel with input , there are about typical outputs; each input generates a fan of about typical outputs, and disjoint fans fit. Choosing the best gives .
The surprising reverse direction is that the space can be filled nearly to this limit with almost disjoint balls, and random selection suffices.
Three points the figure shows and the proof formalizes:
- The transition is abrupt and sharpens with . At fixed length error rises smoothly with rate. As grows, the curve becomes a step: near zero left of a threshold, near one right. “Mean coverage” is the expected number of other codewords inside the received ball, and : exponential in with the difference’s sign.
- The slack threshold is not capacity but tends to it. The decoder needs a radius slightly greater than to contain noise with high probability; slack costs rate. When (and faster), threshold rises to . This is the role of joint-typicality .
- With small , error is dominated by noise outside the ball, not confusion: with , , and , coverage is (disks are invisible), but error is because noise exceeds weight with that probability. Practical lengths are therefore hundreds or thousands of bits.
Joint typicality
The AEP says an iid “typical” sequence has probability near . Decoding needs the same for pairs : sent and received words must “fit” as the channel would produce them.
We use for tolerance rather than lesson 4’s , 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 and almost never form a typical pair, precisely property 3 below.
Proof
-
By the weak law of large numbers in probability, being an iid mean with expectation ; similarly for and the pair, with expectations and . 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.
-
Each pair in has and total mass is at most 1:
- Now the pair has product distribution . In the first two conditions give and , and property 2 bounds the number of terms:
because .
∎Property 3 is the theorem’s heart. An unsent codeword has probability of appearing compatible with the received word of order . With other codewords the expected number of impostors is of order , tending to zero if . The same calculation with the definition’s lower bounds also gives for large , so exponent is correct.
For a binary symmetric channel with uniform input everything is exact. Since for every sequence, the first two conditions always hold and depends only on number of differing positions. Under the joint distribution ; for the independent pair .
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 with (slowly: the law of large numbers is in no hurry), set size stays below , and independent-pair typicality probability decays like , far faster than bound guarantees. The bound is loose because is worst-case slack; as , actual exponent tends to .
Achievability: random codes
To avoid integer parts assume is an integer; otherwise take and nothing changes.
Proof
Fix input distribution and tolerance ; later choose capacity-achieving and small .
Random construction. Generate independent codewords, each with iid symbols according to : . Reveal the code to sender and receiver.
Joint-typicality decoding. On receiving , declare if and no other codeword is jointly typical with . 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:
The construction is symmetric in messages: average error over codes does not depend on . Thus , where is the error event and probability is joint over code and channel.
Error events. Let , with the output when is sent. Error occurs if the correct word is not typical with output or another is: . By the union bound,
- is an iid pair under , so for large by property 1.
- For , is independent of and hence , which depends only on and noise. Also and . Property 3 applies: .
Therefore
for large whenever .
Choose and show existence. Take capacity-achieving , so , and with . If mean error over all codes is , some code has : a mean cannot be less than every term.
Expurgation: average to maximum error. . By Markov, fewer than half the messages can have (otherwise the mean would exceed ). Discard the worst half. A code remains with words, rate , and for all. Removing words does not worsen those retained with the same decoder: output decoded as a discarded message was already an error in .
Since is arbitrary and rate loss vanishes, every is achievable with arbitrarily small maximum error. (To finish with exactly words start with , rate , still below for large .)
∎Two specialist refinements:
- Error exponent. The argument gives only , without a rate. Gallager (1965) refined the union bound and proved average random-ensemble error under maximum-likelihood decoding satisfies , with exponent for every vanishing at . 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 channel uses are organized, information conveyed is at most .
Proof
By chain rule and memorylessness, , because given output is independent of everything else. By subadditivity . Hence
∎Equality 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 be uniform on , , the output, and . They form Markov chain . Then
The first term is bounded by Fano, ; the second by data processing, ; the last step is the lemma. Divide by and rearrange.
∎With () and , the bound gives : 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 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 and length satisfies
where is the inverse standard-normal tail and channel dispersion, the variance of information density under optimal input. For the binary symmetric channel . With and , the approximation (including term , correct for BSC up to ) gives maximum rate at (48% of ), at (83%), and at (94%). Capacity is approached as , 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 sequences and probability tending to 1. Index it with bits (the source coding theorem) and transmit the index with a rate- channel code. Error occurs only if the source is atypical or the channel fails; both probabilities vanish.
Converse. Chain is Markov. By Fano on alphabet and data processing,
For a stationary process decreases to , so . If , 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 sent uncoded over a binary symmetric channel arrives with fraction erroneous bits. By rate–distortion theory (lesson 14), minimum Hamming distortion with one channel use per symbol is satisfying , namely : 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 , and measure reception.
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 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 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 arbitrary words does not fit in memory or decode reasonably fast. The first transformative structure is linearity.
Work over field , with exclusive-or addition and conjunction multiplication (Boolean algebra read as arithmetic modulo 2). Usual linear algebra—rank, kernel, Gaussian elimination—works over , except , so subtraction is addition.
Many texts use row vectors, with of size , the transpose of ours. We retain this platform’s column vectors. That has rank and kernel dimension is rank–nullity.
Weight and distance. Weight counts ones; Hamming distance counts differing positions. The code’s minimum distance is . By linearity is another codeword, so is the smallest nonzero codeword weight: examine words instead of pairs. A distance- code corrects any pattern of up to errors (radius- balls around words are disjoint) and detects up to . In terms of , since minimum distance is the smallest number of columns of summing to zero.
Syndrome. If is sent and the channel adds error pattern , the receiver gets and
The syndrome depends only on error, not the message. Patterns with one syndrome form a coset , of which there are . In the binary symmetric channel with , a weight- pattern has probability , decreasing in . Maximum-likelihood decoding therefore chooses the minimum-weight pattern in the coset of (its leader) and corrects . The table has entries rather than 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 , ordered as binary numbers 1 through 7:
Columns 1, 2, and 4 form the identity, so rank is 3 and code dimension . 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 and the code corrects one error. The elegance: an error at position has syndrome column , which is written in binary. The syndrome says not only that an error occurred, but where.
With two errors at positions and , syndrome 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 elements. The 16 balls are disjoint and : they exactly fill the space. Generally, a code correcting errors obeys the sphere-packing (Hamming) bound , where is ball volume: the first figure’s count with radius instead of . The Hamming family attains equality for every , so its decoder corrects exactly weight-0 or weight-1 patterns.
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 . Exact block error 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 , but asymptotic: above the theorem prohibits error tending to zero with growing block length, not moderate error for a particular short code. For bit error the boundary shifts: tolerating errors in fraction of bits permits lossy compression before channel coding at bits per bit (rate–distortion, lesson 14), and maximum rate becomes
matching when . This is a figure in MacKay’s first chapter. Unlike the block boundary it holds at any length: if uniform data bits become after uses, bitwise Fano and concavity of give , then , namely .
Observe:
- Repetition hugs the axis. Each point improves error by dividing rate; none approaches the boundary.
- Hamming (7,4) can exceed capacity. With , . For block error it lies in the shaded region without contradiction: error is moderate and with even the weak converse gives no positive bound (). What cannot exist is a family at rate with block error tending to zero as length grows; the strong converse makes it tend to 1. For bit error (), whose boundary holds at every length, it lies in the achievable region far from the boundary.
- Short random codes are mediocre. With , 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 , confirmed by the violet curve with : it reaches error at 70% of capacity, far to the right of short codes.
- Long Hamming is not the answer. Rates tend to 1, but only one error per block is corrected; with fixed errors per block grow like and block error tends to 1. Approaching capacity requires correction ability to grow linearly with .
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).
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))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 and with , random codes are worse than higher-rate Hamming (7,4). Column explains why: unstructured random codes almost always have word pairs at distance 0 or 1. This is the birthday paradox, not bad luck: with words drawn from , exact duplication probability is already . 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 , slowly; reaching at rate on this channel () needs hundreds of bits, and a table of 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 (Gallager, 1962). Its bipartite Tanner graph has a node per bit, a node per check, and an edge per one of . 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 . The graph has cycles, so inference is not exact, but with sparse random 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 -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 encoding and decoding. Polarization combines two channel copies through transformation recursively: the resulting synthetic channels become nearly perfect or nearly useless, with near-perfect fraction tending to . Data use only good channels. For erasure channel recursion is explicit: erasure probability becomes a worse channel with and a better one with .
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 () but moves toward extremes: with , nearly 45% of synthetic channels have erasure probability below , and the fraction tends to . 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 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.
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 . The final table shows finite-length reliability cost: with , demanding instead of reduces maximum rate from to , a cut no code can avoid.
Common mistakes
Exercises
Step 1 of 4. How do you write the probability to be bounded?
Step 1 of 5. Where do you start?
More than one answer may be correct.
decodificar_sindrome(H, R). H is an parity-check matrix of zeros and ones and R an matrix of received words, one per row. Return the matrix of corrected words: for each row , calculate its syndrome , find the minimum-weight error pattern with that syndrome (its coset leader), and return . Build the syndrome → leader table just once, visiting patterns in increasing weight order. You may assume .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()Summary
- An code has rate . 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 .
- Achievability: iid words according to , 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 give . The strong converse drives error to 1, and at finite length the maximum rate is approximately .
- Separation: compressing to entropy and protecting up to capacity is optimal if , 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 over ; the syndrome 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.