Data Compression and Source Coding
- 01Code hierarchywhich codes a stream of keystrokes can be decoded from
- 02Kraft inequalityprefix codes share a fixed budget of tree space
- 03Entropy boundno code averages fewer than symbols per keystroke
- 04Shannon codesround up the surprise to get within one bit of
- 05Block codingspreading the rounding loss over keystrokes reaches the entropy rate
- 06Wrong codebookdesigning for instead of costs extra bits
- 07McMillan inequalitylook-ahead decoding buys no shorter codes
- 08Huffman codesgreedily merging the two rarest symbols gives an exactly optimal code
Motivation: from typical sets to actual codebooks
The AEP gave the telecom company a code costing about bits per tape. That code has three problems that make it unusable on a real telegraph line:
| Problem with the typical-set code | Why it matters on the wire |
|---|---|
| It only works for huge blocks. Its guarantees kick in “for 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 of size . | Nobody can enumerate for . 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 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 (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 for a random variable is a mapping from , the range of , to , the set of finite-length strings from a -ary alphabet . is the codeword for , and is its length.
| Component | Detail |
|---|---|
| Signature | |
| Domain | The operator’s alphabet: each key they can press. |
| Codomain | Finite strings of pulses. For a binary wire, (on/off). For a wire with three distinguishable voltage levels, . |
| Example | , is a binary code for . |
DefinitionExpected length
This is what the telecom actually pays per keystroke on average.
ExampleA code that hits the entropy exactly
| 1 | 0 | |
| 2 | 10 | |
| 3 | 110 | |
| 4 | 111 |
bits and 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 bits while
bits. Here . We will see
exactly why: the probabilities are not powers of .
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
is nonsingular if distinct symbols get distinct codewords: .
DefinitionExtension of a code
The extension maps strings of symbols to strings of code symbols by concatenation:
For example, if and , then .
DefinitionUniquely decodable code
is uniquely decodable if its extension 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
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
| Singular | Nonsingular, not UD | UD, not instantaneous | Instantaneous | |
|---|---|---|---|---|
| 1 | 0 | 0 | 10 | 0 |
| 2 | 0 | 010 | 00 | 10 |
| 3 | 0 | 01 | 11 | 110 |
| 4 | 0 | 10 | 110 | 111 |
- Nonsingular, not UD: the stream
010could be2, or1 4, or3 1. - UD, not instantaneous: if the stream starts
00or10, decode at once. If it starts11, count the run of 0s that follows. An odd run means the first codeword was110(symbol 4); an even run means it was11(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 are achievable by a prefix code.
TheoremKraft inequality
For any instantaneous code over an alphabet of size , the codeword lengths must satisfy
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 -ary tree, with
the root at the top and each branch one pulse. A codeword of length
claims its node and everything below it, which is a fraction 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 -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 be the longest codeword length. A codeword at depth has exactly descendants at depth .
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 nodes at depth , so
Dividing by gives .
Step 4 (converse): Greedy construction. Given lengths satisfying the inequality, sort them so . Label the first available node (lexicographically) at depth as codeword 1 and delete its descendants. Then label the first remaining node at depth , 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, . Conversely, any satisfying this can be realized by a prefix code.
ProofCodewords as subintervals of
The tree proof needs a deepest level, which an infinite code doesn’t have. Use intervals instead.
Step 1: Codeword to number. Read codeword as the -ary fraction .
Step 2: Number to interval. The codeword “owns” the interval : every real number whose -ary expansion begins with that codeword. Its length is .
Step 3: Prefix-free means disjoint. Two intervals overlap exactly when one codeword is a prefix of the other. Disjoint subintervals of have total length at most 1, so .
Step 4 (converse). Sort the lengths increasingly and assign intervals in
order from the low end of . For binary lengths this
gives , i.e. codewords
0, 10, ….
∎
Optimal codes and the entropy bound
The problem. Now we can state the engineer’s task as an optimization:
DerivationRelax the integers and use a Lagrange multiplier
Ignore the integer constraint and assume the Kraft budget is spent exactly. Minimize
Differentiating, , so . Summing over and using gives . Hence
IntuitionThe entropy reappears as a length
The relaxed optimum assigns each symbol exactly its surprise, , 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 -ary code for satisfies
with equality if and only if for all .
ProofWrite the gap as a relative entropy plus a wasted-budget term
Step 1: Write the gap.
Step 2: Turn the lengths into a distribution. Let (the Kraft sum) and , a genuine pmf. Then , and
Step 3: Both terms are nonnegative. by the information inequality, and because by Kraft. So .
Step 4: Equality. Both terms must vanish: (the whole Kraft budget is spent) and , i.e. .
∎
IntuitionThe two ways a code wastes pulses
The proof splits the excess cost into two separate physical failures:
| Term | Failure |
|---|---|
| The lengths implicitly assume the operator’s distribution is . Reality is . This is the wrong-codebook penalty, now with integer lengths. | |
| Unclaimed tree space. Some codewords could have been shortened without breaking the prefix property. |
Definition-adic distribution
A distribution is -adic if every probability is for some integer . So is achievable iff the distribution is -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 -adic distribution closest to in relative entropy, use its exponents as lengths, and build the code with the greedy Kraft construction. The search for the closest -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 is usually not an integer. The simplest fix is to round up.
DefinitionShannon code
Assign lengths
These satisfy Kraft, since , so the greedy construction turns them into a prefix code.
TheoremOptimal expected length is within one symbol of entropy
Let be the expected length of an optimal -ary code for . Then
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:
Step 2: Average. Multiply by and sum: .
Step 3: Sandwich. The optimal code is no worse than the Shannon code () and no better than the entropy ( 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 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 keystrokes as one symbol from . The one-bit rounding loss is paid once per block, so it costs only bits per keystroke.
TheoremBlock coding approaches the entropy
Encode i.i.d. keystrokes as one supersymbol, and let be the expected length per keystroke (binary, ). Then
ProofApply the one-bit bound to the supersymbol
The bound holds for any random variable, including the block :
For i.i.d. keystrokes . Divide by .
∎
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
If the process is stationary, then , 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 bits per keystroke, and no fewer.
The price of the wrong codebook
The problem. The company never knows the operator’s true distribution . It designs from its best estimate , 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 , , has expected length under the true distribution satisfying
ProofExpand the ceiling and split the logarithm
Upper bound:
Insert inside the logarithm and split:
Lower bound: the same computation with in place of .
∎
IntuitionRelative entropy, now earned
In the first note we motivated as wasted bits, using idealized non-integer codeword lengths. This theorem shows the story survives real integer codes: believing when the truth is costs exactly 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 -ary code satisfy
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 -th power
Step 1: Pass to the -th extension. If is uniquely decodable, its -th extension (all concatenations of codewords) is nonsingular: distinct -symbol messages produce distinct pulse strings. The length of a concatenation is the sum of the lengths, .
Step 2: The -th power of the Kraft sum is a sum over messages.
Step 3: Group the messages by encoded length. Let be the number of -symbol messages whose encoding has length . Lengths range from 1 to :
Step 4: Unique decodability caps . There are only pulse strings of length , and nonsingularity says no two messages share one. So , and
Step 5: Take -th roots and let . for every . The right side grows only linearly inside a -th root, so it tends to 1. Hence .
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 exceeded 1, then would grow exponentially in . But unique decodability caps the number of -symbol messages that fit in each pulse length, so can grow at most linearly in . Exponential growth can’t stay below linear growth, so . 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 . The fix: every finite subset of a uniquely decodable code is uniquely decodable, so every partial sum is , 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 , 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 .
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 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)
- Take the two least probable symbols.
- Merge them into one symbol whose probability is their sum.
- Repeat until one symbol remains.
- Read the codewords back down the merge tree: each merge splits a codeword into “append 0” and “append 1”.
ExampleA binary Huffman code
with probabilities .
| Merge | Combined | Remaining probabilities |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 | everything | — |
| Codeword | Length | ||
|---|---|---|---|
| 1 | 0.25 | 01 | 2 |
| 2 | 0.25 | 10 | 2 |
| 3 | 0.20 | 11 | 2 |
| 4 | 0.15 | 000 | 3 |
| 5 | 0.15 | 001 | 3 |
Expected length: bits. For comparison, 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, : merge the three least likely symbols at each
step. Merging gives , and the final merge is
. The codewords are 1, 2 for symbols 1 and 2, and
00, 01, 02 for symbols 3–5. ternary digits.
Warning-ary Huffman needs dummy symbols
Each -ary merge reduces the symbol count by . To end with exactly one symbol, the starting count must be for some number of merges . If it isn’t, pad with dummy symbols of probability 0. They occupy the deepest leaves and cost nothing. For example, 6 symbols with need one dummy, since .
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
In the binary Huffman example, the optimal first question is “Is ?” (the first bit). The second question need not wait for the answer: “Is ?” determines the second bit independently.
RemarkWeighted codewords
Huffman’s algorithm never uses . Run on any nonnegative weights , it minimizes the weighted sum .
RemarkSlice (alphabetic) codes
Huffman questions have the form “Is ?” for arbitrary sets .
Suppose only slice questions “Is ?” are allowed, with symbols
ordered so . 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 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 and . Shannon lengths are and bits. The optimal code uses 1 bit for each.
Warning…but optimal codes can be longer than Shannon on some symbols
Distribution . Depending on tie-breaking, Huffman gives lengths or , both with expected length 2. In the second, the third symbol gets 3 bits, more than its Shannon length . 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 ).
RemarkFano codes
Fano’s suboptimal scheme sorts the probabilities, splits them at the index 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 .
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 . There exists an optimal instantaneous code such that:
- lengths are ordered inversely to probabilities: ;
- the two longest codewords have the same length;
- 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 .
Property 1 (swap). Suppose . Swap the codewords of and to get :
is optimal, so this is . Since , we need .
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 since they all have the same length, so that the two least likely symbols sit on a sibling pair.
∎
DefinitionHuffman reduction
For with , the Huffman reduction is the -symbol distribution
TheoremHuffman coding is optimal
If is a Huffman code and is any uniquely decodable code for the same distribution, then .
ProofExpand an optimal reduced code, condense an optimal full code, and compare
Let and be the optimal expected lengths for and its reduction .
Step 1: Expand. Take an optimal code for . Split the codeword of the
merged symbol by appending 0 (for ) and 1 (for
). Only those two symbols get one bit longer, so the resulting code for
has
Step 2: Condense. Take a canonical optimal code for . By the lemma, symbols and are siblings. Merge them into their parent node, which shortens both by one bit. The resulting code for has
Step 3: Add the two equations.
Each bracket is , because no code beats the optimum. Two nonnegative numbers summing to 0 are both 0. So : 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 . 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 , 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 -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 with all , and . Define the midpoint of the step at :
IntuitionA symbol is a stretch of the unit interval
The CDF is a staircase. Symbol owns the vertical step , of height , and these steps tile . Any number inside ‘s step identifies . 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 in binary and truncate it to
bits. That truncation, , is the codeword.
ProofThe code identifies and is prefix-free
Step 1: Truncation stays in the step. Truncating to bits moves the number down by less than . With the chosen length,
The midpoint sits above the bottom of the step, so the truncated value still lies inside ‘s step.
Step 2: Codeword as interval. Read the codeword as the interval . 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 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
ExampleA dyadic source
| in binary | Codeword | |||||
|---|---|---|---|---|---|---|
| 1 | 0.25 | 0.25 | 0.125 | 0.001 | 3 | 001 |
| 2 | 0.5 | 0.75 | 0.5 | 0.10 | 2 | 10 |
| 3 | 0.125 | 0.875 | 0.8125 | 0.1101 | 4 | 1101 |
| 4 | 0.125 | 1.0 | 0.9375 | 0.1111 | 4 | 1111 |
bits, against 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:
| in binary | Codeword | ||||
|---|---|---|---|---|---|
| 1 | 0.25 | 0.125 | 0.001 | 3 | 001 |
| 2 | 0.25 | 0.375 | 0.011 | 3 | 011 |
| 3 | 0.20 | 0.6 | 0.1001… | 4 | 1001 |
| 4 | 0.15 | 0.775 | 0.1100011… | 4 | 1100 |
| 5 | 0.15 | 0.925 | 0.1110110… | 4 | 1110 |
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 keystrokes directly with Huffman needs probabilities for all 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 . 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 . A symbol is drawn, and the player with the shorter codeword wins , the other loses , 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 does have one.
TheoremA rival rarely wins by much
Let be Shannon code lengths and the lengths of any uniquely decodable code. Then for every ,
For example, the chance that a rival’s codeword is at least 5 bits shorter than the Shannon codeword is at most .
ProofConvert “much shorter” into “improbable”, then apply Kraft
Step 1: Remove the ceiling. , so
Step 2: Bound the probability of those symbols. Sum over the symbols where the condition holds, and use the condition itself as the bound on each term:
since by McMillan.
∎
IntuitionShort codewords must be rationed
A rival can beat Shannon by bits only on symbols that are rare enough, . 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 .
TheoremFor dyadic sources, Shannon wins the head-to-head game
If is dyadic and (an integer), then for any other uniquely decodable code ,
with equality iff . 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, . Check: at , ; at , ; for the right side exceeds 1; for , . (This fails for non-integer , which is why dyadic integer lengths are needed.)
Step 2: Write the score difference as an expectation.
Step 3: Use .
by McMillan for (and because the dyadic Shannon code spends its Kraft budget exactly).
Step 4: Equality. Step 1 is tight only at , and Step 3 only if spends its Kraft budget exactly. Together these force .
∎
CorollaryNondyadic sources
For any , with and any other code :
Allowing Shannon a one-bit handicap restores the competitive guarantee.
RemarkRobust to the scoring rule
For dyadic we get , , and more generally for any payoff with 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 . 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 , how many does it take to generate a sample of with distribution ?
ExampleThe easy case
Target on . Read
one flip: 0 means . Otherwise read another: 10 means , 11 means
. The expected number of flips is
, which equals
. 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:
| Property | Meaning |
|---|---|
| Complete | Every node is a leaf or has two children. The tree may be infinite. |
| Leaf probabilities | A leaf at depth is reached with probability . The leaves labelled must have total probability . |
| Cost | The expected number of flips is the expected depth of the tree. |
LemmaExpected depth is an entropy
Let be the leaf reached, so a leaf at depth has probability . Then
TheoremYou can’t generate entropy for free
For any algorithm generating from fair bits,
ProofThe output is a function of the leaf
Step 1: Label every leaf distinctly to get . By the lemma, .
Step 2: is a deterministic function of (several leaves can carry the same label). A function can’t increase entropy: , using the chain rule.
Step 3: Hence .
∎
IntuitionRandomness is conserved, like energy
Each fair flip carries exactly 1 bit of randomness, and the output needs 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
If is dyadic, the optimal algorithm uses exactly flips.
ProofUse the Huffman tree as a generator
For dyadic , the Huffman code equals the Shannon code. The leaf for sits at depth , so it is reached with probability exactly . The expected depth is the expected codeword length, which is 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 . So split each into such atoms using its binary expansion, and give each atom its own leaf. For example, 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
gives atoms
for .
gives atoms
for .
The tree is infinite: flip until the first 0. If it lands on an odd flip,
output ; if on an even flip, output . In this example the expected
number of flips is 2, against bits.
TheoremWithin two flips of the entropy
The optimal algorithm satisfies
ProofBound each symbol’s share of the expected depth
Step 1: Expected depth from atoms. Let range over the atoms. Then , where collects the atoms of symbol (an atom at depth contributes ).
Step 2: Locate . Pick with , i.e. . Then the first atom of is at depth , and all its atoms are at depth .
Step 3: Show . Using and over its atoms,
The depth- atom contributes , depth contributes 0, and the rest contribute at most . So the total is .
Step 4: Sum over symbols. .
∎
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 () and the number of fair bits needed to produce it (). A good compressor turns samples of into fair bits, and a good generator turns fair bits back into samples of . The two operations meet at the same limit.
Quick reference
| Object | Statement | Reads as |
|---|---|---|
| Expected length | Average pulses per keystroke. | |
| Hierarchy | instantaneous UD nonsingular all | Instantaneous decodes each codeword as soon as it ends. |
| Kraft | prefix code | A fixed budget of tree space. |
| McMillan | uniquely decodable | Look-ahead buys no extra lengths. |
| Entropy bound | , equality iff is -adic | No uniquely decodable code beats the entropy. |
| Gap decomposition | Model mismatch plus unused tree space. | |
| Shannon code | , | Round up the surprise. |
| Block coding | Spread the rounding loss over keystrokes. | |
| Stationary source | The entropy rate is the compression limit. | |
| Wrong code | Believing costs extra bits. | |
| Huffman | Merge the two least likely symbols repeatedly | Exactly optimal; greedy is globally optimal. |
| SFE | Truncate to bits | Within 2 bits; the basis of arithmetic coding. |
| Competitive | Rivals rarely beat Shannon by much. | |
| Dyadic competitive | Shannon wins the head-to-head game. | |
| Generation | , if dyadic | Entropy is also the cost of simulating . |
Constants and identities to keep to hand:
- Kraft sum of a prefix code: . Spending it exactly () is necessary for .
- Ideal length . Shannon pays at most 1 extra symbol; SFE pays at most 2.
- Overheads: Shannon/Huffman bit, Fano bits, SFE bits, generation flips. Blocks of divide the per-symbol overhead by .
- -ary Huffman needs symbols. Pad with zero-probability dummies.
- holds on the integers only.
- A function can’t increase entropy: .
References
- Cover & Thomas, Elements of Information Theory — Chapter 5