Source coding and Kraft's inequality
Use binary code trees to connect integer description lengths with entropy and distinguish lossless variable-length coding from almost-lossless block compression.
On this page
The question for today
What you’ll understand
- Apply Kraft's condition to binary prefix code lengths.
- Distinguish the universal entropy lower bound from an achievable upper bound.
- Compute valid codewords, expected lengths and the source object being reconstructed.
Information values are real numbers, but binary codewords have integer lengths. Prefix coding reconciles those facts by assigning short words to common symbols while making concatenations instantly decodable. A code tree imposes a precise capacity constraint on the lengths. Entropy then bounds the best achievable average, rather than the length of every individual word. The coding theorem concerns the specified source and decoder: coding a summary such as a count is not lossless reconstruction of the original ordered observations.
Code-tree space is a finite resource
A binary prefix code has no codeword that is the beginning of another. The decoder can therefore identify the current word without waiting for later symbols. A word of length ell occupies a fraction two to the minus ell of a full binary tree's possible extensions. Disjointness of these occupied branches implies Kraft's inequality. Conversely, nonnegative integer lengths satisfying that inequality can be realized by a prefix code; with at least two supported symbols their usable codewords have positive lengths.
Unique decodability is weaker than the prefix condition: a code can allow unambiguous complete concatenations without allowing immediate symbol-by-symbol termination. McMillan's inequality gives the same necessary length constraint for uniquely decodable codes. Here the constructive examples use prefix codes so that a tree provides an explicit decoder. If the source is a singleton, an empty word can represent its sole symbol when the number of symbols to decode is known; that convention must be separated from a multi-symbol source.
The upper bound is an existence statement
For a finite source with at least two positive-probability symbols, choose Shannon lengths by rounding each ideal information value up to the next integer. Their Kraft sum is at most the sum of the source probabilities, hence at most one. Each rounded length is strictly less than its ideal length plus one. Averaging produces a prefix code with expected length below H plus one. This does not say that every valid prefix code is so efficient; arbitrarily wasteful codes remain valid.
The lower bound follows by normalizing the masses two to the minus each length into a probability law and using nonnegative divergence. Equality is possible for dyadic probabilities whose ideal lengths are already integers. Huffman's algorithm optimizes the expected length among finite binary prefix codes by repeatedly merging two smallest masses. Its tree argument exploits the fact that two least probable symbols can be assigned deepest sibling leaves without increasing the expected length.
The decoding requirement determines the theorem
A variable-length prefix code can reconstruct every supported source symbol with zero error while controlling expected length. A fixed-length block code has a different tradeoff: below the logarithm of the supported block count, it generally needs to permit a failure event. Typicality can make that probability small at rates above entropy. These statements are compatible because they constrain different quantities, namely expected length versus a fixed number of transmitted bits.
Likewise, compressing the count of ones in a block preserves less than compressing the block itself. Several ordered blocks can have one count, so a decoder for the count has not reconstructed their order. An entropy calculation should name the object whose distribution it uses. This distinction is relevant in data aggregation: a summary may be exactly encoded and still discard information needed for a later task, even when its own code is optimal.
Work it through
An exact dyadic prefix code
A four-symbol source has probabilities 1/2,1/4,1/8,1/8. Verify the codewords 0,10,110,111 and compare their expected length with entropy.
No listed word is a prefix of another. The lengths are one, two, three and three, with Kraft sum 1/2+1/4+1/8+1/8=1.
The expected length is (1/2)·1+(1/4)·2+(1/8)·3+(1/8)·3=7/4 bits per symbol.
Each length equals minus log₂ of its probability, so entropy is also 7/4. The entropy lower bound proves optimality of this prefix code for the specified source.
This source has no integer-rounding penalty. Other distributions generally have positive redundancy even for an optimal one-symbol prefix code.
The living notebook
Explore the model
Interactive lab · probability
Code a binomial count rather than the ordered trials
Pause and reset, then set both controls to p = 0.5 and n = 2. Predict count probabilities (0.25,0.5,0.25). Code counts zero, one and two as 00, 1 and 01; predict expected length 1.5 bits. For a fresh comparison, pause and reset, then set p = 0.5 and n = 1; the two outcomes need one bit each. The first code reconstructs a count, not which ordering produced a single success. The instrument displays the source probabilities and does not run the encoder.
- Mean · np
- 5
- Variance · np(1−p)
- 2.5
- Total probability
- 1
These are exact binomial probabilities for independent trials with one fixed success probability. Playback tours the distribution; it does not resample outcomes. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forAn optimal code is lossless only for the random object its decoder reconstructs.
Pause & reason
Check your understanding
Your turn
Try it yourself
For probabilities (0.6,0.3,0.1), compare Shannon lengths (1,2,4) with prefix codewords 0,10,11. Compute both expected lengths and explain why proposed lengths (1,1,2) are impossible for a binary prefix code.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
The three-word code has lengths (1,2,2). Check each Kraft sum before comparing averages.
Compare with the solution
Shannon lengths have Kraft sum 1/2+1/4+1/16=13/16 and expected length 0.6+0.6+0.4=1.6. The code 0,10,11 has Kraft sum one and expected length 0.6+0.6+0.2=1.4, smaller than the rounded construction and consistent with entropy about 1.295462. Proposed lengths (1,1,2) have Kraft sum 1.25, so no binary prefix code realizes them. Shortening descriptions cannot ignore the decoding constraint, even when the requested average looks attractive.
Keep the idea
Take it with you
- Kraft's inequality enforces the space occupied by a binary prefix tree.
- Entropy is a universal lower bound; the within-one-bit upper bound is achievable, not universal.
- Expected-length, fixed-length and summary-coding guarantees reconstruct different objects under different constraints.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.