Kayavak

Kayavak / Deeper / Derivations

Deeper · Derivations

Results rebuilt from first principles

Results you can reconstruct instead of memorising, with every step justified by the one before. 42 chapters so far. Also: Comparisons · What if? · Origins. To change the numbers yourself, try the what-if calculators.

CS·02 Programming Fundamentals & Paradigms

Foundations of Computing

Why a recursive function terminates. Take a function that calls itself only on smaller inputs, with a base case.

  1. Give each input a measure: a natural number, like the length of a list or the value of n.
  2. Every recursive call is made on an input whose measure is strictly smaller. (This is what "progress toward the base case" means; check it in the code.)
  3. Natural numbers can't decrease forever: any strictly decreasing sequence of them is finite.
  4. So every chain of calls reaches an input with no recursive call, the base case, and returns.

The same argument, read the other way, is mathematical induction (chapter 5): if the base case is right and each call is right assuming the smaller calls are, the function is right for every input.

CS·03 Data Structures

Foundations of Computing

Why doubling makes append amortised O(1).

  1. Start with capacity 1 and double whenever the array is full. Appending n items triggers copies when the size reaches 1, 2, 4, …, up to the largest power of two below n.
  2. Each resize copies every current element: 1 + 2 + 4 + … + 2ᵏ where 2ᵏ < n.
  3. That geometric sum equals 2ᵏ⁺¹ − 1, which is less than 2n.
  4. So n appends cost n writes plus fewer than 2n copies: under 3n operations, a constant per append on average.
  5. Any growth factor r > 1 gives the same shape, with total copying under n/(r − 1); a fixed increment doesn't, because the sum 10 + 20 + … grows with the square of n.

CS·04 Algorithms

Foundations of Computing

Why no comparison sort can beat n log n.

  1. A comparison sort learns about the input only by asking "is a < b?". Draw every possible run as a binary tree: each inner node is a comparison, each leaf an output order.
  2. The input could be any of the n! orderings of n distinct items, and each needs a different leaf, so the tree has at least n! leaves.
  3. A binary tree of height h has at most 2ʰ leaves, so 2ʰ ≥ n!, which gives h ≥ log₂(n!).
  4. The height is the worst-case number of comparisons. And log₂(n!) = log₂ 1 + log₂ 2 + … + log₂ n; the last n/2 terms are each at least log₂(n/2), so the sum is at least (n/2) log₂(n/2), which grows like n log n.
  5. So every comparison sort needs Ω(n log n) comparisons in the worst case. Counting and radix sort escape the bound by not comparing: they use the keys' digits as addresses.

CS·05 Discrete Mathematics

Foundations of Computing

The birthday bound: why collisions come so early.

  1. Put k items into N equally likely buckets. The chance the second avoids the first is 1 − 1/N, the third avoids both is 1 − 2/N, and so on.
  2. So P(no collision) = (1 − 1/N)(1 − 2/N)…(1 − (k−1)/N).
  3. For small x, 1 − x ≈ e⁻ˣ. Multiplying the approximations adds the exponents: P ≈ e^−(1 + 2 + … + (k−1))/N = e^−k(k−1)/(2N).
  4. Set this to ½ and solve: k(k−1) ≈ 2N ln 2, so k ≈ √(2 ln 2 · N) ≈ 1.18 √N.
  5. For birthdays, N = 365 gives k ≈ 22.5, so 23 people. For a 32-bit hash, N = 2³² gives k ≈ 77,000: the same numbers the chapter quotes. Collisions arrive near √N, not N.

CS·06 Number Systems & Data Representation

Foundations of Computing

Why "invert and add one" negates a two's complement number.

  1. In n bits, arithmetic wraps around modulo 2ⁿ, so −x is whatever value y makes x + y = 0 modulo 2ⁿ, that is, y = 2ⁿ − x.
  2. Inverting every bit of x gives ~x, and x + ~x is all ones, which is 2ⁿ − 1 (every column adds 1 + 0, with no carry).
  3. Rearranging: ~x = 2ⁿ − 1 − x, so ~x + 1 = 2ⁿ − x, which is exactly −x.
  4. A consequence: the most negative value, −2ⁿ⁻¹, has no positive partner in n bits; negating it gives itself back. In Java, Math.abs(Integer.MIN_VALUE) is negative for this reason.

CS·07 Computer Architecture

Foundations of Computing

Average memory access time. Each access first tries the cache; misses go on to memory.

  1. Every access pays the cache's hit time, say 1 ns.
  2. A fraction of accesses miss (the miss rate, say 5%) and each pays an extra miss penalty, say 100 ns.
  3. So the average is AMAT = hit time + miss rate × miss penalty = 1 + 0.05 × 100 = 6 ns.
  4. Without the cache every access costs 100 ns: the cache makes memory look about 16 times faster, even though it misses one access in twenty.
  5. The formula nests: an L2 miss penalty is itself an AMAT of L3 and memory. And it shows why a miss rate going from 2% to 10%, often just a change of traversal order, multiplies average cost.

CS·08 Operating Systems

Foundations of Computing

Why page tables have several levels.

  1. x86-64 uses 48-bit virtual addresses (in its common 4-level mode) and 4 KB pages. A 4 KB page covers 2¹² addresses, so there are 2⁴⁸ / 2¹² = 2³⁶ possible pages.
  2. A flat table with one 8-byte entry per page would need 2³⁶ × 8 bytes = 512 GB, per process. Impossible.
  3. Most of the address space is unused, so split the 36 page-number bits into four groups of 9. Each group indexes a table of 2⁹ = 512 entries × 8 bytes = 4 KB: exactly one page.
  4. Only the tables covering addresses actually in use need to exist. A small process needs a handful of 4 KB tables, not 512 GB.
  5. The price is four memory lookups per translation, which is why the TLB caches recent translations (chapter 7), and why large pages (2 MB, 1 GB), which skip levels, help programs with huge memory.

CS·09 Networking Fundamentals

Foundations of Computing

How big a TCP window must be to fill a link.

  1. TCP can have at most one window of unacknowledged data in flight; it then waits for acknowledgements, which take one round trip.
  2. So the best throughput is window ÷ RTT.
  3. To fill a link of bandwidth B, the window must be at least B × RTT: the bandwidth-delay product.
  4. Mumbai to London is about 72 ms round trip. To fill 100 Mbit/s: 100 × 10⁶ bit/s × 0.072 s = 7.2 Mbit, about 900 KB in flight.
  5. The original TCP header allows a window of only 64 KB: 64 KB ÷ 72 ms ≈ 7 Mbit/s, whatever the link speed. That's why the window-scaling option (RFC 1323, 1992) exists, and why long, fast paths still need tuned buffers.

CS·10 Compilers & Runtimes

Foundations of Computing

Why a generational garbage collector is cheap.

  1. A copying collector moves the live objects to a fresh area and discards the rest wholesale, so its cost is proportional to the live data, not to the space being reclaimed.
  2. Observation (the weak generational hypothesis): most objects die young. Temporary strings, iterators and request objects become garbage almost immediately.
  3. So allocate new objects in a small "young" area and collect it often. If, say, 95% of it is dead each time, the collector copies only 5% and reclaims the rest for free.
  4. Objects that survive several collections are moved to an "old" area that is collected rarely.
  5. The catch: old objects can point to young ones, so the collector must track those pointers (a write barrier and a remembered set), or it would free young objects still in use. That bookkeeping is the price of the speed.

BE·36 Generics and Type Parameters

The Backend

Why generic types must be invariant if they're mutable.

  1. Suppose List<Dog> were a subtype of List<Animal>.
  2. Then List<Animal> animals = dogs; would compile, where dogs is a List<Dog>.
  3. animals.add(new Cat()) type-checks: a Cat is an Animal.
  4. But animals and dogs are the same list, so Dog d = dogs.get(0) now returns a Cat: the type system has been broken.
  5. So a mutable container can only be covariant (step 2) if it's read-only, and only contravariant if it's write-only. Java makes generics invariant and lets each use choose with wildcards; Kotlin and C# let declarations choose (out T, in T).

BE·38 Concurrency

The Backend

Amdahl's law: why more cores give diminishing returns.

  1. Let a program take time 1 on one core, of which a fraction p can run in parallel and 1 − p can't.
  2. On n cores the parallel part takes p/n; the serial part still takes 1 − p.
  3. Speedup = 1 / ((1 − p) + p/n).
  4. As n grows without limit, p/n goes to zero, so speedup approaches 1 / (1 − p).
  5. If 95% is parallel, no number of cores gives more than 20× (1 / 0.05). The serial 5% (a lock everyone takes, a single-threaded step) sets the ceiling, which is why reducing contention often matters more than adding cores.

BE·41 Memory and Performance

The Backend

Little's law: how many requests are in a system.

  1. Let requests arrive at an average rate λ per second, and each stay an average W seconds.
  2. Plot, over a long period T, how many requests are inside at each moment. The area under that curve is the total request-seconds spent inside.
  3. Counted per request, the same area is roughly (number of requests) × W = λT × W.
  4. The average number inside, L, is that area divided by T: L = λW.
  5. So a service handling 2,000 requests per second at 50 ms each has about 100 in flight at any moment, which sizes thread pools, connection pools and queues. If latency rises to 500 ms at the same rate, 1,000 are in flight: one reason slow dependencies exhaust pools.

BE·43 Build Systems

The Backend

Why a build graph can be run in an order at all, and which order.

  1. Make each task a node and draw an edge from A to B when B needs A's output.
  2. A valid order runs every task after all its inputs: a topological order of the graph.
  3. Such an order exists exactly when the graph has no cycle. If A needs B and B needs A, no order works, which is why build tools reject circular dependencies between modules.
  4. Kahn's algorithm finds one: repeatedly run any task with no unfinished inputs. Tasks that become ready at the same time are independent, so they can run in parallel.
  5. When a source file changes, only tasks reachable from it in the graph need re-running; everything else is up to date.

BE·52 Resilience

The Backend

Retry amplification.

  1. A request passes through three services, A → B → C, and each layer makes up to 3 attempts on failure.
  2. If C fails every time, B makes 3 calls to C for each call it receives.
  3. A makes 3 calls to B for each request, and each of those makes 3 calls to C: 3 × 3 = 9 calls to C.
  4. If the client in front of A also retries 3 times, C receives 3 × 3 × 3 = 27 calls per user action.
  5. In general, with r attempts at each of k layers, the bottom sees rᵏ attempts. Load on the failing service multiplies exactly when it is failing, which is why retries belong at one layer and need a budget.

BE·53 Caching

The Backend

How much a cache actually saves.

  1. Let a cache hit cost h, a miss cost m (the source's latency plus the cache lookup), and the hit rate be p.
  2. Average latency = p·h + (1 − p)·m.
  3. With h = 1 ms, m = 50 ms: at p = 0.9 the average is 0.9 + 5 = 5.9 ms; at p = 0.99 it's 0.99 + 0.5 ≈ 1.5 ms.
  4. Load on the source scales with 1 − p: going from 90% to 99% hits cuts source load tenfold.
  5. So the last few percent of hit rate matter far more than they look, both for latency and for how much the source must handle, and a fall from 99% to 90% (after a deploy flushes the cache, say) multiplies source load by ten.

DB·55 The Relational Model

Databases

When splitting a table loses nothing (Heath's theorem).

  1. Take a table R with attributes X, Y and Z, and split it into R1(X, Y) and R2(X, Z). Joining them back on X gives every original row, and possibly extra rows that were never there.
  2. Suppose X → Y: each X value determines exactly one Y.
  3. Joining R1 and R2 on a given x pairs every (x, y) row with every (x, z) row. But there's only one y for that x, so each (x, z) gets exactly the y it originally had.
  4. So the join produces exactly the original rows: the decomposition is lossless.
  5. Without the dependency, an x with two y values and two z values would join into four rows where there were two: spurious data. That's why normalisation splits tables along functional dependencies, and only along them.

DB·58 Storage Engine Internals

Databases

Why a B-tree is so shallow.

  1. An 8 KB page holding keys of about 16 bytes plus pointers fits roughly 400–500 entries, so each inner node has a fan-out f of about 500.
  2. A tree of height h can reach f^h leaves: 500¹ = 500, 500² = 250,000, 500³ = 125 million, 500⁴ = 62.5 billion.
  3. So four or five levels cover billions of rows, and finding any row means reading that many pages.
  4. The top levels are a tiny fraction of the tree (one root, a few hundred second-level pages) and stay in memory, so in practice a lookup costs one or two disk reads.
  5. A binary tree over the same billion rows would be about 30 levels deep, 30 random reads: the high fan-out is the whole trick.

DB·60 Query Optimisation

Databases

Why the optimiser can't try every join order, and how it copes.

  1. Joining n tables one at a time in a chain (a left-deep plan) can be done in n! orders: 5 tables give 120, 10 give 3,628,800, 15 give over a trillion.
  2. Trying them all is impossible beyond a handful of tables. Selinger's insight: the best plan for joining a set S of tables doesn't depend on how you'll use the result later (apart from its sort order).
  3. So compute the best plan for every subset of tables, building larger subsets from smaller ones: dynamic programming. There are 2ⁿ subsets, not n! orders: 1,024 for 10 tables.
  4. Even 2ⁿ grows too fast eventually, so PostgreSQL switches to a randomised genetic search above a threshold (12 tables by default).
  5. The search is exact only given the estimates: a perfect search over wrong cardinalities still finds a wrong plan.

DB·61 Scaling Databases

Databases

How much data moves when you add a node.

  1. With hash mod N, a key stays put only if its hash gives the same remainder mod N and mod N + 1.
  2. For a uniformly random hash, that happens for about 1 key in N + 1 (the remainders agree only when the hash falls in a matching residue), so about N/(N + 1) of keys move: 80% going from 4 to 5 nodes.
  3. With consistent hashing, nodes own arcs of a ring of hash values. A new node takes over parts of existing arcs, and only the keys in those parts move.
  4. With balanced arcs, the new node should own 1/(N + 1) of the ring, so only about that share of keys moves: 20% from 4 to 5.
  5. Virtual nodes (many small arcs per server) keep the arcs balanced, so the movement is close to that ideal and spread across all existing servers.

AN·01 Start Here: What Numbers Are

Arithmetic and Numbers

Why a×(b+c) =a×b+a×c for whole numbers.

  1. a×(b+c) is a rows, each holding b+c objects (multiplication as rows of a rectangle).
  2. Draw a vertical line in each row after the first b objects. Every row now splits into a part of b and a part of c, and the line runs straight down the whole rectangle.
  3. The left of the line is a rows of b: a×b objects. The right is a rows of c: a×c.
  4. Drawing a line moves nothing, so the total is unchanged: a×(b+c) =a×b+a×c.
  5. The argument uses only whole rows and whole objects. For fractions it needs areas instead (chapter 6), and for negative numbers a definition that keeps the rule true (chapter 9).

AN·02 Place Value and Bases

Arithmetic and Numbers

Why every number has at most one base-b numeral.

  1. Suppose a number n is written two ways: n =dkbk+⋯+d1b+d0 =embm+⋯+e1b+e0, with every digit between 0 and b−1.
  2. Every term except the last is a multiple of b, so n =b×(something)+d0 and also n =b×(something else)+e0.
  3. Both d0 and e0 are between 0 and b−1, so each is the remainder of n on division by b; the division algorithm (chapter 4) says there's only one such remainder. So d0=e0.
  4. Subtract it and divide by b: the remaining digits of both numerals now write the same smaller number, (n−d0)/b.
  5. Repeat. At every step the digits agree, and the numbers shrink, so the process ends with the two numerals identical. The bound 0≤di<b is used in step 3 and nowhere else; drop it and uniqueness fails.

AN·03 Adding and Subtracting, and Why the Methods Work

Arithmetic and Numbers

Why, when adding n numbers, no carry is ever more than n−1.

  1. Each column holds n digits, each at most 9, so its digits sum to at most 9n.
  2. Suppose the carry into this column is at most n−1. Then the column total is at most 9n+n−1=10n−1.
  3. The carry out is the column total's tens part (the quotient on dividing by 10). Since the total is less than 10n, the quotient is at most n−1.
  4. The first column has no carry in (0, which is at most n−1), so step 2's assumption holds there; step 3 then gives it for the next column, and so on along the whole number. This is induction.
  5. With n=2: carries are at most 1. With n=3: at most 2. The bound is reached, for example by adding 99…9 to itself n times.

AN·04 Multiplying and Dividing

Arithmetic and Numbers

Why Karatsuba's method takes about n1.585 steps.

  1. To multiply two n-digit numbers, split each into halves of n/2 digits: a=a110m+a0, b=b110m+b0.
  2. The product is a1b1102m+(a1b0+a0b1)10m+a0b0. Done directly that needs four half-size products.
  3. Karatsuba computes the middle coefficient as (a1+a0)(b1+b0)−a1b1−a0b0, reusing the two outer products, so three half-size products are enough (plus additions, which cost only about n steps).
  4. Apply the same trick to each half-size product, and again, k=log2n times, until the pieces are single digits. At each level the number of products triples, so the bottom level has 3k single-digit products.
  5. 3log2n =nlog23≈n1.585, against 4log2n=n2 for the school method. The additions at each level don't change this growth rate. For 256 digits that's a few thousand products against 65,536, as the chapter's lab counted.

AN·05 Factors, Multiples and Primes

Arithmetic and Numbers

Why a prime dividing a product must divide one of the factors, from Euclid's algorithm.

  1. Run Euclid's algorithm backwards. For 1071 and 462: 1071=2×462+147, 462=3×147+21, 147=7×21.
  2. Rewrite the last useful line as 21=462−3×147, then replace 147 using the first line: 21 =462−3×(1071−2×462) =7×462−3×1071.
  3. The same steps work for any pair, so the gcd of a and b can always be written as as+bt for some whole numbers s and t (one of them negative). This is Bézout's identity.
  4. Now let a prime p divide a×b but not a. The only factors of p are 1 and p, so gcd(p,a)=1, and step 3 gives 1=ps+at.
  5. Multiply by b: b=pbs+abt. The prime p divides pbs and it divides ab, so it divides the right-hand side, which is b.
  6. Uniqueness of factorisation follows: if two factorisations differed, a prime from one would divide the product of the other, so by step 5 it would divide (and so equal) one of its primes; cancel it and repeat.

AN·06 Fractions

Arithmetic and Numbers

Why ordinary addition gives the same answer whichever form you use.

  1. Suppose ab and a′b′ are the same fraction, so ab′=a′b (the chapter's test), and add each to cd.
  2. The two sums are ad+bcbd and a′d+b′cb′d. They're equal exactly when the cross-products are equal: (ad+bc)b′d and (a′d+b′c)bd.
  3. Expand: the first is ab′d2+bb′cd; the second is a′bd2+bb′cd.
  4. The second terms are identical, and the first terms are equal because ab′=a′b (step 1). So the sums are equal: addition is a rule about numbers, not about the particular pairs.
  5. Try the same with the mediant, a+cb+d against a′+cb′+d. Nothing in step 1 forces them to match, and they don't: 12 and 24 with 13 give 25 and 37, and 2×7 =14≠15 =5×3. Addition works because every term of the cross-products carries the equal products ab′ and a′b, or the same term twice; the mediant's don't. So the mediant depends on the pairs, which is why it's right for records and wrong for amounts.

AN·07 Decimals and Percentages

Arithmetic and Numbers

How many decimal places a fraction that ends has.

  1. Take ab in lowest terms with b=2m×5n (the only kind that ends, by the chapter's theorem).
  2. A decimal with k places is a whole number over 10k=2k×5k. For ab to be written that way, b must divide 10k, so k≥m and k≥n.
  3. Take k=max(m,n) and multiply top and bottom by 2k−m×5k−n: the bottom becomes 10k, so k places are enough.
  4. Fewer won't do: with k−1 places the bottom 10k−1 lacks a factor 2 or a factor 5 that b needs, and since a shares no factor with b, it can't make up for it.
  5. So ab has exactly max(m,n) decimal places. Check: 340, with 40=23×5, has 3 places (0.075); 7125 =753 has 3 (0.056); 11024 =1210 has 10 (0.0009765625).

AN·08 Ratio, Proportion and Rates

Arithmetic and Numbers

Why combining two groups gives a rate between the groups' rates, and when it can reverse a comparison.

  1. A group with a successes out of b has rate ab; another, c out of d, has rate cd. Combined, the rate is the mediant a+cb+d.
  2. Rewrite it as a weighted average: a+cb+d =bb+d·ab+db+d·cd, since the first term is ab+d and the second cb+d.
  3. The weights bb+d and db+d are positive and add to 1, so the combined rate lies between the two group rates (chapter 6's mediant property, now with its weights visible).
  4. Now compare two options, each combining a "small" and a "large" group. Each option's overall rate is a weighted average of its own two group rates, with weights given by its own split between the groups.
  5. If option A has the higher rate in both groups but puts most of its weight on the group where rates are low, and option B puts most of its weight on the group where rates are high, A's average can be the lower one. With the same weights for both, the higher group rates must give the higher average (the chapter's challenge exercise), so a reversal needs different splits.

AN·09 Negative Numbers

Arithmetic and Numbers

Why two's complement addition gives the right signed answer whenever that answer fits.

  1. With n bits, store an integer x in range (−2n−1≤x<2n−1) as c(x)=xmod2n, the floored remainder, which is between 0 and 2n−1.
  2. The hardware adds two codes as unsigned numbers and keeps n bits: it computes (c(x)+c(y))mod2n.
  3. Remainders add (chapter 5): (c(x)+c(y))mod2n =(x+y)mod2n =c(x+y), provided x+y is itself in range, so that its code is defined by step 1.
  4. So the stored result is exactly the code of the true sum, and reading it as signed gives x+y. No step looked at signs.
  5. If x+y is out of range, the hardware still produces (x+y)mod2n, which reads as x+y±2n: that's overflow, and it happens exactly when two numbers of the same sign give a result of the other sign, which is how processors detect it.

AN·10 Powers, Roots, Scientific Notation and Logarithms

Arithmetic and Numbers

Why (1+1n)n increases with n and stays below 3.

  1. Expand by the binomial theorem: (1+1n)n =∑k=0n(nk)1nk, and each term is 1k!·nn·n−1n⋯n−k+1n.
  2. Rewrite the factors as 1·(1−1n)⋯(1−k−1n). Each is less than 1, and each grows when n grows. So every term grows with n, and a larger n adds more (positive) terms: the whole expression increases.
  3. Each term is at most 1k!, so the total is at most 1+1+12!+13!+⋯.
  4. Since k!≥2k−1, that's at most 1+1+12+14+⋯ =1+2 =3 (a geometric series, the household capstone's stage 10).
  5. An increasing sequence that never passes 3 approaches some limit (a property of the real numbers, chapter 12): that limit is e≈2.71828, and the exercises' P4 watched compounding approach it.

AN·11 Estimation, Rounding, Error and Units

Arithmetic and Numbers

Why, for small relative errors, the relative error of a product is about the sum of the inputs' relative errors.

  1. Write the measured values as a(1+ρa) and b(1+ρb), where ρa and ρb are the relative errors (positive or negative).
  2. Their product is ab(1+ρa)(1+ρb) =ab(1+ρa+ρb+ρaρb) by distributivity.
  3. So the product's relative error is ρa+ρb+ρaρb.
  4. If |ρa| and |ρb| are at most 1 % (0.01), the extra term ρaρb is at most 0.0001, a hundred times smaller than either: negligible. So the relative error is about ρa+ρb, at most |ρa|+|ρb|.
  5. For a power, an, the same argument with n equal factors gives about nρa: a 1 % error in a length is about a 2 % error in an area and 3 % in a volume (chapter 10's k2 and k3 again).

AN·12 The Real Number Line

Arithmetic and Numbers

Why every nest of shrinking intervals of decimals pins down exactly one decimal (a sketch of completeness).

  1. Take intervals [a1,b1]⊇[a2,b2]⊇⋯ whose widths shrink to zero, such as the bisection intervals for 2.
  2. For each number of decimal places k, the widths eventually fall below 10−k. After that, all the intervals agree on the first k decimal places of their points (allowing for the 0.4999… = 0.5 ambiguity, which only affects numbers that end).
  3. Define a decimal c by taking, for each k, the kth digit that the late intervals agree on. This is an infinite decimal, so it's a real number.
  4. c lies in every interval: if it were outside [an,bn], it would differ from that interval's points by some fixed amount, but by step 2 it agrees with later (smaller) intervals' points to any number of places.
  5. There can't be two such numbers c≠d: they'd differ by some fixed amount, and once the widths are smaller than that, no interval contains both. So exactly one real number lies in all the intervals. In the fractions, step 3 can produce a non-repeating decimal, which is no fraction: the gap.

IT·01 Start Here: What Information Is

Information Theory

Why log2N questions are needed, and enough, to pick one of N possibilities.

  1. A yes-or-no question splits the remaining possibilities into two groups: those for which the answer is yes, and those for which it's no.
  2. Whatever the answer, at least one group has at least half the possibilities. In the worst case you're left with that group.
  3. So after k questions, in the worst case at least N/2k possibilities remain. To be sure of one, you need N/2k≤1, that is, 2k≥N, so k≥log2N: no strategy can do it in fewer.
  4. Halving questions ("is it in the first half?") achieve it: each leaves at most half (rounded up), so after ⌈log2N⌉ questions one possibility remains.
  5. So the worst case needs exactly ⌈log2N⌉ questions, and log2N is the information in the answer. For a million, that's 20 (the chapter's lab checked every secret).

IT·02 Counting Possibilities: Bits, Logarithms and Questions

Information Theory

Why log2n! is about nlog2n−1.44n, without Stirling's formula.

  1. log2n! =log21+log22+⋯+log2n, because the logarithm of a product is the sum of the logarithms.
  2. The sum is close to the area under the curve log2x from 1 to n: each term log2k is the area of a strip of width 1 and height log2k, and the curve rises slowly.
  3. That area is ∫1nlog2xdx =1ln2[xlnx−x]1n =nlog2n−n−1ln2.
  4. Since 1ln2 =log2e≈1.443, this is nlog2n−1.443(n−1).
  5. The strips overshoot the curve a little (by less than log2n in total), which is the 12log2(2πn) correction in Stirling's formula. For n=10,000: 10,000×13.288−14,427≈118,450, against the exact 118,458 in the chapter's lab.

IT·03 The Probability You Need

Information Theory

Why a 50 % chance of a collision among random b-bit values arrives after about 1.18×2b/2 values.

  1. With M equally likely values, the chance that the kth value avoids the k−1 before it is 1−k−1M, so all n are different with probability ∏k=1n(1−k−1M) (the product rule).
  2. For small x, 1−x≈e−x, so the product is about e−(0+1+⋯+(n−1))/M =e−n(n−1)/2M, because a product of exponentials is the exponential of the sum.
  3. That's close to e−n2/2M when n is large, so P(collision)≈1−e−n2/2M.
  4. Setting it to 12: e−n2/2M=12, so n22M=ln2 and n =2ln2·M≈1.177M.
  5. With M=2b, that's 1.177×2b/2: about 77,000 for 32 bits and 5 billion for 64, as the chapter's lab computed. For M=365 it gives 22.5, so 23 people.

IT·04 Entropy: the Average Surprise of a Source

Information Theory

Why grouping forces the logarithm, for equally likely outcomes.

  1. Let A(n) be the uncertainty of n equally likely outcomes. Shannon asked that A grow with n and that grouping hold.
  2. Take nk equally likely outcomes and group them into n groups of nk−1. Grouping says A(nk)=A(n)+A(nk−1): choose the group, then the outcome within it (each group equally likely, so the second stage always costs A(nk−1)). Repeating, A(nk)=kA(n).
  3. For any s and t at least 2 and any large m, pick k with sk≤tm<sk+1. Because A grows, kA(s)≤mA(t)<(k+1)A(s), so A(t)A(s) lies between km and k+1m.
  4. Taking logarithms of the same inequality, logtlogs lies between the same two bounds. So |A(t)A(s)−logtlogs|≤1m for every m: the two ratios are equal.
  5. So A(n)=clogn for a constant c>0. Grouping unequal probabilities as fractions of equally likely outcomes then gives H=−c∑plogp (continuity covers probabilities that aren't fractions).

IT·05 Codes: Prefix Codes, Kraft's Inequality and Huffman Coding

Information Theory

Why Huffman's average length is the sum of the merged weights.

  1. Each time Huffman merges two trees of weights a and b, every symbol in them moves one level deeper, so their codewords each gain one digit.
  2. The symbols in the merged trees have total probability a+b, so the average codeword length grows by exactly a+b at that merge.
  3. Starting from depth 0 for every symbol, the final average length is therefore the sum of the weights of all the merged nodes, the internal nodes of the tree, excluding none: L¯ =∑internal nodesw.
  4. Check on 12,14,18,18: merges create weights 14, 12 and 1, which add to 1.75, the average length found in the chapter.
  5. This gives a quick way to compute a Huffman code's cost without writing a single codeword, and it's why a priority queue of weights is all the algorithm needs.

IT·06 The Source Coding Theorem: Why Entropy Is the Limit

Information Theory

Why an arithmetic code needs at most ⌈log21P⌉+1 digits for a message of probability P.

  1. After coding, the message owns an interval [L,L+P) of width P inside [0,1).
  2. Let k =⌈log21P⌉+1, so 2−k≤P2. Binary fractions with k digits are spaced 2−k apart.
  3. Take the smallest k-digit fraction c≥L; then c<L+2−k. The whole range of numbers that start with those k digits is [c,c+2−k), which ends below L+2·2−k≤L+P: inside the interval.
  4. So the k digits identify the interval unambiguously, whatever digits might follow them, and the decoder recovers the message (given its length).
  5. The cost is k<log21P+2: the message's total surprise plus less than 2 digits, however long the message.

IT·07 Joint and Conditional Entropy, Mutual Information

Information Theory

Why the chain rule for mutual information gives the data processing inequality.

  1. The chain rule for entropy, applied to conditional entropies, gives a chain rule for mutual information: I(X;Y,Z) =I(X;Y)+I(X;Z∣Y): the information that Y and Z together carry about X is what Y carries plus what Z adds once Y is known.
  2. The same quantity can be expanded in the other order: I(X;Y,Z) =I(X;Z)+I(X;Y∣Z).
  3. In a Markov chain X→Y→Z, once Y is known, Z is independent of X, so I(X;Z∣Y)=0.
  4. Setting the two expansions equal: I(X;Y) =I(X;Z)+I(X;Y∣Z).
  5. Conditional mutual information is never negative, so I(X;Z)≤I(X;Y), with equality exactly when Z keeps everything Y knew about X (a "sufficient statistic").

IT·08 Channels and Noise

Information Theory

Why Hamming codes are perfect.

  1. A code of length n that corrects one error needs every codeword's "ball", the codeword and its n neighbours one flip away, to be separate: n+1 blocks per codeword.
  2. With k data bits there are 2k codewords, and all the balls must fit among the 2n possible blocks: 2k(n+1)≤2n, that is n+1≤2n−k. This is the Hamming bound for one error.
  3. With r=n−k check bits, the bound says n≤2r−1.
  4. Hamming codes have n=2r−1 exactly: r=3 gives (7,4), r=4 gives (15,11). The balls then fill the whole space with nothing left over: every possible block is within one flip of exactly one codeword.
  5. Such codes are called perfect. Apart from repetition codes of odd length and trivial cases, the only other perfect binary code is the Golay code of length 23 (1949), which corrects three errors; this was proved in the early 1970s.

IT·09 Channel Capacity and the Noisy-Channel Coding Theorem

Information Theory

Why the Gaussian channel's capacity is 12log2(1+P/N).

  1. The output is Y=X+Z, with noise Z normal, variance N, independent of X, and E[X2]≤P.
  2. I(X;Y)=h(Y)−h(Y∣X). Given X, Y is X plus noise, a shifted copy of Z, and shifting doesn't change differential entropy: h(Y∣X) =h(Z) =12log2(2πeN).
  3. Y's variance is at most P+N, since X and Z are independent.
  4. Among all distributions with a given variance, the normal has the largest differential entropy, so h(Y)≤12log2(2πe(P+N)), with equality when Y is normal, which happens when X is normal with variance P.
  5. Subtracting: I(X;Y)≤12log2P+NN =12log2(1+P/N), achieved by normal inputs, so that's the capacity. With bandwidth B, the channel allows 2B independent uses per second (the sampling theorem), giving Blog2(1+SNR) bits per second.

IT·10 Information Everywhere: Language, DNA, Randomness and Passwords

Information Theory

Why a model's cross-entropy can't beat the entropy rate (for a source whose symbols are independent, as a sketch).

  1. Let the source's true probabilities be p and the model's be q. The model's average surprise per symbol is ∑xp(x)log21q(x), its cross-entropy.
  2. Subtract the entropy ∑xp(x)log21p(x): the difference is ∑xp(x)log2p(x)q(x).
  3. Using lnu≤u−1 as in chapter 4: −∑plnqp≥−∑p(qp−1) =1−∑q≥0.
  4. So the model's average surprise is at least the entropy, with equality only when q=p. The difference is the Kullback–Leibler divergence, chapter 11's subject.
  5. For sources with memory, the same argument applies to each symbol given the past, and the entropy rate takes the entropy's place.

IT·11 Information in Machine Learning: Cross-Entropy and KL Divergence

Information Theory

Why maximum likelihood minimises KL divergence.

  1. Data x1,…,xn come from an unknown p; a model qθ has parameters θ.
  2. Maximum likelihood chooses θ to maximise ∏iqθ(xi), equivalently to minimise 1n∑ilog21qθ(xi), the model's average surprise on the data.
  3. By the law of large numbers (chapter 6), that average tends to ∑xp(x)log21qθ(x) =H(p,qθ) as n grows.
  4. H(p,qθ) =H(p)+D(p‖qθ), and H(p) doesn't depend on θ.
  5. So, with enough data, maximum likelihood chooses the model in the family closest to the truth in forward KL divergence, the "covering" direction, which is why it spreads probability over everything the data does.