A source and a plain code
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.
Four symbols fit in 2 bits: 00, 01, 10, 11, because 2² = 4. Every symbol costs 2 bits, so the 8-symbol message costs 16 bits. Can we spend fewer?
Measuring information
A rare symbol tells you more. Shannon measured this as information, or surprise: I = log2(1/p) bits. A (p = 1/2) carries 1 bit, B 2 bits, C and D 3 bits each.
Weight each surprise by how often it comes and add: H = ½·1 + ¼·2 + ⅛·3 + ⅛·3 = 1.75 bits per symbol. This average is the entropy of the source.
A code that fits
Give each symbol as many bits as its surprise: A 0, B 10, C 110, D 111. No codeword is the start of another, so this is a prefix-free code.
Now the common A costs 1 bit and the rare C and D cost 3. The same 8 symbols take 14 bits instead of 16: 12.5% fewer, and nothing is lost.
The receiver needs no gaps between codewords. It reads bits until they match a codeword, writes that letter and starts again. Prefix-free makes the first match the only one.
14 bits / 8 symbols = 1.75 bits per symbol: exactly H. Shannon proved no decodable code (one the receiver can always split back into letters) can average fewer than H bits. Huffman's method (see the DSA lesson) finds the best code.
Beyond four symbols
A source with two symbols, picked with odds p and 1 − p, has H(p) bits. A fair coin (p = 0.5) gives the most: 1 bit. At p = 0.1 it is only 0.469 bits.
With numpy, entropy is one line. p holds the four probabilities. np.log2 takes the base-2 log of every entry, and −(p·log2 p).sum() adds the weighted surprises: 1.75.
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.