TExcelTAD
Home › Information Theory › Optimal Code Lengths

Optimal Code Lengths

The entropy bound says no symbol code beats H(X)H(X) bits per symbol, and equality needs ℓ(x)=log⁡21P(x)\ell(x) = \log_2 \frac{1}{P(x)}. Those ideal lengths are usually not integers. This lesson shows that rounding them up costs less than one bit, that coding blocks of symbols spreads that bit over the block, and what it costs to use lengths matched to the wrong distribution.

Shannon code lengths

Choose ℓ(x)=⌈log⁡21P(x)⌉\ell(x) = \left\lceil \log_2 \frac{1}{P(x)} \right\rceil. These lengths satisfy Kraft, because 2−ℓ(x)≤P(x)2^{-\ell(x)} \le P(x) and the probabilities sum to 1, so a prefix code with them exists (The Kraft Inequality). Since ℓ(x)<log⁡21P(x)+1\ell(x) < \log_2 \frac{1}{P(x)} + 1,

H(X)≤L<H(X)+1H(X) \le L < H(X) + 1

This is the source coding theorem for symbol codes.

python · try it yourself
import numpy as np

P = np.array([0.4, 0.3, 0.2, 0.1])
ideal = np.log2(1 / P)
shannon = np.ceil(ideal).astype(int)
print("ideal lengths:  ", np.round(ideal, 3))
print("Shannon lengths:", shannon, " Kraft sum:", float(np.sum(2.0 ** -shannon)))
print(f"H = {-np.sum(P * np.log2(P)):.4f},  L = {P @ shannon:.4f}")
ideal lengths:   [1.322 1.737 2.322 3.322]
Shannon lengths: [2 2 3 4]  Kraft sum: 0.6875
H = 1.8464,  L = 2.4000

Shannon lengths are not always optimal: here the Kraft sum is well below 1, which wastes code space. Huffman's algorithm finds the best integer lengths (Huffman Coding).

Blocking removes the extra bit

Applying the bound to blocks of nn symbols, whose entropy is nHnH, gives nH≤Ln<nH+1nH \le L_n < nH + 1, so per symbol

H≤Lnn<H+1nH \le \frac{L_n}{n} < H + \frac{1}{n}

The overhead per symbol shrinks as 1n\frac{1}{n}. The cost is an alphabet of size ∣A∣n|\mathcal{A}|^n; arithmetic coding gets the same effect without building the huge code (Arithmetic Coding).

python · try it yourself
import numpy as np
from itertools import product

p = np.array([0.9, 0.1])
H = -np.sum(p * np.log2(p))
for n in [1, 2, 4, 8, 12]:
    probs = np.array([np.prod(c) for c in product(p, repeat=n)])
    L = probs @ np.ceil(np.log2(1 / probs))
    print(f"n = {n:2d}: Shannon code {L / n:.4f} bits/symbol   (H = {H:.4f})")
n =  1: Shannon code 1.3000 bits/symbol   (H = 0.4690)
n =  2: Shannon code 0.8000 bits/symbol   (H = 0.4690)
n =  4: Shannon code 0.5509 bits/symbol   (H = 0.4690)
n =  8: Shannon code 0.5501 bits/symbol   (H = 0.4690)
n = 12: Shannon code 0.4951 bits/symbol   (H = 0.4690)

The cost of a wrong model

If the code lengths are ideal for a model QQ, ℓ(x)=log⁡21Q(x)\ell(x) = \log_2 \frac{1}{Q(x)}, but the data follow PP, the expected length is the cross-entropy:

L=∑xP(x)log⁡21Q(x)=H(P)+DKL(P∥Q)L = \sum_x P(x)\log_2 \frac{1}{Q(x)} = H(P) + D_{\text{KL}}(P \parallel Q)

Every bit of KL divergence is a bit wasted per symbol (Relative Entropy (KL Divergence)).

python · try it yourself
import numpy as np

P = np.array([0.5, 0.25, 0.125, 0.125])
for name, Q in [("true model", P), ("slightly off", np.array([0.4, 0.3, 0.15, 0.15])),
                ("uniform", np.ones(4) / 4), ("badly off", np.array([0.05, 0.05, 0.45, 0.45]))]:
    L = P @ np.log2(1 / Q)
    print(f"{name:12s}: L = {L:.4f}, KL = {np.sum(P * np.log2(P / Q)):.4f}")
true model  : L = 1.7500, KL = 0.0000
slightly off: L = 1.7794, KL = 0.0294
uniform     : L = 2.0000, KL = 0.2500
badly off   : L = 3.5294, KL = 1.7794

Dyadic distributions

When every probability is a power of 12\frac{1}{2} (a dyadic distribution), the ideal lengths are integers and L=HL = H exactly. For other distributions some redundancy L−H>0L - H > 0 remains for symbol codes.

In software

  • Adaptive compressors estimate QQ as they go, so their redundancy is the KL divergence between the true statistics and the running estimate, which shrinks as more data arrive.
  • When a format allows blocking or arithmetic coding, prefer it for very skewed sources (one symbol with probability near 1), where symbol codes waste close to 1 bit per symbol.

Exercises

Exercise 1: Shannon lengths

Compute Shannon code lengths for P=(0.6,0.25,0.1,0.05)P = (0.6, 0.25, 0.1, 0.05).

Answer

(1,2,4,5)(1, 2, 4, 5).

Solution

⌈log⁡210.6⌉=⌈0.737⌉=1\lceil \log_2 \frac{1}{0.6} \rceil = \lceil 0.737 \rceil = 1, ⌈2⌉=2\lceil 2 \rceil = 2, ⌈3.32⌉=4\lceil 3.32 \rceil = 4, ⌈4.32⌉=5\lceil 4.32 \rceil = 5.

Exercise 2: Very skewed source

A source emits a with probability 0.99. What is the best expected length of a symbol code with 2 symbols, and what is the entropy?

Answer

1 bit versus about 0.081 bits.

Solution

Every codeword needs at least 1 bit, so L=1L = 1, while H2(0.01)=0.0808H_2(0.01) = 0.0808. The redundancy is over 90%; blocking or arithmetic coding is needed.

Exercise 3: Mismatched code (code)

Code lengths (1,2,3,3)(1, 2, 3, 3) were designed for (12,14,18,18)(\frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \frac{1}{8}), but the data follow P=(0.25,0.25,0.25,0.25)P = (0.25, 0.25, 0.25, 0.25). Compute the expected length and DKL(P∥Q)D_{\text{KL}}(P \parallel Q).

Answer

2.25 bits per symbol, and the divergence is 0.25 bits.

Solution
python · try it yourself
import numpy as np

P = np.ones(4) / 4; Q = np.array([0.5, 0.25, 0.125, 0.125])
print(float(P @ np.log2(1 / Q)), float(np.sum(P * np.log2(P / Q))))
2.25 0.25

The uniform data have entropy 2, and the mismatch adds 0.25 bits.

Test yourself

Shannon code lengths ⌈log⁡21P(x)⌉\lceil \log_2 \frac{1}{P(x)} \rceil give an expected length…

  1. between H and H + 1
  2. exactly H
  3. below H
  4. between H + 1 and H + 2

Coding blocks of n symbols reduces the per-symbol overhead to below…

  1. 1n\frac{1}{n} bit
  2. 1 bit
  3. nn bits
  4. 12\frac{1}{2} bit

Using code lengths ideal for Q on data from P costs on average…

  1. H(P)+DKL(P∥Q)H(P) + D_{\text{KL}}(P \parallel Q) bits
  2. H(Q)H(Q) bits
  3. H(P)−DKL(P∥Q)H(P) - D_{\text{KL}}(P \parallel Q) bits
  4. H(P)H(Q)H(P)H(Q) bits