Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·01

Start Here: What Information Is

Around chapter 1: how information, surprise and bits connect to the rest of the book; three other ways to see them; what the chapter simplifies (probability depends on the model, a compressor can be fooled by a 60-byte program, and unequal odds beat the worst case on average); how Python's secrets module sizes tokens in bytes of information and what hex and base64 do to them; four debugging drills; and interview questions.

6 topics · ~13 min read
Updated Suggest a correction

Understanding it better

Concept map

  • A message is a choice from a set of possibilities (Hartley 1928) → information depends on the set and its probabilities, not on meaning (Shannon 1948).
  • Surprise −log2p → zero for certainty, unbounded for the rare → additive for independent events → must be a logarithm (the chapter's theorem).
  • Units bit, nat, ban → one theory, scaled.
  • Questions → ⌈log2N⌉ in the worst case → fewer on average when the odds are unequal (point 3 below; chapter 5).
  • Average surprise → entropy (chapter 4), measured in the lab as 4.19 bits per letter.
  • Stored digits against information → redundancy → compression (chapters 5 and 6), with compressed size as an upper bound.
  • Shannon's system → source coding (remove redundancy) and channel coding (add it back, chapters 8 and 9).

Explain it differently

Information as a weight lifted. Before a message you carry a load of uncertainty: all the things that might be true. Each message lifts some of the load. A message you expected lifts almost nothing; a surprising one lifts a lot. Bits measure the weight lifted, and two independent messages lift their two weights.

The library index. To find one book among a million, you don't read every title: you follow the index, each step narrowing the shelves by half. Twenty steps find any book. The number of steps you need is the information in "which book", and a library whose readers mostly want the same few books could put those near the door, so the average reader needs fewer steps (chapter 5).

News value. A newspaper headline "Sun rises" sells nothing; "Snow in the desert" sells out. Editors already rank stories by surprise. Information theory makes the ranking a number, and also explains why a paper that printed only surprising headlines would still need a few routine ones: without them, readers couldn't tell whether a missing story meant "nothing happened" or "the paper lost it" (the redundancy of chapter 8).

Gaps and misconceptions

What the chapter oversimplifies

1. "Surprise depends only on the probability", but the probability depends on what you already know. The chapter's surprise of a letter used its overall frequency. A reader who has just seen "q" knows much more:

Python
import math
from collections import Counter
text = open("data/shakespeare.txt", encoding="utf-8").read().lower()
letters = "".join(c for c in text if "a" <= c <= "z")
n = len(letters)
p_u = letters.count("u") / n
after_q = Counter(letters[i + 1] for i in range(n - 1) if letters[i] == "q")
p_u_after_q = after_q["u"] / sum(after_q.values())
print(f"P(u) = {p_u:.4f}: surprise {-math.log2(p_u):.2f} bits")
print(f"P(u | previous letter is q) = {p_u_after_q:.4f}: surprise {-math.log2(p_u_after_q) + 0.0:.3f} bits")
print("letters after q:", dict(after_q.most_common()))
Text
P(u) = 0.0351: surprise 4.83 bits
P(u | previous letter is q) = 1.0000: surprise 0.000 bits
letters after q: {'u': 840}

On its own, a "u" carries 4.83 bits. After a "q" it carries nothing: in all 840 cases in the plays, "q" is followed by "u". The same letter has different surprise depending on the model of the source, and the better the model, the less surprise is left. That's why the chapter's 4.19 bits per letter (no context) is far above the 2.6 bits per letter lzma achieved (it uses context), and why chapter 7 defines conditional information.

2. "A compressor measures information", but a compressor only sees the patterns it models. The lab's "random bytes" didn't compress. But they weren't random: Python made them from a seed.

Python
import bz2, lzma, random, zlib
program = "import random\nrandom.seed(1948)\nrandom.randbytes(1_115_394)\n"
random.seed(1948)
data = random.randbytes(1_115_394)
for name, f in (("zlib", lambda d: zlib.compress(d, 9)), ("bz2", lambda d: bz2.compress(d, 9)), ("lzma", lambda d: lzma.compress(d, preset=9))):
    print(f"{name:<5} {len(f(data)):>10,} bytes")
print(f"the program that makes the same bytes: {len(program)} bytes")
Text
zlib   1,115,740 bytes
bz2    1,120,564 bytes
lzma   1,115,508 bytes
the program that makes the same bytes: 60 bytes

All three compressors made the 1,115,394 bytes slightly bigger, yet a 60-byte program regenerates them exactly. A pseudo-random generator is designed to have no pattern that a general-purpose compressor can find, but the bytes have a very short description. So "the compressed size" is an upper bound on information relative to the compressor's model; the shortest description (Kolmogorov complexity, the exercises' "What the chapter leaves out") can be far shorter, and can't be computed in general. For data really produced by a random source, the lab's conclusion stands: no compressor can shrink it on average (chapter 6).

3. "log2N questions", which is only the worst case for equally likely outcomes. When some outcomes are likelier, you can ask about them first:

Python
import math, random
random.seed(5)
outcomes, probs = "ABCD", [1 / 2, 1 / 4, 1 / 8, 1 / 8]
# Strategy 1: two fair halving questions, ignoring probabilities. Strategy 2: ask about the likeliest first.
questions_2 = {"A": 1, "B": 2, "C": 3, "D": 3}   # "Is it A?" then "Is it B?" then "Is it C?"
draws = random.choices(outcomes, weights=probs, k=1_000_000)
print("halving, ignoring probabilities: 2.000 questions every time")
print(f"likeliest first: {sum(questions_2[d] for d in draws) / len(draws):.3f} questions on average")
print("average surprise:", sum(p * -math.log2(p) for p in probs))
Text
halving, ignoring probabilities: 2.000 questions every time
likeliest first: 1.749 questions on average
average surprise: 1.75

With four outcomes of probabilities 12,14,18,18, halving always needs 2 questions, but "is it A? then B? then C?" needs 1, 2 or 3, averaging 1.75 over a million draws: exactly the average surprise of the outcomes, 12·1+14·2+18·3+18·3 =1.75. The strategy asks as many questions about each outcome as its surprise in bits. Chapter 4 calls that average the entropy, and chapter 5 shows that a question strategy is the same thing as a code.

Common misconceptions

Misconception What's actually true Where it's shown
"A letter always carries the same information." It depends on the model: "u" carries 4.83 bits alone and 0 after "q". What the chapter oversimplifies, point 1
"If no compressor can shrink it, it's random." Pseudo-random bytes from a 60-byte program defeat zlib, bz2 and lzma. What the chapter oversimplifies, point 2
"Finding one of N needs log₂ N questions, always." That's the worst case for equal odds; unequal odds allow fewer on average. What the chapter oversimplifies, point 3
"A 32-character hex token has 256 bits of security." It carries 128 bits: each hex character is 4 bits stored in 8. Code walkthrough
"math.log gives bits." It gives nats; bits need math.log2. Drill D1
"Percentages work as probabilities." Surprise needs p between 0 and 1; percentages give negative "bits". Drill D2
"int(math.log2(n)) questions are enough." It rounds down; the worst case needs ⌈log2n⌉. Drill D3
"Compressing a message measures its information." Short messages grow, because of fixed headers and checksums. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Probability as the receiver's knowledge. Shannon's probabilities describe the source, but they're used by the receiver; when the two disagree, coding costs more (chapter 11's Kullback–Leibler divergence). Some writers (E. T. Jaynes most forcefully) read all probability as a state of knowledge, which makes information a property of the receiver's model.
  • Cauchy's functional equation. The chapter's proof that surprise must be a logarithm is a case of Cauchy's equation g(x+y)=g(x)+g(y), whose only well-behaved solutions are g(x)=cx. Without some regularity condition (continuity, monotonicity, or even measurability) it has bizarre other solutions, which is why the theorem needs the "changes smoothly" condition.
  • Kolmogorov complexity and randomness. Point 2 above is the gap between statistical randomness (no pattern a test finds) and algorithmic randomness (no short description). A string is algorithmically random if its shortest description is about as long as the string; most strings are, by counting, but no algorithm can certify a particular one (a consequence of the halting problem).

Applying it

Code walkthrough

Python's secrets module makes tokens for passwords, reset links and session ids, and it sizes them in bytes of information. Excerpts from Lib/secrets.py in Python 3.13 (on your computer: python3 -c "import secrets; print(secrets.__file__)"):

Python
DEFAULT_ENTROPY = 32  # number of bytes to return by default

def token_bytes(nbytes=None):
    """Return a random byte string containing *nbytes* bytes.
    ...
    """
    if nbytes is None:
        nbytes = DEFAULT_ENTROPY
    return _sysrand.randbytes(nbytes)

def token_hex(nbytes=None):
    """Return a random text string, in hexadecimal.

    The string has *nbytes* random bytes, each byte converted to two
    hex digits.  ...
    """
    return token_bytes(nbytes).hex()

def token_urlsafe(nbytes=None):
    """Return a random URL-safe text string, in Base64 encoding.

    The string has *nbytes* random bytes.  ...
    """
    tok = token_bytes(nbytes)
    return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')

The argument is always the number of random bytes, so the information in a token is 8× nbytes bits, whatever its text looks like: DEFAULT_ENTROPY = 32 means 256 bits. _sysrand is a random.SystemRandom, which reads the operating system's cryptographic random source, so each byte is (as far as anyone can tell) uniform and independent: a full 8 bits. token_hex spells each byte as two hex characters, so the text is twice as long and carries the same information; token_urlsafe uses base64, 6 bits per character, and strips the = padding. Measured:

Python
import lzma, math, secrets
print("default token_bytes length:", len(secrets.token_bytes()), "bytes =", 8 * secrets.DEFAULT_ENTROPY, "bits of information")
for name, make in (("token_bytes(16)", lambda: secrets.token_bytes(16)),
                   ("token_hex(16)", lambda: secrets.token_hex(16).encode()),
                   ("token_urlsafe(16)", lambda: secrets.token_urlsafe(16).encode())):
    tokens = [make() for _ in range(20_000)]
    size = len(tokens[0])
    packed = len(lzma.compress(b"".join(tokens), preset=9))
    print(f"{name:<18} {size:>2} bytes stored = {8 * size:>3} binary digits for 128 bits;"
          f" lzma on 20,000 of them: {8 * packed / (20_000 * 128):.3f} compressed bits per bit of information")
print("bits per character: hex", math.log2(16), "| URL-safe base64", math.log2(64), "| 22 characters x 6 =", 22 * 6)
Text
default token_bytes length: 32 bytes = 256 bits of information
token_bytes(16)    16 bytes stored = 128 binary digits for 128 bits; lzma on 20,000 of them: 1.000 compressed bits per bit of information
token_hex(16)      32 bytes stored = 256 binary digits for 128 bits; lzma on 20,000 of them: 1.039 compressed bits per bit of information
token_urlsafe(16)  22 bytes stored = 176 binary digits for 128 bits; lzma on 20,000 of them: 1.051 compressed bits per bit of information
bits per character: hex 4.0 | URL-safe base64 6.0 | 22 characters x 6 = 132

All three tokens from nbytes=16 carry 128 bits. As bytes they take 128 stored binary digits, one per bit, and lzma can't shrink them. As hex they take 256 binary digits (each character is a byte carrying 4 bits), and as base64 176 (22 characters, each a byte carrying 6 bits; 22×6=132, so the last character carries only 2 bits of the token). lzma squeezes the text forms back towards one compressed bit per bit of information but doesn't quite get there (1.039 and 1.051), a reminder that a general-purpose compressor gives an upper bound.

Read it yourself

Using the code above: how many bits of information does token_urlsafe(32) carry, and how many characters long is it? A colleague shortens reset links by keeping only the first 16 characters of token_hex(). How many bits are left, and is it enough?

Debugging drills

D1. Bits that come out too small

A surprise function reports a fair coin as 0.69 bits.

Python
import math
def surprise_bits(p):
    return -math.log(p)
print("fair coin:", surprise_bits(0.5), "bits")
print("1 in 1024:", surprise_bits(1 / 1024), "bits")
Text
fair coin: 0.6931471805599453 bits
1 in 1024: 6.931471805599453 bits

D2. Negative information

A weather app computes the surprise of each forecast from an API's probabilities and gets negative bits.

Python
import math
forecast = {"sun": 70, "cloud": 25, "rain": 5}      # percent, from a weather API
for kind, p in forecast.items():
    print(f"{kind:<5} surprise {-math.log2(p):6.2f} bits")
Text
sun   surprise  -6.13 bits
cloud surprise  -4.64 bits
rain  surprise  -2.32 bits

D3. One question short

A game asks at most questions_needed(n) questions before giving up. Players with 1,000 possibilities sometimes lose although they played perfectly.

Python
import math
def questions_needed(n):
    """Yes-or-no questions that always identify one of n possibilities."""
    return int(math.log2(n))
for n in (8, 1000, 1_000_000):
    print(n, "->", questions_needed(n))
Text
8 -> 3
1000 -> 9
1000000 -> 19

D4. Messages that grow when compressed

A team estimates how much information each chat message carries by compressing it, and finds that every message carries more information than its length.

Python
import zlib
for msg in (b"a", b"yes", b"no", b"hello world"):
    print(f"{msg!r:<15} {len(msg):>2} bytes -> zlib {len(zlib.compress(msg)):>2} bytes")
Text
b'a'             1 bytes -> zlib  9 bytes
b'yes'           3 bytes -> zlib 11 bytes
b'no'            2 bytes -> zlib 10 bytes
b'hello world'  11 bytes -> zlib 19 bytes

Career-oriented

Interview prep

Mid level

Q1. What does it mean for a file to contain "less information than its size"? Give two examples and a way to measure it.

How to get there. Stored digits against bits of information; compression as an upper bound.

Q2. Why is the information in an outcome −log2p, and what does a bit mean?

How to get there. Additivity forces the logarithm; the base fixes the unit.

Senior level

Q3. A product shows users a "random-looking" 12-character code for redeeming gift cards, made of uppercase letters and digits. How would you decide whether it's long enough?

How to get there. Information in the code, attacker's guesses, number of valid codes alive.

Q4. A team proposes saving storage by compressing each small JSON event individually before writing it. Evaluate the idea.

How to get there. Overhead on small inputs; where the redundancy actually is.

Staff level

Q5. Your organisation is building a telemetry pipeline that costs millions a year in storage and transfer. How would you use the ideas of this chapter to set a strategy?

How to get there. Information against volume; what's surprising; what must be kept anyway.

Q6. A researcher claims a new compression algorithm shrinks every file by at least one byte. How do you respond?

How to get there. Counting files of each length.