Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·10

Information Everywhere: Language, DNA, Randomness and Passwords

Around chapter 10: how models, real sources, min-entropy and guessing connect the book; three other ways to see them; what the chapter simplifies (the plug-in entropy of passwords keeps rising with more data, two distributions with the same entropy can need 32 or 257 guesses on average, and compressors on small samples overstate entropy); how Python's secrets module draws a fair number below n by drawing again; four debugging drills; and interview questions.

6 topics · ~15 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Source coding theorem (chapter 6) → every model's surprise on unseen data is an upper bound on the entropy rate → language models, compressors.
  • Overfitting (chapter 7) → blending contexts (PPM, Witten–Bell) → 2.13 bits per letter on the plays.
  • Shannon's guessing game → guess counts give an upper bound for any guesser, a lower bound only for an ideal one.
  • Encodings (chapter 1) → bytes measure UTF-8, not information; compare the same content.
  • DNA: near 2 bits for general models; reverse complements and references (conditional entropy, chapter 7) find its structure.
  • Min-entropy −log2maxp → guessability; ≤ Shannon entropy → secure generators, seeds, passwords.
  • Guess curves → password policy that targets the top of the distribution.
  • Next: chapter 11 makes "surprise under a model" precise as cross-entropy and KL divergence.

Explain it differently

Betting on the next letter. Cover and King estimated English by having people bet on each next letter. A gambler who knew the true probabilities would grow their money fastest, and how fast it grows is log227 minus the entropy rate: better knowledge of the language, faster growth. Every model is a betting strategy, and the money it wins measures how much it knows.

The phone book and the lottery. A phone book full of names looks like high-entropy text, but if you know the town, you can guess the common surnames. A lottery ticket's numbers look no more random, but every combination really is equally likely. Shannon entropy can't tell them apart from frequencies alone; min-entropy, the chance of the best guess, can.

A lock with a favourite combination. A combination lock with a million settings is strong only if every setting is equally likely. If one in a hundred owners sets it to their birth year, a thief with a list of years opens many locks in a few tries. The lock's design has 20 bits; its owners have given it far fewer.

Gaps and misconceptions

What the chapter oversimplifies

1. "The plug-in entropy of the passwords is 21 bits, an underestimate", but how much of one? Take random samples of the accounts of different sizes:

Python
import math
import numpy as np

counts = []
with open("data/rockyou-withcount.txt", "rb") as f:
    for line in f:
        field = line.split(None, 1)[:1]
        if field and field[0].isdigit():
            counts.append(int(field[0]))
counts = np.array(counts)
rng = np.random.default_rng(10)
print(f"{'share of accounts':>18}{'accounts':>13}{'distinct':>12}{'plug-in entropy':>17}{'min-entropy':>13}")
for share in (0.001, 0.01, 0.1, 1.0):
    c = rng.binomial(counts, share) if share < 1 else counts
    c = c[c > 0]
    p = c / c.sum()
    print(f"{share:>18}{c.sum():>13,}{c.size:>12,}{-(p * np.log2(p)).sum():>17.2f}{-math.log2(p.max()):>13.2f}")
Text
 share of accounts     accounts    distinct  plug-in entropy  min-entropy
             0.001       32,964      29,180            14.61         6.79
              0.01      325,503     247,749            17.25         6.80
               0.1    3,259,911   1,974,275            19.44         6.81
               1.0   32,603,388  14,344,391            21.07         6.81

With 0.1 % of the accounts the estimate is 14.61 bits; with 1 %, 17.25; 10 %, 19.44; all of them, 21.07, and it shows no sign of levelling off: each tenfold increase in data adds about 2 bits, because new data keeps revealing new passwords (most passwords are unique). There's no reliable way to estimate the Shannon entropy of such a long-tailed distribution from a sample. The min-entropy, by contrast, is the same at every size (6.79 to 6.81 bits): the top of the distribution is easy to estimate. That's another reason security work measures the top (min-entropy, guess curves) rather than the Shannon entropy.

2. "Entropy measures how hard something is to guess", but not on average either. James Massey showed (1994) that Shannon entropy doesn't determine the expected number of guesses:

Python
import math

def shannon(p):
    return -sum(x * math.log2(x) for x in p if x)
def guesswork(p):                                 # expected number of guesses, best guesses first
    return sum(i * x for i, x in enumerate(sorted(p, reverse=True), start=1))
def min_entropy(p):
    return -math.log2(max(p))

uniform = [1 / 64] * 64                            # 6 bits
skewed = [0.5] + [0.5 / 2**10] * 2**10             # also 6 bits of Shannon entropy
for name, p in (("uniform over 64 values", uniform), ("half on one value, half spread over 1,024", skewed)):
    print(f"{name:<42} Shannon {shannon(p):.2f} bits, min-entropy {min_entropy(p):.2f}, expected guesses {guesswork(p):,.1f}")
Text
uniform over 64 values                     Shannon 6.00 bits, min-entropy 6.00, expected guesses 32.5
half on one value, half spread over 1,024  Shannon 6.00 bits, min-entropy 1.00, expected guesses 257.2

Both distributions have exactly 6 bits of Shannon entropy. Guessing a value from the uniform one takes 32.5 guesses on average; from the skewed one, 257.2, almost eight times as many, even though its min-entropy is only 1 bit (half the time the first guess wins). Shannon entropy, min-entropy and the expected number of guesses (the guesswork) answer three different questions: average description length, best single guess, and patience needed. A secret is strong when all three are high, which only happens when it's close to uniform.

3. "lzma needs 2.80 bits per character for the English declaration", but on 10,000 bytes. Compressors learn as they go, so their figure depends on how much they've seen:

Python
import lzma
from pathlib import Path

text = Path("data/shakespeare.txt").read_bytes()
print(f"{'bytes of the plays':>19}{'lzma bits per char':>20}")
for n in (1_000, 10_000, 100_000, len(text)):
    print(f"{n:>19,}{8 * len(lzma.compress(text[:n], preset=9 | lzma.PRESET_EXTREME)) / n:>20.3f}")
Text
 bytes of the plays  lzma bits per char
              1,000               5.344
             10,000               3.674
            100,000               2.981
          1,115,394               2.614

On the plays, lzma needs 5.34 bits per character after 1,000 bytes, 3.67 after 10,000, 2.98 after 100,000 and 2.61 for the whole 1.1 MB. Every figure is an upper bound, and short samples give loose ones: the chapter's 13-language table, made from about 10,000 bytes each, overstates every language's entropy, most of all for scripts with hundreds of characters, where a small sample barely shows each character's frequency. Comparisons are only fair at equal and sufficient sizes, and a compressor's figure should always be reported with the amount of data.

Common misconceptions

Misconception What's actually true Where it's shown
"With enough data, the plug-in estimate of password entropy settles." It rose about 2 bits per tenfold more data, from 14.6 to 21.1. What the chapter oversimplifies, point 1
"Equal entropy means equally hard to guess." 6 bits each: 32.5 expected guesses for one, 257.2 for the other. What the chapter oversimplifies, point 2
"A compressor's bits per character is a fixed property of the text." lzma: 5.34 after 1,000 bytes, 2.61 after 1.1 MB. What the chapter oversimplifies, point 3
"A fair number below n is a random number modulo n." secrets draws again when the value is too large; draws per number ranged from 1.02 to 2.00. Code walkthrough
"Length times log of the character pool measures strength." 'Password1!' scored 65.5 bits by the formula. Drill D1
"A long random-looking token is strong." A 20-character token seeded with the time was found in about 2,400 guesses. Drill D2
"A text in a language the model knows gets a finite score." A character outside a model's alphabet gave infinite surprise. Drill D3
"DNA can't exceed 2 bits per base." Counted with masking case and gaps, it 'had' 2.62. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Universal compression. Some compressors (Lempel–Ziv, context-tree weighting) approach the entropy rate of any stationary source as the data grows, without knowing the source in advance. The price is the convergence speed of point 3: how much data they need depends on how complex the source is.
  • Guesswork and Rényi entropy. Erdal Arıkan (1996) showed that the moments of the number of guesses are governed by Rényi entropies (the exercises' "What the chapter leaves out"): the expected guesses grow like 2H1/2, the Rényi entropy of order ½, not like 2H.
  • Entropy of natural language at scale. Language models' cross-entropy keeps falling with more data and parameters, and nobody knows the floor; estimates of the entropy rate of English text are bounds, and the gap between the best model and the true rate is unknown.

Applying it

Code walkthrough

Python's secrets.randbelow(n) returns a uniformly random integer from 0 to n−1 using the operating system's generator, without the modulo bias of the exercises' P2. It calls SystemRandom._randbelow, which is this method from random.py in CPython 3.13 (on your computer: python3 -c "import random; print(random.__file__)"):

Python
    def _randbelow_with_getrandbits(self, n):
        "Return a random int in the range [0,n).  Defined for n > 0."

        getrandbits = self.getrandbits
        k = n.bit_length()
        r = getrandbits(k)  # 0 <= r < 2**k
        while r >= n:
            r = getrandbits(k)
        return r

with SystemRandom.getrandbits taking its bits from os.urandom:

Python
    def getrandbits(self, k):
        """getrandbits(k) -> x.  Generates an int with k random bits."""
        if k < 0:
            raise ValueError('number of bits must be non-negative')
        numbytes = (k + 7) // 8                       # bits / 8 and rounded up
        x = int.from_bytes(_urandom(numbytes))
        return x >> (numbytes * 8 - k)                # trim excess bits

The method draws k random bits, enough for numbers up to 2k−1≥n−1, and if the result is too big it simply draws again: rejection sampling. Every accepted value from 0 to n−1 was equally likely to be drawn, so the result is exactly uniform: no value gets an extra share, unlike byte % 10. The cost is extra draws: a draw is kept with probability n/2k, which is at least ½, so on average at most 2 draws are needed. Measured:

Python
import math, random
from collections import Counter

class Counting(random.SystemRandom):
    """SystemRandom, counting how many times getrandbits is called."""
    calls = 0
    def getrandbits(self, k):
        Counting.calls += 1
        return super().getrandbits(k)

g = Counting()
print(f"{'n':>6}{'bits drawn (k)':>15}{'chance a draw is kept':>23}{'draws per number, measured':>28}")
for n in (10, 64, 65, 100, 1000):
    Counting.calls = 0
    values = Counter(g._randbelow(n) for _ in range(100_000))
    k = n.bit_length()
    print(f"{n:>6}{k:>15}{n / 2**k:>23.3f}{Counting.calls / 100_000:>28.3f}")
counts = Counter(g._randbelow(10) for _ in range(1_000_000))
print("n = 10, a million draws:", " ".join(f"{d}:{counts[d] / 1e6:.4f}" for d in range(10)))
Text
     n bits drawn (k)  chance a draw is kept  draws per number, measured
    10              4                  0.625                       1.600
    64              7                  0.500                       1.998
    65              7                  0.508                       1.976
   100              7                  0.781                       1.280
  1000             10                  0.977                       1.024
n = 10, a million draws: 0:0.0995 1:0.1002 2:0.1004 3:0.1000 4:0.0998 5:0.0997 6:0.1004 7:0.1002 8:0.1001 9:0.0998

For n=10, 4 bits are drawn and 10 of the 16 values kept, so each number takes 1.6 draws on average; for 1,000, 10 bits and 98 % kept. The frequencies of a million draws below 10 are all within sampling noise of 0.1000.

Read it yourself

Using the code above: for n=64, the method draws 7 bits and keeps only half of the draws, though 6 bits would give exactly 64 equally likely values. Why does n.bit_length() give 7, and what would be a better choice of k? And why is it safe to throw away the rejected draws rather than, say, subtracting n from them?

Debugging drills

D1. A strength meter that likes "Password1!"

A sign-up form shows password strength in bits. It rates "Password1!" at 65.5 bits, stronger than a random 8-character password with symbols.

Python
import math, string

def strength_bits(password):
    pool = 0
    if any(c in string.ascii_lowercase for c in password): pool += 26
    if any(c in string.ascii_uppercase for c in password): pool += 26
    if any(c in string.digits for c in password): pool += 10
    if any(c in string.punctuation for c in password): pool += 32
    return len(password) * math.log2(pool)

for pw in ("Password1!", "Summer2026!", "correct horse battery staple", "kq7#Vz!m"):
    print(f"{pw!r:<32}{strength_bits(pw):6.1f} bits")
Text
'Password1!'                      65.5 bits
'Summer2026!'                     72.1 bits
'correct horse battery staple'   131.6 bits
'kq7#Vz!m'                        52.4 bits

D2. A 20-character token found in a few thousand guesses

A reset token is 20 characters from 36 symbols, about 103 bits by length. An attacker found one in about 2,400 guesses.

Python
import math, random, time

def reset_token(now):
    random.seed(int(now))                         # seeded with the time, to the second
    return "".join(random.choice("abcdefghijklmnopqrstuvwxyz0123456789") for _ in range(20))

issued_at = time.time() - 1234.5                  # a token issued about 20 minutes ago...
token = reset_token(issued_at)
# ...and an attacker who knows it was issued in the last hour tries every second
guesses = 0
for t in range(int(time.time()) - 3600, int(time.time()) + 1):
    guesses += 1
    if reset_token(t) == token:
        print(f"20-character token recovered after {guesses:,} guesses: {'match' if reset_token(t) == token else '?'}")
        break
print(f"the token looks like {len(token)} characters from 36 symbols ({20 * 5.17:.0f} bits), but there were only 3,601 possibilities ({math.log2(3601):.1f} bits)")
Text
20-character token recovered after 2,366 guesses: match
the token looks like 20 characters from 36 symbols (103 bits), but there were only 3,601 possibilities (11.8 bits)

D3. Infinite surprise

A language identifier gives an infinite score to "le droit à la vie" under the English and German models, and to "ça" under every model.

Python
import math
from pathlib import Path
from real import Blend

texts = {"English": "English-Latin1", "French": "French_Francais-Latin1", "German": "German_Deutsch-Latin1"}
models = {}
for lang, f in texts.items():
    t = " ".join(Path("data/udhr", f).read_bytes().decode("latin-1").lower().split())
    models[lang] = Blend(sorted(set(t)), 3)       # each model's alphabet: the characters in its own training text
    models[lang].train(t)

def bits(model, s):
    total = 0.0
    for i in range(len(s)):
        p = model.probs(s[max(0, i - 3):i]).get(s[i], 0.0)
        total += -math.log2(p) if p > 0 else math.inf
    return total / len(s)

for piece in ("the right to life", "le droit à la vie", "das recht auf leben", "straße", "ça"):
    print(f"{piece!r:<22}" + "  ".join(f"{l} {bits(m, piece):.2f}" for l, m in models.items()))
Text
'the right to life'   English 1.11  French 6.47  German 6.29
'le droit à la vie'   English inf  French 1.28  German inf
'das recht auf leben' English 5.04  French 5.76  German 1.13
'straße'              English inf  French inf  German 4.34
'ça'                  English inf  French inf  German inf

D4. DNA with 2.6 bits per base

A pipeline reports that a genome has 2.62 bits of order-0 entropy per base, more than the 2 bits four letters allow.

Python
from collections import Counter
from pathlib import Path
from real import entropy

dna = Path("data/chloroplast.txt").read_text().strip()
# The same genome as a database might deliver it: repeats "soft-masked" in lower case, and a gap of unknown bases
masked = dna[:84_000] + dna[84_000:110_000].lower() + "N" * 500 + dna[110_500:]
for name, s in (("as sequenced", dna), ("as delivered", masked)):
    c = Counter(s)
    print(f"{name:<13} symbols {''.join(sorted(c))}: order-0 entropy {entropy(list(c.values())):.4f} bits per base")
Text
as sequenced  symbols ACGT: order-0 entropy 1.9449 bits per base
as delivered  symbols ACGNTacgt: order-0 entropy 2.6206 bits per base

Career-oriented

Interview prep

Mid level

Q1. How would you generate a secure random token in Python, and what's wrong with random?

How to get there. Predictability, seeds, the secrets module.

Q2. What's the difference between Shannon entropy and min-entropy, and which should you use for passwords and keys?

How to get there. Average surprise against best guess.

Senior level

Q3. A product wants to show users "password strength". How would you implement it, and what would you avoid?

How to get there. Drill D1, NIST guidance, guess curves.

Q4. Your team needs to estimate how compressible a new kind of log data will be before choosing a storage format. How do you do it reliably?

How to get there. Upper bounds, sample size, the right model.

Staff level

Q5. A service generated API keys for two years with a library that, it turns out, seeded its generator from the process start time. How do you assess and handle it?

How to get there. Min-entropy of the seed, what an attacker can do, response.

Q6. Leadership asks whether the company should invest in training its own language model to compress its large text archives. How do you frame the decision?

How to get there. Cross-entropy as compression, costs of the model, alternatives.