Shannon's Source Coding Theorem: Optimal Lossless Rates and the Kraft Inequality
Anchor (Master): Cover & Thomas 2006 Elements of Information Theory 2e (Wiley) §5.1-5.6; Csiszar & Korner 2011 Information Theory: Coding Theorems for Discrete Memoryless Systems 2e (Cambridge) §1.1-1.3; Shannon 1948 A Mathematical Theory of Communication §§7-9 (the source coding theorem, Kraft inequality, and block coding)
Intuition Beginner
You have four messages to send: A, B, C, and D. Message A happens half the time, B a quarter of the time, and C and D each one-eighth of the time. You want to encode each message as a string of 0s and 1s so that you can send the shortest possible string on average.
A naive encoding uses two bits for every message: A = 00, B = 01, C = 10, D = 11. The average length is 2 bits. But A is much more common than D. What if you gave A a shorter code? Say A = 0, B = 10, C = 110, D = 111. Now the average length is bits. You saved 0.25 bits per message.
This code has a special property: no codeword is a prefix of another. If you see a 0, you know it is A immediately — no other codeword starts with 0. This is called a prefix-free code, and it means you can decode messages as they arrive without waiting for a delimiter.
Shannon's source coding theorem says that the entropy of the source sets the floor for how short any prefix-free code can be. The entropy of this source is bits, and our code achieves exactly that. We matched the limit. In general, the best you can do is between and bits per symbol — and by encoding blocks of symbols together, you can get arbitrarily close to .
The engine behind all of this is the Kraft inequality. It is a simple constraint on the lengths of a prefix-free code: if your codeword lengths are , then the sum must be at most 1. This single inequality is both necessary (every prefix-free code satisfies it) and sufficient (any set of lengths satisfying it can be realised as a prefix-free code). It is the bridge between the geometry of binary trees and the arithmetic of compression.
Visual Beginner
| Symbol | Probability | Codeword | Length | Contribution to average length |
|---|---|---|---|---|
| A | 0.500 | 0 | 1 | |
| B | 0.250 | 10 | 2 | |
| C | 0.125 | 110 | 3 | |
| D | 0.125 | 111 | 3 | |
| Total | 1.000 | 1.750 bits |
Figure: a binary tree with root at the top. The left branch from the root is labelled 0 and leads to leaf A at depth 1. The right branch is labelled 1; its left child is labelled 0 and leads to leaf B at depth 2. The right child of that node branches again: left to C (code 110, depth 3) and right to D (code 111, depth 3). Each leaf is labelled with its symbol and probability. The tree has no internal node that is also a leaf — this is the prefix-free property visualised.
The Kraft sum for this code: . The sum equals 1 exactly, which means no shorter code exists for these lengths — the code tree is "full."
Worked example Beginner
Consider a source with four symbols and probabilities , , , .
Step 1: Compute the entropy. The entropy measures the average information content. For each symbol, the information is .
- A: bit
- B: bits
- C: bits
- D: bits
The entropy is the probability-weighted average:
Step 2: Build a code. Assign codewords using the Shannon-Fano idea: give symbol a codeword of length . For our source, the ideal lengths are exactly 1, 2, 3, 3 — all integers already. We assign A = 0, B = 10, C = 110, D = 111.
Step 3: Verify the Kraft inequality. The sum is . The inequality is satisfied with equality, so these lengths are achievable as a prefix-free code.
Step 4: Compute the expected length. The average codeword length is bits. This equals the entropy bits exactly. The source coding theorem says this is the best possible — no prefix-free code can do better.
Check your understanding Beginner
Formal definition Intermediate+
Let be a finite source alphabet with probability distribution .
Definition (Binary code). A code is a mapping assigning to each source symbol a finite binary string called a codeword. The length is the number of bits in the codeword for .
Definition (Prefix-free code). A code is prefix-free (or instantaneous) if no codeword is a prefix of any other codeword: for all , is not a prefix of .
Definition (Expected length). The expected length of a code for source is:
Definition (Optimal code). Define where the minimum is over all prefix-free codes for .
Counterexamples to common slips
Prefix-free is not the same as uniquely decodable. A uniquely decodable code allows unambiguous decoding of concatenated codewords but may not be instantaneous. Every prefix-free code is uniquely decodable, but not vice versa (e.g., the code is uniquely decodable but not prefix-free — you can always parse by reading from the right, but you cannot decode left-to-right without lookahead).
The Kraft inequality is about lengths, not specific codewords. The inequality constrains the set of lengths , not the particular assignment of binary strings. Two different prefix-free codes with the same length vector satisfy the same Kraft sum.
is defined over prefix-free codes, not all codes. If you allow non-prefix-free codes, you can sometimes achieve shorter expected length, but the resulting code may not be practically decodable. The restriction to prefix-free codes is without loss of optimality for expected length, because McMillan's theorem (below) shows that any uniquely decodable code has lengths satisfying Kraft.
Key theorem with proof Intermediate+
Theorem (Kraft inequality — necessity). If is a prefix-free binary code with codeword lengths , then
Proof. Let . Consider the full binary tree of depth . This tree has leaf nodes. Each codeword of length corresponds to a node at depth in the tree. Because the code is prefix-free, no codeword node is an ancestor of another. The subtree rooted at the codeword node for contains leaves, and these subtrees are disjoint. Therefore:
since the total number of leaves in all disjoint subtrees cannot exceed the total number of leaves in the tree. Dividing both sides by yields the result.
Theorem (Kraft inequality — sufficiency). Given lengths satisfying , there exists a prefix-free binary code with these exact lengths.
Proof. Construct the code by traversing a binary tree from the root. Sort the lengths so . At each step , assign the leftmost available node at depth as the codeword for , and remove its entire subtree from future consideration.
We must verify that a node is always available at step . At depth , the full tree has nodes. After assigning the first codewords, the number of nodes removed from depth is at most (each earlier codeword of length blocks nodes at depth ). The number of remaining available nodes is:
where the inequality uses , so . Thus at least one node remains.
Theorem (McMillan). The Kraft inequality holds for the codeword lengths of any uniquely decodable code, not just prefix-free codes. Consequently, the set of achievable length vectors is the same for uniquely decodable codes and prefix-free codes.
Proof sketch. For a -ary alphabet, let be uniquely decodable with lengths . Consider the -th power of the code (the code applied to -tuples of source symbols). This extended code has length sum . Since the extended code must also be uniquely decodable, its lengths must be at least 1, giving for each . Taking -th roots and letting forces .
Theorem (Shannon source coding theorem — one-shot). Let be a discrete random variable with entropy . Then the minimum expected codeword length over all prefix-free binary codes satisfies:
Proof of lower bound. For any prefix-free code with lengths , define where by Kraft. Then is a probability distribution. The expected length is:
Since , we have . By Gibbs' inequality, . Therefore:
Proof of upper bound (Shannon-Fano coding). Assign codeword length . First, verify Kraft:
So a prefix-free code with these lengths exists. The expected length is:
Theorem (Source coding theorem — tight version). Let be i.i.d. draws from . Define as the minimum expected codeword length per symbol for blocks of size (i.e., the optimal code for has expected length ). Then:
Proof. Apply the one-shot theorem to the block random variable , which has entropy by the chain rule and independence. The one-shot bounds give , so . As , the upper bound converges to .
Bridge. The source coding theorem builds toward the channel coding theorem 46.03.01 where entropy reappears as the capacity limit, and this time with a noisy channel rather than a clean wire; it appears again in rate-distortion theory 46.04.01 where the lossy version replaces the entropy with the rate-distortion function , and the foundational reason entropy governs compression is that the Kraft inequality ties every binary tree to the simplex of distributions, making the unique exponent that satisfies both the counting bound and the achievability construction. This is exactly the AEP 46.02.01 made operational: the typical set of size is the object being indexed, and the Kraft inequality guarantees that the index fits in bits. The central insight is that prefix-free codes, uniquely decodable codes, and block-optimal codes all live in the same length-constrained world governed by .
Exercises Intermediate+
Lean formalization Intermediate+
Mathlib does not define prefix-free codes, the Kraft inequality, or the source coding theorem. The PMF type for probability mass functions exists, and entropy is definable as a functional on PMF, but the connection to coding theory is absent. A Codex.InformationTheory.SourceCoding module would need:
- A
PrefixCodestructure parametrised by an alphabet and a list of codeword lengths. - A proof that
Sum (2 ^ (-l_i)) <= 1is necessary and sufficient for the existence of a prefix-free code (Kraft inequality, both directions). - McMillan's theorem: uniquely decodable codes satisfy Kraft.
- The source coding theorem bounds:
H(X) <= L*andL* < H(X) + 1. - The tight version:
L_n^* / n -> H(X).
Items 1-3 are combinatorial and should be approachable with Mathlib's existing List and Finset machinery. Item 4 requires the entropy functional from 46.01.01, which is itself not yet in Mathlib. Item 5 needs the chain rule (also absent). The foundational gap is the missing PrefixCode structure; once it ships along with Kraft, the source coding theorem follows from Gibbs' inequality. This unit ships without a Lean module.
Advanced results Master
Optimality and Huffman coding
The source coding theorem gives bounds on but does not construct the optimal code. Huffman coding (covered in 46.02.03) is a greedy algorithm that achieves . The algorithm repeatedly merges the two lowest-probability symbols, building the code tree bottom-up. It produces the minimum expected length among all prefix-free codes for the given distribution.
The gap between Huffman's and the entropy can be bounded more precisely. For a source with symbols:
where is the largest symbol probability. This refinement replaces the generic bound from Shannon-Fano coding with a distribution-dependent quantity that is often much smaller.
Competitive optimality of Shannon-Fano coding
While Shannon-Fano coding is not optimal (Huffman is), it has a remarkable competitive property. For any symbol :
This means the Shannon-Fano codeword for each individual symbol is at most 1 bit longer than the "ideal" length . No other code construction has this pointwise guarantee — Huffman optimises the expected length but can assign a very long codeword to a low-probability symbol that exceeds by more than 1.
The -ary Kraft inequality
The entire theory generalises from binary codes to codes over a -symbol alphabet (). The Kraft inequality becomes:
and the source coding theorem generalises to , where is the entropy in -ary units. The proof is identical in structure; the tree becomes -ary and the counting argument uses leaves.
Competitive optimality of the Shannon code
Shannon (1948) proved a stronger result than the expected-length bound. Consider coding a single symbol using the Shannon code versus any other prefix-free code . Define the excess length . Shannon showed that:
This means the Shannon code is unlikely to waste many bits relative to any competing code. The proof uses the Kraft inequality on : the set of symbols where has total probability at most because the Shannon lengths satisfy .
Weak typicality and the operational source coding theorem
The AEP 46.02.01 gives a direct operational proof of the source coding theorem. For i.i.d. draws , the typical set satisfies:
- (cardinality bound).
- for large (probability bound).
Index the typical set with bits and use one extra bit to flag whether the sequence is typical. If typical, send the index. If atypical, send the raw sequence (costing at most bits). The expected rate is:
which converges to as and . This gives an explicit coding scheme achieving the entropy limit, complementing the Kraft-based bound with a constructive achievability proof.
Synthesis. The Kraft inequality is the load-bearing constraint that connects the geometry of binary trees to the probability simplex — every prefix-free code satisfies and every such length vector can be constructed; the source coding theorem builds toward the channel coding theorem 46.03.01 where capacity replaces entropy as the operational limit; the central insight is that entropy is not merely a measure of uncertainty but the exact compression rate achievable in the limit of long blocks; this is exactly the AEP 46.02.01 made constructive, since the typical set of size is the object being indexed; McMillan's theorem generalises the foundational reason why restricting to prefix-free codes is without loss — uniquely decodable codes satisfy the same length constraint; and the block-coding argument puts these together by showing , tightening the one-shot gap to zero.
Full proof set Master
Proposition (Lower bound via Gibbs). For any prefix-free code with expected length for source , .
Proof. Define the distribution where . Then:
since implies , and by Gibbs' inequality.
Proposition (Tight convergence rate). For a source with symbols, the Shannon-Fano code achieves where .
Proof. The gap is where denotes the fractional part of . Each fractional part is in , and the sum of fractional parts weighted by is at most because at least one symbol has an integer (namely the most probable symbol, whose fractional part contributes zero or near-zero). More precisely, , and since the largest weight is multiplied by a fractional part less than 1, the total is bounded by ; the exact bound follows from noting that the sum of all fractional parts is less than 1 by the integral part of Kraft.
Proposition (Source coding with side information). If the encoder and decoder both observe a correlated random variable , the minimum expected length for encoding given satisfies .
Proof. Condition on . For each value , the conditional distribution has entropy . Apply the source coding theorem to each conditional code: the optimal prefix-free code for has expected length satisfying . The unconditional expected length is . Taking the convex combination of the per- bounds gives .
Connections Master
46.01.01— Entropy is the central quantity in the source coding theorem; is both the lower bound on any code's expected length and the asymptotic limit achievable by block coding. The chain rule from this unit feeds the block-coding argument via .46.02.01— The AEP identifies the typical set of size , which is the set any efficient code must index; the source coding theorem makes this operational by showing bits suffice.46.01.02— The redundancy of any code equals the KL divergence where , connecting coding overhead directly to relative entropy.46.03.01— The channel coding theorem is the dual: source coding compresses to bits per symbol, channel coding transmits reliably at bits per channel use. The Kraft inequality reappears in the analysis of random coding error exponents.46.02.03— Huffman coding is the greedy algorithm that achieves exactly; the source coding theorem provides the entropy benchmark that Huffman matches.37.02.01— The law of large numbers underpins the AEP, which drives the tight version of the source coding theorem ().
Historical & philosophical context Master
Shannon introduced the source coding theorem in his 1948 paper "A Mathematical Theory of Communication" (Bell System Technical Journal 27, 379-423 and 623-656). Section 7 of the paper argues that the output of a discrete information source can be encoded at a rate equal to the source entropy. Shannon's construction assigns codeword lengths proportional to , an idea now called Shannon-Fano coding (Fano independently developed it in his 1949 technical report at MIT, "The Transmission of Information").
The Kraft inequality was introduced by Leonard G. Kraft Jr. in his 1949 MIT master's thesis "A Device for Quantizing, Grouping, and Coding Amplitude-Modulated Pulses," where he proved that is necessary and sufficient for the existence of a prefix-free code. McMillan (1956, "Two Inequalities Implied by Unique Decipherability," IRE Transactions on Information Theory 2(4), 115-116) extended the necessity direction to all uniquely decodable codes, showing that the prefix-free restriction is without loss of generality for the achievable length vectors. The combined result — Kraft for necessity, McMillan for the extension — is sometimes called the Kraft-McMillan inequality.
The philosophical significance is that entropy is not merely a measure of uncertainty but an operational quantity: it tells you the exact number of bits needed to describe a random variable without loss. Shannon's insight was that information could be quantified independently of its meaning, and the source coding theorem is the primary operationalisation of that insight. Huffman (1952, "A Method for the Construction of Minimum-Redundancy Codes," Proceedings of the IRE 40(9), 1098-1101) provided the optimal greedy construction, completing the practical side of the theory.
Bibliography Master
@article{shannon1948,
author = {Shannon, C. E.},
title = {A Mathematical Theory of Communication},
journal = {Bell System Technical Journal},
volume = {27},
pages = {379--423 and 623--656},
year = {1948},
}
@book{cover-thomas2006,
author = {Cover, T. M. and Thomas, J. A.},
title = {Elements of Information Theory},
edition = {2nd},
publisher = {Wiley},
year = {2006},
}
@book{csiszar-korner2011,
author = {Csisz{\'a}r, I. and K{\"o}rner, J.},
title = {Information Theory: Coding Theorems for Discrete Memoryless Systems},
edition = {2nd},
publisher = {Cambridge University Press},
year = {2011},
}
@mastersthesis{kraft1949,
author = {Kraft, L. G.},
title = {A Device for Quantizing, Grouping, and Coding Amplitude-Modulated Pulses},
school = {Massachusetts Institute of Technology},
year = {1949},
}
@article{mcmillan1956,
author = {McMillan, B.},
title = {Two Inequalities Implied by Unique Decipherability},
journal = {IRE Transactions on Information Theory},
volume = {2},
number = {4},
pages = {115--116},
year = {1956},
}
@techreport{fano1949,
author = {Fano, R. M.},
title = {The Transmission of Information},
institution = {MIT Research Laboratory of Electronics},
year = {1949},
number = {Technical Report No. 65},
}
@article{huffman1952,
author = {Huffman, D. A.},
title = {A Method for the Construction of Minimum-Redundancy Codes},
journal = {Proceedings of the IRE},
volume = {40},
number = {9},
pages = {1098--1101},
year = {1952},
}