Information TheoryComputer Science, Applied · Book 1
0 / 0

Shelves / Information Theory

IT·02

Counting Possibilities: Bits, Logarithms and Questions

How to count what a message could have been, and turn the count into bits: sequences (the multiplication principle), orderings (factorials) and choices (combinations); logarithms as the tool that turns those counts into information; fixed-length codes from the telegraph's 5-bit Baudot code to 7-bit ASCII; grouping symbols into blocks to waste fewer binary digits; question strategies as binary trees; and the information-theoretic reason no comparison sort can beat about n log₂ n comparisons, checked against Python's own sort.

26 topics · ~28 min read · 12-question quiz
Updated Suggest a correction

Start here

What this chapter answers

How many possible passwords, card hands, shuffles or lottery draws are there, and how many bits does each carry? Why does a code for 26 letters need 5 binary digits, and why does that waste some of them? How can you waste less without any probability at all? What do yes-or-no questions have to do with binary trees? And why can no sorting method that compares items do much better than nlog2n comparisons, however clever it is?

Counting in one picture

A café offers 3 mains, 4 drinks and 2 desserts, and a meal is one of each. To tell the kitchen which meal you want, you're picking one of 3×4×2=24 possibilities, so your order carries log224≈4.58 bits. The kitchen could number the 24 meals and you could send the number in 5 binary digits (25=32≥24). Or you could send the main in 2 digits, the drink in 2 and the dessert in 1, also 5. Both work; both "waste" a little, since 5 is more than 4.58. Counting the possibilities gives the information; rounding up to whole binary digits gives the cost of a fixed-length code. This chapter is about both numbers and the gap between them.

Counting possibilities

Sequences: the multiplication principle

If a first choice has a options and, whatever it was, a second has b, then the pair has a×b possibilities. Repeating this gives the multiplication principle: a sequence of n symbols, each chosen from an alphabet of k, has

k×k×⋯×k=kn

possibilities. A 4-digit PIN has 104; an 8-character password from the 94 printable keyboard symbols has 948≈6.1×1015; an IPv4 address of 32 binary digits has 232≈4.3 billion.

Because log2kn=nlog2k, the information in such a sequence is n times the information in one symbol: the password carries 8×log294≈52.4 bits. Information grows linearly with length while the number of possibilities grows exponentially, which is the whole reason a logarithm is the right measure.

Orderings: factorials

How many ways can n different things be put in order? The first place has n choices, the second n−1 (one thing is used), and so on down to 1:

n!=n×(n−1)×⋯×2×1.

Three people can queue in 3!=6 ways; a deck of 52 cards can be shuffled into 52!≈8.07×1067 orders, so a well-shuffled deck carries log252!≈225.6 bits. That number has a practical consequence: a card game that shuffles using a random number generator with a 32-bit seed can only ever produce 232 of those orders, a vanishing fraction, and anyone who learns the seed knows every card. A widely reported 1999 analysis of an online poker site did exactly that.

Choices: combinations

How many ways can you choose r things from n, when the order of choosing doesn't matter? Count ordered choices (n×(n−1)×⋯×(n−r+1)), then divide by the r! orders in which each set could have been picked:

(nr)=n!r!(n−r)!,

read "n choose r". A 5-card hand from 52 is one of (525) =2,598,960 (21.3 bits); a 6-from-49 lottery draw one of (496) =13,983,816 (23.7 bits, chapter 1's jackpot). These binomial coefficients come back in chapter 6: (nr) is the number of strings of n binary digits with exactly r ones, and its logarithm is how the source coding theorem is proved.

From counts to bits

Every count above becomes information through log2, and three rules (Mathematics Book 1, chapter 10) do almost all the work:

Rule In symbols What it means here
Products become sums log2(ab) =log2a+log2b Independent choices' bits add
Powers become multiples log2an=nlog2a n symbols carry n times one symbol's bits
Quotients become differences log2ab =log2a−log2b Ruling out possibilities subtracts bits

For estimates in your head, use 210=1024≈103: so log21000≈10, log2106≈20, log2109≈30, and log210≈3.32. A billion possibilities is about 30 bits; 8 billion is about 33.

Fixed-length codes

One symbol at a time

A fixed-length code gives every symbol of an alphabet a string of the same number of binary digits. With K symbols you need L digits where 2L≥K, so

L=⌈log2K⌉.

Baudot's 5 digits give 32 codes; ASCII's 7 give 128. Twenty-six capital letters need 5 (since 24=16<26≤32), and the 65 different bytes in the chapter's Shakespeare file need 7. Fixed-length codes are simple to decode: cut the stream every L digits, and each piece is a symbol. That's why machines use them.

The cost is the rounding. A letter from 26 equally likely ones carries log226≈4.70 bits, but the code spends 5: six of the 32 codes are never used, and 0.30 of a binary digit per letter is wasted. The efficiency of a code is information carried divided by digits spent: 4.70/5=94%. For decimal digits it's worse: each carries log210≈3.32 bits, but needs 4 binary digits, so 83 % efficiency (binary-coded decimal, used in old calculators and some financial hardware, pays exactly this).

Grouping symbols into blocks

The waste comes from rounding up once per symbol. Round up once per group instead. Three decimal digits have 103=1000 possibilities, which fit in 10 binary digits (210=1024): 103≈3.33 digits per decimal digit instead of 4, almost exactly log210≈3.32. In general, a block of m symbols from K needs ⌈mlog2K⌉ digits, and since the rounding loses less than one digit per block,

Interactive diagram: Packing decimal digits: one at a time or in blocks. It needs JavaScript; the text around it says the same.
log2K≤⌈mlog2K⌉m<log2K+1m.

So longer blocks get as close to log2K as you like. This is the first appearance of the most important trick in the book: coding many symbols together beats coding them one at a time. Chapter 6 uses it, with probabilities, to prove that entropy is the limit of compression. The lab shows that the improvement isn't steady: some block lengths fit a power of two much better than others.

Questions as trees

A strategy is a binary tree

Any plan of yes-or-no questions can be drawn as a binary tree. The root is the first question; its two branches lead to the next question for each answer; and each leaf is a point where the answer is known. Reading the answers along the path from the root to a leaf, writing 1 for yes and 0 for no, gives a string of binary digits that identifies that outcome: a codeword. So a question strategy and a code are the same thing. The number of questions to reach an outcome is the depth of its leaf, which is the length of its codeword.

A tree of depth d has at most 2d leaves, so a strategy that must distinguish N outcomes has some leaf at depth at least log2N: the chapter 1 bound, in a picture. A fixed-length code is a tree with all its leaves at the same depth. Chapter 5 will let the leaves sit at different depths, likely outcomes near the root, and that's how compression works.

The sorting lower bound

Sorting is a question game. A comparison sort learns about its input only by asking "is item i less than item j?", one yes-or-no question at a time, and it must end up knowing which of the n! possible orders the input was in (otherwise two inputs in different orders would be rearranged the same way, and one of them would come out unsorted).

Interactive diagram: Sorting three items: a tree of yes-or-no questions. It needs JavaScript; the text around it says the same.

How big is log2n!? Using Stirling's approximation n!≈2πn(n/e)n,

log2n!≈nlog2n−nlog2e+12log2(2πn)≈nlog2n−1.44n.

So every comparison sort needs about nlog2n comparisons, and merge sort, heap sort and Python's own sort achieve that, up to a small factor. This is why "O(nlogn)" is the speed limit you meet in algorithms courses (Software Engineering, Volume 1, chapter 4): it isn't a property of any particular algorithm but of the information a sort must gather, log2n! bits, one bit per comparison at best. Sorts that beat it, such as counting sort and radix sort, do so by asking questions with more than two answers (which bucket does this digit go in?).

Lab: counting, packing and sorting

Experiment 1: how many bits in everyday choices

Python
import math
cases = [("a 4-digit PIN", 10 ** 4),
         ("an 8-character password from 94 printable symbols", 94 ** 8),
         ("a hand of 5 cards from 52", math.comb(52, 5)),
         ("the order of a shuffled 52-card deck", math.factorial(52)),
         ("a 6-from-49 lottery draw", math.comb(49, 6)),
         ("an IPv4 address", 2 ** 32),
         ("an IPv6 address", 2 ** 128)]
for name, n in cases:
    print(f"{name:<52} {n:.4g} possibilities = {math.log2(n):7.2f} bits")
Text
a 4-digit PIN                                        1e+04 possibilities =   13.29 bits
an 8-character password from 94 printable symbols    6.096e+15 possibilities =   52.44 bits
a hand of 5 cards from 52                            2.599e+06 possibilities =   21.31 bits
the order of a shuffled 52-card deck                 8.066e+67 possibilities =  225.58 bits
a 6-from-49 lottery draw                             1.398e+07 possibilities =   23.74 bits
an IPv4 address                                      4.295e+09 possibilities =   32.00 bits
an IPv6 address                                      3.403e+38 possibilities =  128.00 bits

A PIN carries 13.3 bits and a random 8-character password 52.4; a 5-card hand 21.3 and a lottery draw 23.7. A shuffled deck carries 225.6 bits, more than an IPv6 address (128): there are more ways to shuffle a deck than there are IPv6 addresses, by a factor of about 1029.

Experiment 2: block coding gets closer to log₂ K

Python
import math
def best_block(k, max_len=12):
    """For an alphabet of k symbols, bits per symbol when coding blocks of length L with a fixed-length code."""
    rows = []
    for L in range(1, max_len + 1):
        bits = math.ceil(L * math.log2(k) - 1e-12)      # ceil(log2(k**L))
        assert 2 ** bits >= k ** L > 2 ** (bits - 1)
        rows.append((L, bits, bits / L))
    return rows
for name, k in (("decimal digits", 10), ("die rolls", 6), ("letters A-Z", 26)):
    rows = best_block(k)
    shown = ", ".join(f"{L}->{b / L:.3f}" for L, b, _ in rows if L in (1, 2, 3, 5, 10, 12))
    print(f"{name:<15} log2 {k} = {math.log2(k):.4f}; bits per symbol by block length: {shown}")
Text
decimal digits  log2 10 = 3.3219; bits per symbol by block length: 1->4.000, 2->3.500, 3->3.333, 5->3.400, 10->3.400, 12->3.333
die rolls       log2 6 = 2.5850; bits per symbol by block length: 1->3.000, 2->3.000, 3->2.667, 5->2.600, 10->2.600, 12->2.667
letters A-Z     log2 26 = 4.7004; bits per symbol by block length: 1->5.000, 2->5.000, 3->5.000, 5->4.800, 10->4.800, 12->4.750

One decimal digit at a time costs 4 binary digits; blocks of 3 cost 3.333 per digit (1000 in 1024), within 0.012 of log210. The improvement isn't monotone: blocks of 5 digits cost 3.4, worse than blocks of 3, because 105=100,000 sits just above 216=65,536 and needs 17 digits. Die rolls do best in blocks of 5 (65 =7,776≤8,192 =213, so 2.6 per roll against log26=2.585). The bound guarantees that as blocks lengthen, the cost falls below log2K+1m, but for a particular length the fit can be lucky or unlucky.

Experiment 3: Python's sort against the information limit

Python
import functools, math, random
random.seed(52)
class Counted:
    calls = 0
    def __init__(self, v): self.v = v
    def __lt__(self, other):
        Counted.calls += 1
        return self.v < other.v
for n in (10, 100, 1000, 10_000):
    xs = [Counted(random.random()) for _ in range(n)]
    Counted.calls = 0
    sorted(xs)
    bound = math.lgamma(n + 1) / math.log(2)        # log2(n!)
    print(f"n = {n:>6}: log2(n!) = {bound:>10,.0f}   Python's sort used {Counted.calls:>10,} comparisons   ratio {Counted.calls / bound:.3f}")
Text
n =     10: log2(n!) =         22   Python's sort used         25 comparisons   ratio 1.147
n =    100: log2(n!) =        525   Python's sort used        540 comparisons   ratio 1.029
n =   1000: log2(n!) =      8,529   Python's sort used      8,665 comparisons   ratio 1.016
n =  10000: log2(n!) =    118,458   Python's sort used    120,177 comparisons   ratio 1.015

Wrapping the items in a class that counts calls to < lets us count every comparison Python's built-in sort makes (math.lgamma(n + 1) is lnn!, divided by ln2 to give log2n!). On shuffled data, Python's sort uses only 1.5 % more comparisons than the information-theoretic minimum for 10,000 items: 120,177 against 118,458. No comparison sort can do better than the minimum in the worst case, and Python's comes within a whisker of it on random input. (On input that's already partly sorted, it uses far fewer, because such input carries less than log2n! bits of "which order is this?": chapter 4's entropy again.)

Experiment 4: a fixed-length code for Shakespeare

Python
import math
def pack(values, width):
    """Write each value in `width` binary digits, most significant first, into bytes."""
    out, acc, n = bytearray(), 0, 0
    for v in values:
        acc, n = (acc << width) | v, n + width
        while n >= 8:
            n -= 8
            out.append((acc >> n) & 0xFF)
        acc &= (1 << n) - 1
    if n:
        out.append((acc << (8 - n)) & 0xFF)      # pad the last byte with zeros
    return bytes(out)
def unpack(packed, width, count):
    values, acc, n, it = [], 0, 0, iter(packed)
    while len(values) < count:
        while n < width:
            acc, n = (acc << 8) | next(it), n + 8
        n -= width
        values.append((acc >> n) & ((1 << width) - 1))
        acc &= (1 << n) - 1
    return values
data = open("data/shakespeare.txt", "rb").read()
alphabet = sorted(set(data))
width = math.ceil(math.log2(len(alphabet)))
index = {b: i for i, b in enumerate(alphabet)}
packed = pack([index[b] for b in data], width)
restored = bytes(alphabet[i] for i in unpack(packed, width, len(data)))
print(f"{len(alphabet)} distinct bytes -> {width} binary digits each")
print(f"original {len(data):,} bytes, packed {len(packed):,} bytes ({8 * len(packed) / len(data):.3f} bits per byte)")
print("round trip exact:", restored == data)
Text
65 distinct bytes -> 7 binary digits each
original 1,115,394 bytes, packed 975,970 bytes (7.000 bits per byte)
round trip exact: True

The plays use 65 different byte values, so each fits in 7 binary digits. The program numbers the 65 symbols, writes each number in 7 digits into a stream of bytes (a bit writer), and reads them back: 1,115,394 bytes become 975,970, an exact round trip. Saving one digit in eight is all a fixed-length code can do here; chapter 1's lzma got to 2.6 bits per character by exploiting unequal frequencies and context, which fixed-length codes ignore. The bit writer itself is reused by every later chapter and by the capstone.

Worked examples

Counting and bits

A code for a keypad

The sorting bound for small n

Exercises

Practice

  1. How many 6-character strings are there from the lowercase letters and digits (36 symbols)? How many bits?
  2. In how many orders can 10 books be put on a shelf? How many bits is that?
  3. How many ways can a committee of 4 be chosen from 12 people? How many bits?
  4. How many binary digits does a fixed-length code need for: the 4 DNA bases; the 20 amino acids; the 128 ASCII characters; 1,000 product codes?
  5. Use 210≈103 to estimate log2 of 4 million and of 2 trillion.
  6. What's the efficiency of a fixed-length code for 20 equally likely amino acids, one at a time? In blocks of 3?
  7. What's the minimum worst-case number of comparisons to sort 6 items?
Answers
  1. 366=2,176,782,336; 6log236≈31.0 bits.
  2. 10!=3,628,800; log210!≈21.79 bits.
  3. (124)=495; log2495≈8.95 bits.
  4. 2; 5; 7; 10.
  5. 4×106≈22×220, so about 22 (exactly 21.93). 2×1012≈2×240, so about 41 (exactly 40.86).
  6. log220≈4.32 bits in 5 digits: 86.4 %. Blocks of 3: 203 =8000≤8192 =213, so 13 digits for 3 acids, 4.333 each: 99.7 %.
  7. ⌈log2720⌉ =10.

Harder

  1. Explain, using the multiplication principle, why (nr) =(nn−r), and why (n0)+(n1)+⋯+(nn) =2n.
  2. A website issues 6-digit verification codes that expire after 10 minutes and allows 5 attempts. What's an attacker's chance of guessing one code? How many bits of information does a code carry, and how many does the attacker effectively get to "try"?
  3. Show that log2n!≤nlog2n for every n≥1, without Stirling's formula. Then show it's at least n2log2n2.
  4. Why does counting sort, which sorts n numbers between 0 and 999 in about n+1000 steps, not contradict the sorting lower bound?
  5. A sensor sends readings 0 to 99 as two ASCII digits (16 binary digits). Propose a fixed-length code for blocks of readings that gets within 1 % of the information limit, and say how many readings per block.
Answers
  1. Choosing the r items to take is the same as choosing the n−r to leave, so the counts match. For the sum: each of the 2n subsets of n items (each item in or out, multiplication principle) has some size r, and there are (nr) subsets of each size.
  2. 5106=1 in 200,000. A code carries log2106≈19.93 bits; 5 guesses cover log25≈2.32 bits' worth of possibilities, leaving about 17.6 bits the attacker can't get through. (Their success chance is 2−17.6.)
  3. n! =1×2×⋯×n≤n×n×⋯×n =nn, so log2n!≤nlog2n. For the lower bound, the top half of the factors, from about n2 to n, are each at least n2, and there are at least n2 of them, so n!≥(n2)n/2. So log2n! is between n2log2n2 and nlog2n: it grows like nlogn.
  4. Counting sort doesn't learn about the input by comparisons. It asks "which of 1000 values is this?", a question with 1000 answers, worth up to log21000≈10 bits each, so n such questions can gather 10n bits, plenty for log2n! when n is moderate. The lower bound only applies to methods restricted to two-answer comparisons.
  5. Each reading carries log2100≈6.644 bits. Blocks of 3: 1003=106≤220, 20 digits for 3 readings, 6.667 each: 99.65 % efficiency. One reading at a time needs 7 (94.9 %); ASCII spends 16 (41.5 %).

Challenge

  1. Ralph Hartley's 1928 measure was H=nlogs for n symbols from an alphabet of s. A telegraph line sends 50 symbols a second from Baudot's 32-symbol alphabet. What's its rate in bits per second? If letters arrived with English frequencies instead of equally likely, would the true information rate be higher or lower, and why doesn't Hartley's measure see it?
Discussion

50×log232=250 bits per second. With English text, the symbols aren't equally likely (letters vary from 12 % to 0.07 %, chapter 1), and each depends on the ones before, so the information per symbol is less than log232=5 bits: perhaps 1 to 2 bits per letter with context (chapter 10 measures it). The line's capacity to carry information is 250 bits per second, but the English source fills only a fraction of it. Hartley's measure counts possibilities, as if all were equally likely; it measures the line, not the message. Shannon's entropy (chapter 4) measures the message, and the gap between the two is what compression recovers.

In real life

Misconceptions and limits

The model to keep

Common misconceptions

Misconception What's actually true Where it's shown
"Doubling a password's length doubles the number of passwords." It squares it; it doubles the bits. Sequences: the multiplication principle
"A code for K symbols needs log₂ K binary digits." One at a time it needs ⌈log2K⌉; only blocks approach log2K. Fixed-length codes
"Longer blocks always do better." Not always: decimal blocks of 5 cost more than blocks of 3. Experiment 2
"O(n log n) sorting is a fact about merge sort." It's a fact about the information any comparison sort must gather. The sorting lower bound
"Counting sort breaks the sorting lower bound." It asks questions with many answers, not comparisons. Harder exercise 11
"The information bound can always be achieved exactly." It's a floor: sorting 12 items needs 30 comparisons, not 29. Worked example, the sorting bound
"A random generator can produce any shuffle." Not if its seed has fewer than 226 bits. Orderings: factorials
"Fixed-length codes can compress text a lot." Only by the rounding: 8 to 7 bits for Shakespeare; compression needs probabilities. Experiment 4

Limits and trade-offs

  • Equally likely is an assumption. Counting gives the information only when every possibility is equally likely. Real messages aren't, and chapter 4's entropy replaces log2N with an average that weights each outcome by its probability.
  • Fixed-length codes trade size for simplicity. They can be decoded at any position (symbol i starts at digit iL), which variable-length codes can't; that random access is why databases and CPUs prefer them.
  • Blocks add delay and complexity. Coding 5 die rolls at once means waiting for 5 rolls before sending anything, and the encoder's tables grow as Km.

Revision sheet

Key ideas

  • Multiplication principle: n choices from k each give kn sequences; bits add: nlog2k.
  • Factorial: n! orders; log252!≈225.6 bits in a shuffled deck.
  • Combinations: (nr) =n!r!(n−r)! ways to choose r from n.
  • Estimating: 210≈103; log210≈3.32.
  • Fixed-length code: ⌈log2K⌉ digits per symbol; efficiency = log2K ÷ digits.
  • Blocks: m symbols in ⌈mlog2K⌉ digits; under log2K+1m per symbol.
  • Question strategies are binary trees; a codeword is the path; depth = questions.
  • Sorting bound: any comparison sort needs ⌈log2n!⌉≈nlog2n−1.44n comparisons in the worst case.
  • Stirling: n!≈2πn(n/e)n.

Glossary

  • Multiplication principle: if one choice has a options and a second has b whatever the first was, together they have a×b.
  • Factorial: n! =n×(n−1)×⋯×1, the number of orders of n different things.
  • Binomial coefficient: (nr), the number of ways to choose r things from n when order doesn't matter.
  • Fixed-length code: a code giving every symbol a codeword of the same number of binary digits.
  • Codeword: the string of symbols a code assigns to one message or symbol.
  • Code efficiency: the information a code carries per symbol divided by the binary digits it spends per symbol.
  • Block coding (of a source): encoding several source symbols together as one, so rounding costs less per symbol.
  • Bit writer: code that packs values of any number of binary digits into a stream of bytes, and its reader unpacks them.
  • Decision tree: a binary tree drawing a strategy of yes-or-no questions, with an outcome at each leaf.
  • Comparison sort: a sorting method that learns about its input only by comparing pairs of items.
  • Sorting lower bound: the fact that any comparison sort needs at least ⌈log2n!⌉ comparisons in the worst case.
  • Stirling's approximation: n!≈2πn(n/e)n, so log2n!≈nlog2n−1.44n.
  • ASCII: the American Standard Code for Information Interchange (1963), a 7-bit fixed-length code for 128 characters.