Sub topic 8
Entropy: The Lower Bound on Average Code Length
The previous chapters built a Huffman code for abracadabra and used it to encode and decode. This one asks how good that code is. Huffman's algorithm produced 23 bits for an 11-symbol message. Could a smarter code have used 20 bits, or 15? Shannon entropy answers that. It gives a hard floor on the average number of bits per symbol that any symbol-by-symbol prefix code can reach, and it explains why Huffman lands so close to that floor.
This chapter assumes you know symbol frequencies and probabilities, prefix-free codes and their binary trees, the build_codes function from the Huffman construction chapter, and logarithms in base 2.
Information Content of a Single Symbol
Start with one symbol that has probability p. Its self-information is -log2(p) bits. This is the number of bits an ideal code would spend on it:
- A symbol with probability 1/2 carries 1 bit. One yes/no question identifies it.
- A symbol with probability 1/8 carries 3 bits. Three halvings of the possibilities are needed.
- A symbol with probability 1 carries 0 bits. You already knew it was coming.
The logarithm fits because information from independent events should add up. Two independent events have probability p * q, and -log2(p*q) = -log2(p) - log2(q).
Entropy as Expected Self-Information
The entropy H of a source is the average self-information, weighted by how often each symbol occurs:
H = - Σ p(s) · log2 p(s) (sum over all symbols s)The average code length L of a code is the same kind of weighted average, using the actual code lengths len(s):
L = Σ p(s) · len(s)Comparing the two formulas term by term shows what entropy means. In an ideal world, symbol s would get a code exactly -log2 p(s) bits long, and L would equal H. In practice code lengths must be whole numbers, so L can only approximate H.
For abracadabra the counts are a=5, b=2, r=2, c=1, d=1 out of 11. The table sets each symbol's ideal length beside the length Huffman actually assigned.
| Symbol | Count | p(s) | Ideal length -log2 p | Huffman length | Huffman code |
|---|---|---|---|---|---|
| a | 5 | 0.455 | 1.138 | 1 | 0 |
| b | 2 | 0.182 | 2.459 | 3 | 110 |
| r | 2 | 0.182 | 2.459 | 3 | 111 |
| c | 1 | 0.091 | 3.459 | 3 | 100 |
| d | 1 | 0.091 | 3.459 | 3 | 101 |
Weighting the ideal lengths by probability gives H ≈ 2.040 bits per symbol. Weighting the Huffman lengths gives L = 23/11 ≈ 2.091. The gap, called the redundancy, is about 0.051 bits per symbol. For comparison, a fixed-length code for five symbols needs 3 bits each, and 8-bit ASCII needs 8.
The chart shows that Huffman does not simply round each ideal length up. It gives a fewer bits than ideal and gives b and r more. Huffman optimizes the weighted total and does not try to match each length to its ideal.
Measuring It in Code
The block below is self-contained. It repeats build_codes from the construction chapter so it runs on its own. It computes entropy, the Huffman average, and, for contrast, the Shannon code lengths ceil(-log2 p). Shannon codes round every ideal length up to a whole number.
import heapq
import math
from collections import Counter
from itertools import count
def build_codes(text):
freq = Counter(text)
tiebreak = count()
heap = [(f, next(tiebreak), sym) for sym, f in freq.items()]
heapq.heapify(heap)
if len(heap) == 1:
_, _, sym = heap[0]
return {sym: "0"}
while len(heap) > 1:
f1, _, left = heapq.heappop(heap)
f2, _, right = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tiebreak), (left, right)))
codes = {}
def walk(node, prefix):
if isinstance(node, tuple):
walk(node[0], prefix + "0")
walk(node[1], prefix + "1")
else:
codes[node] = prefix
walk(heap[0][2], "")
return codes
def entropy_bits(text):
n = len(text)
return -sum((f / n) * math.log2(f / n) for f in Counter(text).values())
def average_length(text, lengths):
return sum(lengths[ch] for ch in text) / len(text)
def kraft_sum(lengths):
return sum(2 ** -l for l in lengths.values())
text = "abracadabra"
n = len(text)
huffman = {s: len(c) for s, c in build_codes(text).items()}
shannon = {s: math.ceil(-math.log2(f / n)) for s, f in Counter(text).items()}
print("entropy ", round(entropy_bits(text), 3))
print("huffman avg ", round(average_length(text, huffman), 3), "kraft", kraft_sum(huffman))
print("shannon avg ", round(average_length(text, shannon), 3), "kraft", kraft_sum(shannon))Output:
entropy 2.04
huffman avg 2.091 kraft 1.0
shannon avg 2.727 kraft 0.625Both codes stay above the entropy and below entropy plus one bit. The Shannon code wastes more: its Kraft sum of 0.625 means a large part of the code tree is unused.
Why No Prefix Code Can Beat Entropy
The lower bound comes from two facts.
The first fact is the Kraft inequality. Any prefix code with lengths len(s) satisfies Σ 2^(-len(s)) ≤ 1. In tree terms, a codeword of length l claims a fraction 2^-l of all possible bit paths, and prefix-free codewords cannot share paths. The Huffman code above sums to exactly 1 (1/2 + 4 · 1/8). Every Huffman tree is a full binary tree, so it always reaches equality.
The second fact is Gibbs' inequality. For any probability distribution p and any values q with Σ q(s) ≤ 1:
- Σ p(s) log2 p(s) ≤ - Σ p(s) log2 q(s)Set q(s) = 2^(-len(s)). The right side becomes Σ p(s) · len(s) = L, and the left side is H. So H ≤ L for every prefix code. Equality holds only when p(s) = 2^(-len(s)) for every symbol, which means every probability must be a power of 1/2. Such distributions are called dyadic.
Why Huffman Stays Within One Bit
The upper bound comes from a construction. The Shannon lengths ceil(-log2 p(s)) satisfy Kraft, because 2^(-ceil(x)) ≤ 2^(-x), so a prefix code with those lengths exists. Each length is less than its ideal value plus 1, so its average is less than H + 1. Huffman is optimal among prefix codes, as the next chapter proves, so its average can be no worse than this Shannon code. That gives:
H ≤ L_huffman < H + 1Edge Cases Where the Gap Grows
The "less than one bit" redundancy can still be large compared with the entropy.
| Source | Entropy H | Huffman L | Redundancy |
|---|---|---|---|
| Dyadic: 1/2, 1/4, 1/8, 1/8 | 1.75 | 1.75 | 0 |
| abracadabra | 2.040 | 2.091 | 0.051 |
| Skewed: 0.9, 0.1 | 0.469 | 1 | 0.531 |
| Single symbol only | 0 | 1 (by convention) | 1 |
With two symbols, Huffman must spend at least 1 bit per symbol, however predictable the source is. For the 0.9/0.1 source, that is more than twice the entropy. The single-symbol case even breaks the strict bound L < H + 1. In theory such a source needs 0 bits, because a decoder only needs the symbol and the message length. build_codes returns "0" so that every symbol produces a visible bit. The limitations chapter returns to these cases.
Common Errors
- Using the natural log. Calling
math.loggives entropy in nats. Usemath.log2to get bits. - Comparing totals with averages. 23 bits is the total, and 2.091 is bits per symbol. Multiply
Hby the message length before comparing it with an encoded bit count. - Assuming Huffman matches each ideal length. It minimizes the weighted sum. Individual lengths can sit above or below
-log2 p. - Treating
H + 1as typical. For most real alphabets the gap is far smaller. It grows close to 1 only when one symbol dominates.
Exercise
A source emits w, x, y, z with probabilities 1/2, 1/4, 1/8, 1/8. Compute its entropy, give Huffman code lengths, and explain why the redundancy is exactly zero.
Show answer
H = 1/2·1 + 1/4·2 + 1/8·3 + 1/8·3 = 1.75 bits. Huffman gives lengths 1, 2, 3, 3, so L = 1.75. Every probability is a power of 1/2, so each ideal length -log2 p is already a whole number and Gibbs' inequality holds with equality.
Exercise
For the text "aaaaaaaaab" (nine a's and one b), compute the entropy per symbol, the Huffman average length, and the total bits for the whole message under each. What does the result suggest about this source?
Show answer
p(a) = 0.9 and p(b) = 0.1, so H = 0.9·0.152 + 0.1·3.322 ≈ 0.469 bits per symbol, about 4.69 bits in total. Huffman must give each symbol 1 bit, so L = 1 and the total is 10 bits. The redundancy is 0.531 bits per symbol, more than the entropy itself. Highly skewed small alphabets are a poor fit for symbol-by-symbol Huffman coding. Grouping symbols or using arithmetic coding would get closer to the bound.
Exercise
The Shannon code for abracadabra has Kraft sum 0.625. What does a Kraft sum below 1 tell you about the code, and can Huffman ever produce one?
Show answer
A sum below 1 means some branches of the code tree hold no codeword, so some codes could be shortened without breaking the prefix property. Huffman always builds a full binary tree in which every internal node has two children, so its Kraft sum is exactly 1 whenever there are at least two symbols.