Data Compression and Source Coding

What this note builds
  1. 01Code hierarchywhich codes a stream of keystrokes can be decoded from
  2. 02Kraft inequalityprefix codes share a fixed budget of tree space
  3. 03Entropy boundno code averages fewer than HH symbols per keystroke
  4. 04Shannon codesround up the surprise to get within one bit of HH
  5. 05Block codingspreading the rounding loss over nn keystrokes reaches the entropy rate
  6. 06Wrong codebookdesigning for qq instead of pp costs D(p∥q)D(p \Vert q) extra bits
  7. 07McMillan inequalitylook-ahead decoding buys no shorter codes
  8. 08Huffman codesgreedily merging the two rarest symbols gives an exactly optimal code
· 42 min read · 8,340 words

Motivation: from typical sets to actual codebooks

The AEP gave the telecom company a code costing about nH(X)nH(X) bits per tape. That code has three problems that make it unusable on a real telegraph line:

Problem with the typical-set codeWhy it matters on the wire
It only works for huge blocks. Its guarantees kick in “for nn sufficiently large”.The operator sends one telegram at a time. The company needs a codebook that works for one keystroke, or a short burst of them.
It is an existence proof. It indexes an abstract set Aϵ(n)A_\epsilon^{(n)} of size ≈2nH\approx 2^{nH}.Nobody can enumerate Aϵ(n)A_\epsilon^{(n)} for n=1000n = 1000. The engineer needs a construction that runs on the station’s hardware.
It left a converse open. We showed no smaller high-probability set beats the typical set.We did not show that no cleverer code beats HH bits per symbol. A smart engineer might still undercut the company with a scheme nobody thought of.

This note fixes all three. We work with a single random variable XX (one keystroke), find the shortest possible average description of it, prove that nothing beats the entropy, and give explicit algorithms that come within a bit of it.

IntuitionThe Morse code principle

Morse already did this by instinct. The most frequent English letter, E, is a single dot. Rare letters like Q get “dash, dash, dot, dash”. Short descriptions for frequent outcomes, long descriptions for rare ones. This note turns that rule of thumb into a theory with exact limits.


Codes

DefinitionSource code

A source code CC for a random variable XX is a mapping from X\mathcal{X}, the range of XX, to D∗\mathcal{D}^*, the set of finite-length strings from a DD-ary alphabet D={0,1,…,D−1}\mathcal{D} = \{0, 1, \ldots, D-1\}. C(x)C(x) is the codeword for xx, and l(x)l(x) is its length.

ComponentDetail
SignatureC:X→D∗C : \mathcal{X} \rightarrow \mathcal{D}^*
DomainThe operator’s alphabet: each key they can press.
CodomainFinite strings of pulses. For a binary wire, D=2D = 2 (on/off). For a wire with three distinguishable voltage levels, D=3D = 3.
ExampleC(red)=00C(\text{red}) = 00, C(blue)=11C(\text{blue}) = 11 is a binary code for X={red,blue}\mathcal{X} = \{\text{red}, \text{blue}\}.

DefinitionExpected length

L(C)=∑x∈Xp(x) l(x)L(C) = \sum_{x \in \mathcal{X}} p(x)\, l(x)

This is what the telecom actually pays per keystroke on average.

ExampleA code that hits the entropy exactly

xxp(x)p(x)C(x)C(x)
11/21/20
21/41/410
31/81/8110
41/81/8111

H(X)=1.75H(X) = 1.75 bits and L(C)=1.75L(C) = 1.75 bits. Any bit string decodes uniquely: 0110111100110 reads as 1 3 4 2 1 3.

ExampleA code that cannot hit the entropy

Three equally likely symbols with codewords 0, 10, 11. The code is just as decodable, but H(X)=log⁡3≈1.58H(X) = \log 3 \approx 1.58 bits while L(C)=13(1+2+2)≈1.67L(C) = \frac{1}{3}(1 + 2 + 2) \approx 1.67 bits. Here L>HL > H. We will see exactly why: the probabilities are not powers of 12\frac{1}{2}.

RemarkMorse is good, not optimal

Morse uses four symbols (dot, dash, letter space, word space), but wastes many possible codewords: letters contain no spaces except a terminating letter space, and no space may follow another. Counting the sequences allowed under such constraints was solved by Shannon in 1948. The same problem appears in magnetic recording, where long runs of 0s are forbidden.

The hierarchy of codes

The problem. The operator never sends one keystroke. They send a stream, and the codewords are concatenated on the wire with no gaps. A code that is unambiguous for one keystroke can still be ambiguous for a stream.

DefinitionNonsingular code

CC is nonsingular if distinct symbols get distinct codewords: x≠x′⇒C(x)≠C(x′)x \ne x' \Rightarrow C(x) \ne C(x').

DefinitionExtension of a code

The extension C∗C^* maps strings of symbols to strings of code symbols by concatenation:

C(x1x2⋯xn)=C(x1)C(x2)⋯C(xn)C(x_1 x_2 \cdots x_n) = C(x_1) C(x_2) \cdots C(x_n)

For example, if C(x1)=00C(x_1) = 00 and C(x2)=11C(x_2) = 11, then C(x1x2)=0011C(x_1x_2) = 0011.

DefinitionUniquely decodable code

CC is uniquely decodable if its extension C∗C^* is nonsingular. Every encoded stream has exactly one source string producing it, but you may have to read the whole stream before you can decode even the first symbol.

DefinitionPrefix (instantaneous) code

CC is a prefix code (or instantaneous code) if no codeword is a prefix of any other codeword.

IntuitionWhy “instantaneous” is the property the receiver wants

A prefix code is self-punctuating. The receiver reads pulses off the tape, and the moment the pulses read so far form a complete codeword, that symbol is decoded. No later pulse can change the verdict, because no longer codeword starts with that one. The commas are implicit. With the dyadic code above, 01011111010 parses on the fly as 0,10,111,110,10.

A merely uniquely decodable code is like a telegram whose first word you can’t read until the last word arrives. That is correct but useless for a live line.

flowchart TD
  A["All codes"] --> B["Nonsingular: one keystroke decodes"]
  B --> C["Uniquely decodable: a whole stream decodes"]
  C --> D["Instantaneous (prefix): each codeword decodes as soon as it ends"]

ExampleOne code in each class

xxSingularNonsingular, not UDUD, not instantaneousInstantaneous
100100
200100010
300111110
4010110111
  • Nonsingular, not UD: the stream 010 could be 2, or 1 4, or 3 1.
  • UD, not instantaneous: if the stream starts 00 or 10, decode at once. If it starts 11, count the run of 0s that follows. An odd run means the first codeword was 110 (symbol 4); an even run means it was 11 (symbol 3). You may have to look arbitrarily far ahead, but the answer is always unique.
  • Instantaneous: no codeword is a prefix of another.

NoteTesting unique decodability

Sardinas and Patterson give a finite test for unique decodability. It builds sets of possible dangling suffixes and eliminates them systematically (Cover & Thomas, Problem 5.27).


The Kraft inequality

The problem. We want short codewords. But we cannot make all codewords short and still keep the prefix property: the codeword 0 blocks every other codeword starting with 0. Before optimizing, we need to know exactly which lists of lengths l1,…,lml_1, \ldots, l_m are achievable by a prefix code.

TheoremKraft inequality

For any instantaneous code over an alphabet of size DD, the codeword lengths l1,l2,…,lml_1, l_2, \ldots, l_m must satisfy

∑iD−li≤1\sum_i D^{-l_i} \le 1

Conversely, given any lengths satisfying this inequality, there exists an instantaneous code with these lengths.

IntuitionA fixed budget of tree space

Picture every possible codeword as a node in an infinite DD-ary tree, with the root at the top and each branch one pulse. A codeword of length ll claims its node and everything below it, which is a fraction D−lD^{-l} of the tree. The prefix condition says claims cannot overlap. So the claimed fractions add up to at most the whole tree, which is 1. A short codeword is expensive: 0 alone eats half of a binary tree.

flowchart TD
  R((root)) -->|0| A["0: claims 1/2"]
  R -->|1| B(( ))
  B -->|0| C["10: claims 1/4"]
  B -->|1| D(( ))
  D -->|0| E["110: claims 1/8"]
  D -->|1| F["111: claims 1/8"]
ProofCount descendants at the deepest level

Step 1: Represent the code as a tree. Each codeword is a leaf of a DD-ary tree, and the path from the root spells its symbols. The prefix condition means no codeword is an ancestor of another.

Step 2: Look at the deepest level. Let lmax⁡l_{\max} be the longest codeword length. A codeword at depth lil_i has exactly Dlmax⁡−liD^{l_{\max} - l_i} descendants at depth lmax⁡l_{\max}.

Step 3: The descendant sets are disjoint. If two codewords shared a descendant, one would be an ancestor of the other, violating the prefix condition. There are only Dlmax⁡D^{l_{\max}} nodes at depth lmax⁡l_{\max}, so

∑iDlmax⁡−li≤Dlmax⁡\sum_i D^{l_{\max} - l_i} \le D^{l_{\max}}

Dividing by Dlmax⁡D^{l_{\max}} gives ∑iD−li≤1\sum_i D^{-l_i} \le 1.

Step 4 (converse): Greedy construction. Given lengths satisfying the inequality, sort them so l1≤l2≤⋯l_1 \le l_2 \le \cdots. Label the first available node (lexicographically) at depth l1l_1 as codeword 1 and delete its descendants. Then label the first remaining node at depth l2l_2, and so on. The Kraft inequality guarantees a node is always available, and deleting descendants keeps the code prefix-free.

∎

TheoremExtended Kraft inequality

For any countably infinite prefix code, ∑i=1∞D−li≤1\sum_{i=1}^\infty D^{-l_i} \le 1. Conversely, any l1,l2,…l_1, l_2, \ldots satisfying this can be realized by a prefix code.

ProofCodewords as subintervals of [0,1][0,1]

The tree proof needs a deepest level, which an infinite code doesn’t have. Use intervals instead.

Step 1: Codeword to number. Read codeword y1y2⋯yliy_1 y_2 \cdots y_{l_i} as the DD-ary fraction 0.y1y2⋯yli=∑j=1liyjD−j0.y_1 y_2 \cdots y_{l_i} = \sum_{j=1}^{l_i} y_j D^{-j}.

Step 2: Number to interval. The codeword “owns” the interval [0.y1⋯yli,  0.y1⋯yli+D−li)\big[0.y_1\cdots y_{l_i},\; 0.y_1 \cdots y_{l_i} + D^{-l_i}\big): every real number whose DD-ary expansion begins with that codeword. Its length is D−liD^{-l_i}.

Step 3: Prefix-free means disjoint. Two intervals overlap exactly when one codeword is a prefix of the other. Disjoint subintervals of [0,1][0,1] have total length at most 1, so ∑D−li≤1\sum D^{-l_i} \le 1.

Step 4 (converse). Sort the lengths increasingly and assign intervals in order from the low end of [0,1][0,1]. For binary lengths 1,2,…1, 2, \ldots this gives [0,12),[12,34),…[0, \frac{1}{2}), [\frac{1}{2}, \frac{3}{4}), \ldots, i.e. codewords 0, 10, ….

∎


Optimal codes and the entropy bound

The problem. Now we can state the engineer’s task as an optimization:

minimize L=∑ipiliover integers l1,…,lm subject to ∑iD−li≤1\text{minimize } L = \sum_i p_i l_i \quad \text{over integers } l_1, \ldots, l_m \text{ subject to } \sum_i D^{-l_i} \le 1

DerivationRelax the integers and use a Lagrange multiplier

Ignore the integer constraint and assume the Kraft budget is spent exactly. Minimize

J=∑pili+λ∑D−liJ = \sum p_i l_i + \lambda \sum D^{-l_i}

Differentiating, ∂J∂li=pi−λD−liln⁡D=0\frac{\partial J}{\partial l_i} = p_i - \lambda D^{-l_i} \ln D = 0, so D−li=piλln⁡DD^{-l_i} = \frac{p_i}{\lambda \ln D}. Summing over ii and using ∑D−li=1\sum D^{-l_i} = 1 gives λ=1/ln⁡D\lambda = 1/\ln D. Hence

pi=D−li,li∗=−log⁡Dpi,L∗=∑pili∗=HD(X)p_i = D^{-l_i}, \qquad l_i^* = -\log_D p_i, \qquad L^* = \sum p_i l_i^* = H_D(X)

IntuitionThe entropy reappears as a length

The relaxed optimum assigns each symbol exactly its surprise, −log⁡pi-\log p_i, as a codeword length. The averaged surprise is the entropy, so the ideal average length is the entropy. “Bits of surprise” was not just a metaphor: it is the length of the best possible description. Calculus only suggests this optimum, though. The theorem below proves it directly.

TheoremEntropy is a lower bound on expected length

The expected length of any instantaneous DD-ary code for XX satisfies

L≥HD(X)L \ge H_D(X)

with equality if and only if D−li=piD^{-l_i} = p_i for all ii.

ProofWrite the gap as a relative entropy plus a wasted-budget term

Step 1: Write the gap.

L−HD(X)=∑pili−∑pilog⁡D1pi=−∑pilog⁡DD−li+∑pilog⁡DpiL - H_D(X) = \sum p_i l_i - \sum p_i \log_D \frac{1}{p_i} = -\sum p_i \log_D D^{-l_i} + \sum p_i \log_D p_i

Step 2: Turn the lengths into a distribution. Let c=∑jD−ljc = \sum_j D^{-l_j} (the Kraft sum) and ri=D−li/cr_i = D^{-l_i}/c, a genuine pmf. Then D−li=c riD^{-l_i} = c\, r_i, and

L−H=∑pilog⁡Dpiri−log⁡Dc=D(p ∥ r)+log⁡D1cL - H = \sum p_i \log_D \frac{p_i}{r_i} - \log_D c = D(p \,\Vert\, r) + \log_D \frac{1}{c}

Step 3: Both terms are nonnegative. D(p∥r)≥0D(p \Vert r) \ge 0 by the information inequality, and log⁡D(1/c)≥0\log_D(1/c) \ge 0 because c≤1c \le 1 by Kraft. So L≥HL \ge H.

Step 4: Equality. Both terms must vanish: c=1c = 1 (the whole Kraft budget is spent) and p=rp = r, i.e. pi=D−lip_i = D^{-l_i}.

∎

IntuitionThe two ways a code wastes pulses

The proof splits the excess cost L−HL - H into two separate physical failures:

TermFailure
D(p∥r)D(p \Vert r)The lengths implicitly assume the operator’s distribution is ri∝D−lir_i \propto D^{-l_i}. Reality is pp. This is the wrong-codebook penalty, now with integer lengths.
log⁡D(1/c)\log_D(1/c)Unclaimed tree space. Some codewords could have been shortened without breaking the prefix property.

DefinitionDD-adic distribution

A distribution is DD-adic if every probability is D−nD^{-n} for some integer nn. So L=HL = H is achievable iff the distribution is DD-adic. The first example above was dyadic, which is why it hit 1.75 bits exactly; the uniform-on-three example was not.

RemarkA procedure we can’t easily run

The proof suggests an algorithm: find the DD-adic distribution closest to pp in relative entropy, use its exponents as lengths, and build the code with the greedy Kraft construction. The search for the closest DD-adic distribution is not obvious, though. Huffman’s algorithm (Huffman codes) is what actually solves the problem.


Bounds on the optimal code length

Shannon codes: within one bit

The problem. The ideal length log⁡1pi\log \frac{1}{p_i} is usually not an integer. The simplest fix is to round up.

DefinitionShannon code

Assign lengths

li=⌈log⁡D1pi⌉l_i = \left\lceil \log_D \frac{1}{p_i} \right\rceil

These satisfy Kraft, since ∑D−⌈log⁡D(1/pi)⌉≤∑D−log⁡D(1/pi)=∑pi=1\sum D^{-\lceil \log_D (1/p_i) \rceil} \le \sum D^{-\log_D(1/p_i)} = \sum p_i = 1, so the greedy construction turns them into a prefix code.

TheoremOptimal expected length is within one symbol of entropy

Let L∗L^* be the expected length of an optimal DD-ary code for XX. Then

HD(X)≤L∗<HD(X)+1H_D(X) \le L^* < H_D(X) + 1

ProofSandwich the optimum between the entropy and the Shannon code

Step 1: Shannon lengths are within one of the ideal. Rounding up loses less than one symbol:

log⁡D1pi≤li<log⁡D1pi+1\log_D \frac{1}{p_i} \le l_i < \log_D \frac{1}{p_i} + 1

Step 2: Average. Multiply by pip_i and sum: HD(X)≤LShannon<HD(X)+1H_D(X) \le L_{\text{Shannon}} < H_D(X) + 1.

Step 3: Sandwich. The optimal code is no worse than the Shannon code (L∗≤LShannonL^* \le L_{\text{Shannon}}) and no better than the entropy (L∗≥HDL^* \ge H_D by the theorem above).

∎

Spreading the overhead over a block

IntuitionWhy one bit of overhead is too much, and how to dilute it

For a binary operator with H(X)=0.1H(X) = 0.1 bits, “within one bit” means paying up to 1.1 bits per keystroke for 0.1 bits of information, an overhead of about 1000%. The fix is to encode supersymbols. Treat nn keystrokes as one symbol from Xn\mathcal{X}^n. The one-bit rounding loss is paid once per block, so it costs only 1/n1/n bits per keystroke.

TheoremBlock coding approaches the entropy

Encode nn i.i.d. keystrokes as one supersymbol, and let Ln=1nE l(X1,…,Xn)L_n = \frac{1}{n}\mathbb{E}\, l(X_1, \ldots, X_n) be the expected length per keystroke (binary, D=2D = 2). Then

H(X)≤Ln<H(X)+1nH(X) \le L_n < H(X) + \frac{1}{n}

ProofApply the one-bit bound to the supersymbol

The bound H≤L∗<H+1H \le L^* < H + 1 holds for any random variable, including the block (X1,…,Xn)(X_1, \ldots, X_n):

H(X1,…,Xn)≤E l(X1,…,Xn)<H(X1,…,Xn)+1H(X_1, \ldots, X_n) \le \mathbb{E}\, l(X_1, \ldots, X_n) < H(X_1, \ldots, X_n) + 1

For i.i.d. keystrokes H(X1,…,Xn)=nH(X)H(X_1, \ldots, X_n) = nH(X). Divide by nn.

∎

TheoremThe entropy rate is the compression limit for dependent sources

For any stochastic process (not necessarily i.i.d.), the minimum expected codeword length per symbol satisfies

H(X1,…,Xn)n≤Ln∗<H(X1,…,Xn)n+1n\frac{H(X_1, \ldots, X_n)}{n} \le L_n^* < \frac{H(X_1, \ldots, X_n)}{n} + \frac{1}{n}

If the process is stationary, then Ln∗→H(X)L_n^* \rightarrow H(\mathcal{X}), the entropy rate.

ImportantThis closes a gap left in the entropy-rates note

The entropy rate was introduced as an accounting figure, and we deferred its interpretation as the best achievable compression. This theorem supplies it, with the same sandwich argument applied to blocks of the stationary process. An operator with grammar can be described at H(X)H(\mathcal{X}) bits per keystroke, and no fewer.

The price of the wrong codebook

The problem. The company never knows the operator’s true distribution pp. It designs from its best estimate qq, for example English letter frequencies when the operator is actually writing about chemistry. How much does the mistake cost?

TheoremWrong code

The Shannon code designed for qq, l(x)=⌈log⁡1q(x)⌉l(x) = \lceil \log \frac{1}{q(x)} \rceil, has expected length under the true distribution pp satisfying

H(p)+D(p ∥ q)≤Ep l(X)<H(p)+D(p ∥ q)+1H(p) + D(p \,\Vert\, q) \le \mathbb{E}_p\, l(X) < H(p) + D(p \,\Vert\, q) + 1

ProofExpand the ceiling and split the logarithm

Upper bound:

Epl(X)=∑xp(x)⌈log⁡1q(x)⌉<∑xp(x)(log⁡1q(x)+1)\mathbb{E}_p l(X) = \sum_x p(x) \left\lceil \log \frac{1}{q(x)} \right\rceil < \sum_x p(x) \left( \log \frac{1}{q(x)} + 1 \right)

Insert 1=p(x)p(x)1 = \frac{p(x)}{p(x)} inside the logarithm and split:

=∑xp(x)log⁡p(x)q(x)+∑xp(x)log⁡1p(x)+1=D(p ∥ q)+H(p)+1= \sum_x p(x) \log \frac{p(x)}{q(x)} + \sum_x p(x) \log \frac{1}{p(x)} + 1 = D(p \,\Vert\, q) + H(p) + 1

Lower bound: the same computation with ⌈y⌉≥y\lceil y \rceil \ge y in place of ⌈y⌉<y+1\lceil y \rceil < y + 1.

∎

IntuitionRelative entropy, now earned

In the first note we motivated D(p∥q)D(p \Vert q) as wasted bits, using idealized non-integer codeword lengths. This theorem shows the story survives real integer codes: believing qq when the truth is pp costs exactly D(p∥q)D(p \Vert q) extra bits per keystroke, up to the usual one bit of rounding.


Kraft inequality for uniquely decodable codes

The problem. Uniquely decodable codes are a strictly larger class than prefix codes (the hierarchy table shows one that isn’t instantaneous). If we’re willing to let the receiver look ahead, could a uniquely decodable code beat the entropy bound, which we only proved for prefix codes?

TheoremMcMillan inequality

The codeword lengths of any uniquely decodable DD-ary code satisfy

∑iD−li≤1\sum_i D^{-l_i} \le 1

Conversely, lengths satisfying this inequality are achievable by a uniquely decodable code (indeed by a prefix code).

ProofKarush’s proof: raise the Kraft sum to the kk-th power

Step 1: Pass to the kk-th extension. If CC is uniquely decodable, its kk-th extension CkC^k (all concatenations of kk codewords) is nonsingular: distinct kk-symbol messages produce distinct pulse strings. The length of a concatenation is the sum of the lengths, l(xk)=∑i=1kl(xi)l(x^k) = \sum_{i=1}^k l(x_i).

Step 2: The kk-th power of the Kraft sum is a sum over messages.

(∑x∈XD−l(x))k=∑x1,…,xkD−l(x1)⋯D−l(xk)=∑xk∈XkD−l(xk)\left(\sum_{x \in \mathcal{X}} D^{-l(x)}\right)^k = \sum_{x_1, \ldots, x_k} D^{-l(x_1)} \cdots D^{-l(x_k)} = \sum_{x^k \in \mathcal{X}^k} D^{-l(x^k)}

Step 3: Group the messages by encoded length. Let a(m)a(m) be the number of kk-symbol messages whose encoding has length mm. Lengths range from 1 to k lmax⁡k\, l_{\max}:

∑xkD−l(xk)=∑m=1klmax⁡a(m)D−m\sum_{x^k} D^{-l(x^k)} = \sum_{m=1}^{k l_{\max}} a(m) D^{-m}

Step 4: Unique decodability caps a(m)a(m). There are only DmD^m pulse strings of length mm, and nonsingularity says no two messages share one. So a(m)≤Dma(m) \le D^m, and

(∑xD−l(x))k≤∑m=1klmax⁡DmD−m=k lmax⁡\left(\sum_x D^{-l(x)}\right)^k \le \sum_{m=1}^{k l_{\max}} D^m D^{-m} = k\, l_{\max}

Step 5: Take kk-th roots and let k→∞k \rightarrow \infty. ∑xD−l(x)≤(klmax⁡)1/k\sum_x D^{-l(x)} \le (k l_{\max})^{1/k} for every kk. The right side grows only linearly inside a kk-th root, so it tends to 1. Hence ∑D−l(x)≤1\sum D^{-l(x)} \le 1.

Step 6 (converse). Lengths satisfying Kraft give a prefix code, and every prefix code is uniquely decodable.

∎

IntuitionWhy the power trick works

If the Kraft sum ss exceeded 1, then sks^k would grow exponentially in kk. But unique decodability caps the number of kk-symbol messages that fit in each pulse length, so sks^k can grow at most linearly in kk. Exponential growth can’t stay below linear growth, so s≤1s \le 1. Long messages amplify any over-spending of the Kraft budget until it collides with the pigeonhole limit on distinct pulse strings.

CorollaryInfinite alphabets

A uniquely decodable code on a countably infinite alphabet also satisfies Kraft. The proof breaks only because lmax⁡=∞l_{\max} = \infty. The fix: every finite subset of a uniquely decodable code is uniquely decodable, so every partial sum is ≤1\le 1, and so is the limit.

ImportantLook-ahead buys nothing

The set of achievable codeword lengths is the same for uniquely decodable and instantaneous codes. Every bound in this note, including L≥HL \ge H, therefore holds for all uniquely decodable codes. The receiver gains nothing by waiting to see future pulses, so the engineer can insist on instantaneous decoding at no cost. This is the converse the AEP note left open: no uniquely decodable scheme whatsoever averages below HH.


Huffman codes

The problem. The Shannon code is within one bit of optimal, but it can be badly wasteful on individual symbols, and “within one bit” is not “optimal”. We want the code that exactly minimizes ∑pili\sum p_i l_i over integer lengths.

IntuitionThe key observation

In an optimal code, the two least likely symbols should get the two longest codewords, and those should have equal length. If one were longer, you could delete its last pulse and still be prefix-free. So the two rarest symbols can be made siblings differing only in the last pulse. Treat them as one merged symbol and solve the smaller problem.

AlgorithmHuffman’s algorithm (binary)

  1. Take the two least probable symbols.
  2. Merge them into one symbol whose probability is their sum.
  3. Repeat until one symbol remains.
  4. Read the codewords back down the merge tree: each merge splits a codeword into “append 0” and “append 1”.

ExampleA binary Huffman code

X∈{1,2,3,4,5}X \in \{1,2,3,4,5\} with probabilities (0.25,0.25,0.2,0.15,0.15)(0.25, 0.25, 0.2, 0.15, 0.15).

MergeCombinedRemaining probabilities
14+5→0.304 + 5 \rightarrow 0.300.30,0.25,0.25,0.200.30, 0.25, 0.25, 0.20
23+2→0.453 + 2 \rightarrow 0.450.45,0.30,0.250.45, 0.30, 0.25
31+{4,5}→0.551 + \{4,5\} \rightarrow 0.550.55,0.450.55, 0.45
4everything →1\rightarrow 1—
xxp(x)p(x)CodewordLength
10.25012
20.25102
30.20112
40.150003
50.150013

Expected length: L=2.3L = 2.3 bits. For comparison, H(X)≈2.29H(X) \approx 2.29 bits.

flowchart TD
  R["1.00"] -->|0| A["0.55"]
  R -->|1| B["0.45"]
  A -->|0| C["0.30"]
  A -->|1| X1["x=1: 0.25"]
  B -->|0| X2["x=2: 0.25"]
  B -->|1| X3["x=3: 0.20"]
  C -->|0| X4["x=4: 0.15"]
  C -->|1| X5["x=5: 0.15"]

ExampleA ternary Huffman code

Same distribution, D=3D = 3: merge the three least likely symbols at each step. Merging 3,4,53, 4, 5 gives 0.50.5, and the final merge is {0.5,0.25,0.25}\{0.5, 0.25, 0.25\}. The codewords are 1, 2 for symbols 1 and 2, and 00, 01, 02 for symbols 3–5. L=1.5L = 1.5 ternary digits.

WarningDD-ary Huffman needs dummy symbols

Each DD-ary merge reduces the symbol count by D−1D - 1. To end with exactly one symbol, the starting count must be 1+k(D−1)1 + k(D-1) for some number of merges kk. If it isn’t, pad with dummy symbols of probability 0. They occupy the deepest leaves and cost nothing. For example, 6 symbols with D=3D = 3 need one dummy, since 7=1+3⋅27 = 1 + 3 \cdot 2.

Comments on Huffman codes

IntuitionSource coding is the game of 20 questions

Identifying an object by yes/no questions is a binary code: each answer is a bit, and the sequence of answers must uniquely determine the object. Conversely, any binary code gives a questioning scheme (“Is the first bit of the object’s codeword a 1?”). So the best questioning strategy is the Huffman code, and the expected number of questions satisfies

H(X)≤EQ<H(X)+1H(X) \le \mathbb{E}Q < H(X) + 1

In the binary Huffman example, the optimal first question is “Is X∈{2,3}X \in \{2, 3\}?” (the first bit). The second question need not wait for the answer: “Is X∈{1,3}X \in \{1, 3\}?” determines the second bit independently.

RemarkWeighted codewords

Huffman’s algorithm never uses ∑pi=1\sum p_i = 1. Run on any nonnegative weights wiw_i, it minimizes the weighted sum ∑wili\sum w_i l_i.

RemarkSlice (alphabetic) codes

Huffman questions have the form “Is X∈AX \in A?” for arbitrary sets AA. Suppose only slice questions “Is X>aX > a?” are allowed, with symbols ordered so p1≥⋯≥pmp_1 \ge \cdots \ge p_m. Take the Huffman lengths (sorted increasingly) and assign them by the greedy first-available-node rule. The result is still optimal, because it has the same lengths, and every bit now splits the symbols into a lower and an upper range. For the binary example, lengths {2,2,2,3,3}\{2,2,2,3,3\} give 00, 01, 10, 110, 111. These are called alphabetic codes, because the codewords are in alphabetical order.

WarningShannon codes can be terrible on individual symbols

Two symbols with probabilities 0.99990.9999 and 0.00010.0001. Shannon lengths are ⌈log⁡10.9999⌉=1\lceil \log \frac{1}{0.9999} \rceil = 1 and ⌈log⁡10.0001⌉=14\lceil \log \frac{1}{0.0001} \rceil = 14 bits. The optimal code uses 1 bit for each.

Warning…but optimal codes can be longer than Shannon on some symbols

Distribution (13,13,14,112)(\frac{1}{3}, \frac{1}{3}, \frac{1}{4}, \frac{1}{12}). Depending on tie-breaking, Huffman gives lengths (2,2,2,2)(2,2,2,2) or (1,2,3,3)(1,2,3,3), both with expected length 2. In the second, the third symbol gets 3 bits, more than its Shannon length ⌈log⁡4⌉=2\lceil \log 4 \rceil = 2. So optimal lengths are not unique, and neither code dominates the other symbol by symbol. Only on average is Huffman better, and the two averages differ by less than one bit (both lie in [H,H+1)[H, H+1)).

RemarkFano codes

Fano’s suboptimal scheme sorts the probabilities, splits them at the index kk that best balances the two halves’ total probability, assigns 0 to the upper half and 1 to the lower, and recurses. It is not optimal in general, but achieves L≤H(X)+2L \le H(X) + 2.


Optimality of Huffman codes

The problem. Huffman’s algorithm is greedy: it only ever looks at the two smallest probabilities. Why should a sequence of local decisions produce a globally optimal code?

LemmaCanonical optimal codes

Order the probabilities p1≥p2≥⋯≥pmp_1 \ge p_2 \ge \cdots \ge p_m. There exists an optimal instantaneous code such that:

  1. lengths are ordered inversely to probabilities: pj>pk⇒lj≤lkp_j > p_k \Rightarrow l_j \le l_k;
  2. the two longest codewords have the same length;
  3. two of the longest codewords differ only in the last bit and belong to the two least likely symbols.

Such codes are called canonical.

ProofSwap, trim, rearrange

Start from any optimal code CmC_m.

Property 1 (swap). Suppose pj>pkp_j > p_k. Swap the codewords of jj and kk to get Cm′C_m':

L(Cm′)−L(Cm)=pjlk+pklj−pjlj−pklk=(pj−pk)(lk−lj)L(C_m') - L(C_m) = p_j l_k + p_k l_j - p_j l_j - p_k l_k = (p_j - p_k)(l_k - l_j)

CmC_m is optimal, so this is ≥0\ge 0. Since pj−pk>0p_j - p_k > 0, we need lk≥ljl_k \ge l_j.

Property 2 (trim). If the longest codeword were strictly longer than all others, delete its last bit. The result is still prefix-free (no other codeword is that long) and has strictly smaller expected length, contradicting optimality.

Property 3 (rearrange). Every maximal-length codeword has a sibling (the same codeword with its last bit flipped). Otherwise we could trim it as above. Swap codewords among the maximal-length ones, which doesn’t change ∑pili\sum p_i l_i since they all have the same length, so that the two least likely symbols sit on a sibling pair.

∎

DefinitionHuffman reduction

For p=(p1,…,pm)p = (p_1, \ldots, p_m) with p1≥⋯≥pmp_1 \ge \cdots \ge p_m, the Huffman reduction is the (m−1)(m-1)-symbol distribution

p′=(p1,…,pm−2,  pm−1+pm)p' = (p_1, \ldots, p_{m-2},\; p_{m-1} + p_m)

TheoremHuffman coding is optimal

If C∗C^* is a Huffman code and C′C' is any uniquely decodable code for the same distribution, then L(C∗)≤L(C′)L(C^*) \le L(C').

ProofExpand an optimal reduced code, condense an optimal full code, and compare

Let L∗(p)L^*(p) and L∗(p′)L^*(p') be the optimal expected lengths for pp and its reduction p′p'.

Step 1: Expand. Take an optimal code for p′p'. Split the codeword of the merged symbol pm−1+pmp_{m-1} + p_m by appending 0 (for m−1m-1) and 1 (for mm). Only those two symbols get one bit longer, so the resulting code for pp has

Lexp(p)=L∗(p′)+pm−1+pmL_{\text{exp}}(p) = L^*(p') + p_{m-1} + p_m

Step 2: Condense. Take a canonical optimal code for pp. By the lemma, symbols m−1m-1 and mm are siblings. Merge them into their parent node, which shortens both by one bit. The resulting code for p′p' has

Lcond(p′)=L∗(p)−pm−1−pmL_{\text{cond}}(p') = L^*(p) - p_{m-1} - p_m

Step 3: Add the two equations.

(Lexp(p)−L∗(p))+(Lcond(p′)−L∗(p′))=0\big(L_{\text{exp}}(p) - L^*(p)\big) + \big(L_{\text{cond}}(p') - L^*(p')\big) = 0

Each bracket is ≥0\ge 0, because no code beats the optimum. Two nonnegative numbers summing to 0 are both 0. So Lexp(p)=L∗(p)L_{\text{exp}}(p) = L^*(p): expanding an optimal code for the reduction gives an optimal code for the original.

Step 4: Induct. For two symbols the optimal code (0, 1) is obvious. Huffman’s algorithm is exactly repeated reduction followed by repeated expansion, so by induction it is optimal for every mm. McMillan extends the comparison from prefix codes to all uniquely decodable codes.

∎

IntuitionGreedy works because the problem factorizes

Merging the two rarest symbols adds a fixed cost pm−1+pmp_{m-1} + p_m, independent of how the rest of the code is built. So minimizing the full problem is the same as minimizing the reduced problem plus a constant. Local optimality is global optimality here because the merge’s cost doesn’t interact with anything else.

NoteScope of the proof

The proof is given for binary codes. It extends to DD-ary Huffman codes (with dummy symbols). There are always many optimal codes: flipping every bit, or swapping two equal-length codewords, gives another. Huffman’s algorithm finds one of them.


Shannon–Fano–Elias coding

The problem. Huffman needs the whole distribution sorted and a merge tree built before the first pulse is sent. We want a code computed directly from the cumulative distribution function, with no sorting. That is the seed of arithmetic coding, which can encode long sequences one symbol at a time.

DefinitionModified cumulative distribution

Let X={1,…,m}\mathcal{X} = \{1, \ldots, m\} with all p(x)>0p(x) > 0, and F(x)=∑a≤xp(a)F(x) = \sum_{a \le x} p(a). Define the midpoint of the step at xx:

Fˉ(x)=∑a<xp(a)+12p(x)\bar{F}(x) = \sum_{a < x} p(a) + \frac{1}{2} p(x)

IntuitionA symbol is a stretch of the unit interval

The CDF is a staircase. Symbol xx owns the vertical step [F(x−1),F(x))[F(x-1), F(x)), of height p(x)p(x), and these steps tile [0,1][0,1]. Any number inside xx‘s step identifies xx. So we transmit a number in that step, with just enough binary digits to stay inside it. Wide steps (likely symbols) need few digits; narrow steps (rare symbols) need many.

DefinitionShannon–Fano–Elias code

Write Fˉ(x)\bar{F}(x) in binary and truncate it to

l(x)=⌈log⁡1p(x)⌉+1l(x) = \left\lceil \log \frac{1}{p(x)} \right\rceil + 1

bits. That truncation, ⌊Fˉ(x)⌋l(x)\lfloor \bar{F}(x) \rfloor_{l(x)}, is the codeword.

ProofThe code identifies xx and is prefix-free

Step 1: Truncation stays in the step. Truncating to l(x)l(x) bits moves the number down by less than 2−l(x)2^{-l(x)}. With the chosen length,

2−l(x)≤p(x)2=Fˉ(x)−F(x−1)2^{-l(x)} \le \frac{p(x)}{2} = \bar{F}(x) - F(x-1)

The midpoint sits p(x)/2p(x)/2 above the bottom of the step, so the truncated value still lies inside xx‘s step.

Step 2: Codeword as interval. Read the codeword z1⋯zlz_1 \cdots z_l as the interval [0.z1⋯zl,  0.z1⋯zl+2−l)[0.z_1 \cdots z_l,\; 0.z_1\cdots z_l + 2^{-l}). The code is prefix-free exactly when these intervals are disjoint (as in the extended Kraft proof).

Step 3: Each interval fits inside its own step. The interval starts in the lower half of the step (at or below the midpoint), and its length 2−l(x)2^{-l(x)} is at most half the step’s height. So it ends below the top of the step. Steps of different symbols are disjoint, hence so are the intervals.

∎

TheoremExpected length within two bits

L=∑xp(x)(⌈log⁡1p(x)⌉+1)<H(X)+2L = \sum_x p(x) \left( \left\lceil \log \frac{1}{p(x)} \right\rceil + 1 \right) < H(X) + 2

ExampleA dyadic source

xxp(x)p(x)F(x)F(x)Fˉ(x)\bar{F}(x)Fˉ\bar{F} in binaryl(x)l(x)Codeword
10.250.250.1250.0013001
20.50.750.50.10210
30.1250.8750.81250.110141101
40.1251.00.93750.111141111

L=2.75L = 2.75 bits, against H=1.75H = 1.75 bits, which Huffman would achieve exactly. The waste is visible: the last bit of the last two codewords is superfluous. But dropping the last bit from every codeword breaks the prefix property.

ExampleA non-dyadic source

Same distribution as the Huffman example. Non-dyadic probabilities have infinite binary expansions, which are truncated:

xxp(x)p(x)Fˉ(x)\bar{F}(x)Fˉ\bar{F} in binaryl(x)l(x)Codeword
10.250.1250.0013001
20.250.3750.0113011
30.200.60.1001…41001
40.150.7750.1100011…41100
50.150.9250.1110110…41110

L=3.5L = 3.5 bits, which is 1.2 bits worse than Huffman’s 2.3.

ImportantWhy bother, if it’s worse than Huffman?

Because it extends to sequences without building anything exponential. Coding a block of nn keystrokes directly with Huffman needs probabilities for all ∣X∣n\lvert \mathcal{X} \rvert^n blocks. With Shannon–Fano–Elias, the probability and the CDF of a sequence can be updated one symbol at a time, so the work grows linearly in nn. Arithmetic coding (Chapter 13) adds fixed-precision arithmetic to make this practical. It underlies JPEG and fax compression.


Competitive optimality of the Shannon code

The problem. Huffman minimizes the average length. A rival engineer can still beat it on particular keystrokes by giving short codewords to rare symbols. So consider a head-to-head game. Two players each design a prefix code for the same pp. A symbol is drawn, and the player with the shorter codeword wins +1+1, the other loses 11, with ties paying 0. Can anyone beat the Shannon code most of the time?

NoteWhy the Shannon code, not Huffman

Huffman lengths have no closed form, which makes them hard to analyze. The Shannon code l(x)=⌈log⁡1p(x)⌉l(x) = \lceil \log \frac{1}{p(x)} \rceil does have one.

TheoremA rival rarely wins by much

Let l(x)l(x) be Shannon code lengths and l′(x)l'(x) the lengths of any uniquely decodable code. Then for every cc,

Pr⁡(l(X)≥l′(X)+c)≤12c−1\Pr\big(l(X) \ge l'(X) + c\big) \le \frac{1}{2^{c-1}}

For example, the chance that a rival’s codeword is at least 5 bits shorter than the Shannon codeword is at most 116\frac{1}{16}.

ProofConvert “much shorter” into “improbable”, then apply Kraft

Step 1: Remove the ceiling. l(X)<log⁡1p(X)+1l(X) < \log \frac{1}{p(X)} + 1, so

Pr⁡(l(X)≥l′(X)+c)≤Pr⁡(log⁡1p(X)≥l′(X)+c−1)=Pr⁡(p(X)≤2−l′(X)−c+1)\Pr\big(l(X) \ge l'(X) + c\big) \le \Pr\left(\log \frac{1}{p(X)} \ge l'(X) + c - 1\right) = \Pr\big(p(X) \le 2^{-l'(X) - c + 1}\big)

Step 2: Bound the probability of those symbols. Sum p(x)p(x) over the symbols where the condition holds, and use the condition itself as the bound on each term:

∑x: p(x)≤2−l′(x)−c+1p(x)≤∑x2−l′(x)2−(c−1)≤2−(c−1)\sum_{x:\, p(x) \le 2^{-l'(x)-c+1}} p(x) \le \sum_x 2^{-l'(x)} 2^{-(c-1)} \le 2^{-(c-1)}

since ∑x2−l′(x)≤1\sum_x 2^{-l'(x)} \le 1 by McMillan.

∎

IntuitionShort codewords must be rationed

A rival can beat Shannon by cc bits only on symbols that are rare enough, p(x)≤2−l′(x)−c+1p(x) \le 2^{-l'(x) - c + 1}. But the rival’s own Kraft budget limits how much probability can sit on symbols it gives short codewords to. Winning big is possible only on a probability mass that shrinks exponentially in cc.

TheoremFor dyadic sources, Shannon wins the head-to-head game

If pp is dyadic and l(x)=log⁡1p(x)l(x) = \log \frac{1}{p(x)} (an integer), then for any other uniquely decodable code l′l',

Pr⁡(l(X)<l′(X))≥Pr⁡(l(X)>l′(X))\Pr\big(l(X) < l'(X)\big) \ge \Pr\big(l(X) > l'(X)\big)

with equality iff l′=ll' = l. The Shannon assignment is uniquely competitively optimal.

ProofBound the sign function by an exponential on the integers

Step 1: A bound on the sign. On the integers, sgn⁡(t)≤2t−1\operatorname{sgn}(t) \le 2^t - 1. Check: at t=0t = 0, 0≤00 \le 0; at t=1t = 1, 1≤11 \le 1; for t≥2t \ge 2 the right side exceeds 1; for t≤−1t \le -1, −1≤2t−1-1 \le 2^t - 1. (This fails for non-integer tt, which is why dyadic integer lengths are needed.)

Step 2: Write the score difference as an expectation.

Pr⁡(l′<l)−Pr⁡(l′>l)=∑xp(x)sgn⁡(l(x)−l′(x))≤∑xp(x)(2l(x)−l′(x)−1)\Pr(l' < l) - \Pr(l' > l) = \sum_x p(x)\operatorname{sgn}\big(l(x) - l'(x)\big) \le \sum_x p(x)\big(2^{l(x) - l'(x)} - 1\big)

Step 3: Use p(x)=2−l(x)p(x) = 2^{-l(x)}.

=∑x2−l(x)(2l(x)−l′(x)−1)=∑x2−l′(x)−∑x2−l(x)=∑x2−l′(x)−1≤0= \sum_x 2^{-l(x)}\big(2^{l(x) - l'(x)} - 1\big) = \sum_x 2^{-l'(x)} - \sum_x 2^{-l(x)} = \sum_x 2^{-l'(x)} - 1 \le 0

by McMillan for l′l' (and because the dyadic Shannon code spends its Kraft budget exactly).

Step 4: Equality. Step 1 is tight only at t∈{0,1}t \in \{0, 1\}, and Step 3 only if l′l' spends its Kraft budget exactly. Together these force l′=ll' = l.

∎

CorollaryNondyadic sources

For any pp, with l(x)=⌈log⁡1p(x)⌉l(x) = \lceil \log \frac{1}{p(x)} \rceil and any other code l′l':

E sgn⁡(l(X)−l′(X)−1)≤0\mathbb{E}\, \operatorname{sgn}\big(l(X) - l'(X) - 1\big) \le 0

Allowing Shannon a one-bit handicap restores the competitive guarantee.

RemarkRobust to the scoring rule

For dyadic pp we get E(l−l′)≤0\mathbb{E}(l - l') \le 0, E sgn⁡(l−l′)≤0\mathbb{E}\, \operatorname{sgn}(l - l') \le 0, and more generally E f(l−l′)≤0\mathbb{E}\, f(l - l') \le 0 for any payoff ff with f(t)≤2t−1f(t) \le 2^t - 1 on the integers. The Shannon code is optimal under a whole family of payoff functions, not just average length.


Generating a random variable from fair coin flips

The problem. The question so far has been how many fair bits it takes to describe a sample of XX. A good compressor’s output is essentially incompressible, so its pulses behave like fair coin flips. Now turn the question around: given a stream of fair coin flips Z1,Z2,…Z_1, Z_2, \ldots, how many does it take to generate a sample of XX with distribution pp?

ExampleThe easy case

Target p=(12,14,14)p = (\frac{1}{2}, \frac{1}{4}, \frac{1}{4}) on {a,b,c}\{a, b, c\}. Read one flip: 0 means aa. Otherwise read another: 10 means bb, 11 means cc. The expected number of flips is 12(1)+14(2)+14(2)=1.5\frac{1}{2}(1) + \frac{1}{4}(2) + \frac{1}{4}(2) = 1.5, which equals H(X)H(X). By contrast, 00→a, 01→b, 10→c, 11→a produces the same distribution but always spends 2 flips.

flowchart TD
  R((start)) -->|0| A["a"]
  R -->|1| N(( ))
  N -->|0| B["b"]
  N -->|1| C["c"]

Any generation algorithm is a binary tree: the coin flips trace a path from the root, and each leaf is labelled with an output symbol. The tree must satisfy three conditions:

PropertyMeaning
CompleteEvery node is a leaf or has two children. The tree may be infinite.
Leaf probabilitiesA leaf at depth kk is reached with probability 2−k2^{-k}. The leaves labelled xx must have total probability p(x)p(x).
CostThe expected number of flips ET\mathbb{E}T is the expected depth of the tree.

LemmaExpected depth is an entropy

Let YY be the leaf reached, so a leaf yy at depth k(y)k(y) has probability 2−k(y)2^{-k(y)}. Then

ET=∑yk(y)2−k(y)=−∑y2−k(y)log⁡2−k(y)=H(Y)\mathbb{E}T = \sum_y k(y) 2^{-k(y)} = -\sum_y 2^{-k(y)} \log 2^{-k(y)} = H(Y)

TheoremYou can’t generate entropy for free

For any algorithm generating XX from fair bits,

ET≥H(X)\mathbb{E}T \ge H(X)

ProofThe output is a function of the leaf

Step 1: Label every leaf distinctly to get YY. By the lemma, ET=H(Y)\mathbb{E}T = H(Y).

Step 2: XX is a deterministic function of YY (several leaves can carry the same label). A function can’t increase entropy: H(Y)=H(Y,X)=H(X)+H(Y∣X)≥H(X)H(Y) = H(Y, X) = H(X) + H(Y \mid X) \ge H(X), using the chain rule.

Step 3: Hence ET=H(Y)≥H(X)\mathbb{E}T = H(Y) \ge H(X).

∎

IntuitionRandomness is conserved, like energy

Each fair flip carries exactly 1 bit of randomness, and the output needs H(X)H(X) bits of randomness. A machine can throw randomness away (several leaves collapsing to one symbol), but it can’t create it. This is the data processing principle run backwards: processing can’t increase information, so it can’t increase randomness either.

TheoremDyadic targets cost exactly H(X)H(X)

If pp is dyadic, the optimal algorithm uses exactly ET=H(X)\mathbb{E}T = H(X) flips.

ProofUse the Huffman tree as a generator

For dyadic pp, the Huffman code equals the Shannon code. The leaf for xx sits at depth log⁡1p(x)\log \frac{1}{p(x)}, so it is reached with probability exactly p(x)p(x). The expected depth is the expected codeword length, which is H(X)H(X) for a dyadic distribution.

∎

Non-dyadic targets: split probabilities into dyadic atoms

IntuitionBinary expansions as recipes

A tree can only make probabilities of the form 2−k2^{-k}. So split each p(x)p(x) into such atoms using its binary expansion, and give each atom its own leaf. For example, 78=12+14+18\frac{7}{8} = \frac{1}{2} + \frac{1}{4} + \frac{1}{8} needs three leaves, at depths 1, 2 and 3. Using the largest atoms possible keeps the tree shallow. The atom depths satisfy Kraft (the atoms sum to 1), so a tree with all of them always exists.

ExampleGenerating (23,13)(\frac{2}{3}, \frac{1}{3})

23=0.101010…2\frac{2}{3} = 0.101010\ldots_2 gives atoms 12,18,132,…\frac{1}{2}, \frac{1}{8}, \frac{1}{32}, \ldots for aa. 13=0.010101…2\frac{1}{3} = 0.010101\ldots_2 gives atoms 14,116,164,…\frac{1}{4}, \frac{1}{16}, \frac{1}{64}, \ldots for bb. The tree is infinite: flip until the first 0. If it lands on an odd flip, output aa; if on an even flip, output bb. In this example the expected number of flips is 2, against H(X)≈0.918H(X) \approx 0.918 bits.

TheoremWithin two flips of the entropy

The optimal algorithm satisfies

H(X)≤ET<H(X)+2H(X) \le \mathbb{E}T < H(X) + 2

ProofBound each symbol’s share of the expected depth

Step 1: Expected depth from atoms. Let YY range over the atoms. Then ET=H(Y)=∑iTi\mathbb{E}T = H(Y) = \sum_i T_i, where Ti=∑j: pi(j)>0j 2−jT_i = \sum_{j:\, p_i^{(j)} > 0} j\, 2^{-j} collects the atoms of symbol ii (an atom at depth jj contributes j2−jj 2^{-j}).

Step 2: Locate pip_i. Pick nn with 2−(n−1)>pi≥2−n2^{-(n-1)} > p_i \ge 2^{-n}, i.e. n−1<−log⁡pi≤nn - 1 < -\log p_i \le n. Then the first atom of pip_i is at depth nn, and all its atoms are at depth ≥n\ge n.

Step 3: Show Ti<−pilog⁡pi+2piT_i < -p_i \log p_i + 2p_i. Using pilog⁡pi<−(n−1)pip_i \log p_i < -(n-1)p_i and pi=∑j2−jp_i = \sum_j 2^{-j} over its atoms,

Ti+pilog⁡pi−2pi<Ti−(n+1)pi=∑j: pi(j)>0(j−n−1)2−jT_i + p_i \log p_i - 2p_i < T_i - (n+1)p_i = \sum_{j:\, p_i^{(j)} > 0} (j - n - 1) 2^{-j}

The depth-nn atom contributes −2−n-2^{-n}, depth n+1n+1 contributes 0, and the rest contribute at most ∑k≥1k 2−(k+n+1)=2−(n+1)⋅2=2−n\sum_{k \ge 1} k\, 2^{-(k+n+1)} = 2^{-(n+1)} \cdot 2 = 2^{-n}. So the total is ≤0\le 0.

Step 4: Sum over symbols. ET=∑iTi<−∑ipilog⁡pi+2∑ipi=H(X)+2\mathbb{E}T = \sum_i T_i < -\sum_i p_i \log p_i + 2\sum_i p_i = H(X) + 2.

∎

NoteOptimality not proved here

Cover & Thomas argue that the largest-atoms-first procedure gives a tree of minimum expected depth, but don’t prove it formally. The theorem above only bounds how well it does.

ImportantCompression and generation are two sides of one coin

Entropy is both the number of fair bits needed to describe XX (H≤L∗<H+1H \le L^* < H + 1) and the number of fair bits needed to produce it (H≤ET<H+2H \le \mathbb{E}T < H + 2). A good compressor turns samples of XX into fair bits, and a good generator turns fair bits back into samples of XX. The two operations meet at the same limit.


Quick reference

ObjectStatementReads as
Expected lengthL(C)=∑p(x)l(x)L(C) = \sum p(x) l(x)Average pulses per keystroke.
Hierarchyinstantaneous ⊂\subset UD ⊂\subset nonsingular ⊂\subset allInstantaneous decodes each codeword as soon as it ends.
Kraftprefix code   ⟺  ∑D−li≤1\iff \sum D^{-l_i} \le 1A fixed budget of tree space.
McMillanuniquely decodable ⇒∑D−li≤1\Rightarrow \sum D^{-l_i} \le 1Look-ahead buys no extra lengths.
Entropy boundL≥HD(X)L \ge H_D(X), equality iff pp is DD-adicNo uniquely decodable code beats the entropy.
Gap decompositionL−H=D(p∥r)+log⁡D1cL - H = D(p \Vert r) + \log_D \frac{1}{c}Model mismatch plus unused tree space.
Shannon codel=⌈log⁡1p⌉l = \lceil \log \frac{1}{p} \rceil, H≤L<H+1H \le L < H + 1Round up the surprise.
Block codingH≤Ln<H+1nH \le L_n < H + \frac{1}{n}Spread the rounding loss over nn keystrokes.
Stationary sourceLn∗→H(X)L_n^* \rightarrow H(\mathcal{X})The entropy rate is the compression limit.
Wrong codeH(p)+D(p∥q)≤Epl<H(p)+D(p∥q)+1H(p) + D(p \Vert q) \le \mathbb{E}_p l < H(p) + D(p\Vert q) + 1Believing qq costs D(p∥q)D(p\Vert q) extra bits.
HuffmanMerge the two least likely symbols repeatedlyExactly optimal; greedy is globally optimal.
SFETruncate Fˉ(x)\bar F(x) to ⌈log⁡1p⌉+1\lceil \log \frac{1}{p} \rceil + 1 bitsWithin 2 bits; the basis of arithmetic coding.
CompetitivePr⁡(l≥l′+c)≤2−(c−1)\Pr(l \ge l' + c) \le 2^{-(c-1)}Rivals rarely beat Shannon by much.
Dyadic competitivePr⁡(l<l′)≥Pr⁡(l>l′)\Pr(l < l') \ge \Pr(l > l')Shannon wins the head-to-head game.
GenerationH≤ET<H+2H \le \mathbb{E}T < H + 2, =H= H if dyadicEntropy is also the cost of simulating XX.

Constants and identities to keep to hand:

  • Kraft sum of a prefix code: ∑D−li≤1\sum D^{-l_i} \le 1. Spending it exactly (=1= 1) is necessary for L=HL = H.
  • Ideal length l∗=log⁡1pl^* = \log \frac{1}{p}. Shannon pays at most 1 extra symbol; SFE pays at most 2.
  • Overheads: Shannon/Huffman <1< 1 bit, Fano ≤2\le 2 bits, SFE <2< 2 bits, generation <2< 2 flips. Blocks of nn divide the per-symbol overhead by nn.
  • DD-ary Huffman needs 1+k(D−1)1 + k(D-1) symbols. Pad with zero-probability dummies.
  • sgn⁡(t)≤2t−1\operatorname{sgn}(t) \le 2^t - 1 holds on the integers only.
  • A function can’t increase entropy: H(f(Y))≤H(Y)H(f(Y)) \le H(Y).

References

← All notes