Mathematics RU

Practice · Chapter 50

Entropy, codes and chains

How much information an outcome carries, Shannon entropy, the average code length and Huffman codes, and the share of time a Markov chain spends in each state.

How to solve it

The more surprising an outcome, the more information it carries: an outcome of probability $\frac{1}{8}$ is $3$ bits, like three yes/no answers. Entropy is the average information per outcome, and also the lower bound for the average length of any code: lossless compression cannot go below it.

Step by step

  1. The information of an outcome of probability $p$: $\log_2 \frac{1}{p}$ bits.
  2. Entropy is the weighted average: $H = \sum p_i \log_2 \frac{1}{p_i}$.
  3. The average code length is $\sum p_i \ell_i$, where $\ell_i$ is the length of a letter's code.
  4. A Huffman code: merge the two rarest symbols into one with their total probability until one is left. A symbol's code length is how many merges it took part in.
  5. A Markov chain: in equilibrium the flow out of each state equals the flow into it.
The probabilities of the outcomes, adding up to $1$. Example: $\left(\frac{1}{4}, \frac{1}{4}, \frac{1}{4}, \frac{1}{8}, \frac{1}{8}\right)$: $3 \cdot \frac{1}{4} \cdot 2 + 2 \cdot \frac{1}{8} \cdot 3 = \frac{3}{2} + \frac{3}{4} = \frac{9}{4}$ bits.

Common mistakes

  • Taking $\log_2 p$ without the minus or the flipped fraction — entropy is never negative.
  • Adding code lengths without weights: frequent letters count more often.
  • Merging the most frequent symbols in Huffman's algorithm instead of the rarest.
  • Confusing a transition probability in a Markov chain with the share of time in a state.

Example