ABCDENC1–2–3–4–5–6–7–8–A1/2B1/4C1/8D1/81import numpy as np2p = np.array([4, 2, 1, 1]) / 83H = -(p * np.log2(p)).sum()4print(H) # 1.75picked Abits sent 0A0
00.250.50.75101234probability pI (bits)SURPRISE I = log2(1/p)ABC, DA 1 · B 2 · C, D 3 bitsH = 1.75average H = 1.75 bitsH = 1.75code average 1.75 = H00.250.50.75100.250.50.751probability pH (bits)BINARY ENTROPY H(p)p = 0.10 · H = 0.469
Coloured parts: what the current step is about; everything else rests in whiteBlocks: the source of letters, the encoder, the receiver's cells, the symbol table and a Python code cardPlots: surprise I = log2(1/p) with the four letters, and binary entropy H(p)A letter hops into the encoder; its codeword rides the wire as a pill as long as its bitsShannon's source: A, B, C, D with odds 1/2, 1/4, 1/8, 1/8 has entropy H = 1.75 bits per symbol. The message ABACABAD costs 16 bits with a 2-bit code and 14 bits with the code 0, 10, 110, 111. The bound H ≤ L holds for any uniquely decodable code of single symbols; the best such code has L < H + 1. Coding longer blocks of symbols brings the average as close to H as you like (Shannon's §9).

A source and a plain code

  1. A source sends one of four symbols, A, B, C or D. A comes half the time, B a quarter, C and D an eighth each. A probability is how often a symbol comes, from 0 to 1.

Measuring information

A code that fits

Beyond four symbols

The working

# step 1/10 · source

symbol   probability p
  A        1/2 = 0.5
  B        1/4 = 0.25
  C        1/8 = 0.125
  D        1/8 = 0.125
           sum = 1

each symbol is picked on its own
(independent of the ones before)
message: A B A C A B A D

The source, its probabilities 1/2, 1/4, 1/8, 1/8 and the code 0, 10, 110, 111 are the worked example in Shannon's 1948 paper (§10). The message ABACABAD is chosen to hold the letters in exactly those proportions. Every number in the figure is computed from this model. Bits move along the wire much more slowly than in any real link, so you can follow each codeword.