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.
- Give each input a measure: a natural number, like the length of a list or the value of
n. - 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.)
- Natural numbers can't decrease forever: any strictly decreasing sequence of them is finite.
- 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).
- 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.
- Each resize copies every current element: 1 + 2 + 4 + … + 2ᵏ where 2ᵏ < n.
- That geometric sum equals 2ᵏ⁺¹ − 1, which is less than 2n.
- So n appends cost n writes plus fewer than 2n copies: under 3n operations, a constant per append on average.
- 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.
- 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.
- 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.
- A binary tree of height h has at most 2ʰ leaves, so 2ʰ ≥ n!, which gives h ≥ log₂(n!).
- 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.
- 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.
- 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.
- So P(no collision) = (1 − 1/N)(1 − 2/N)…(1 − (k−1)/N).
- For small x, 1 − x ≈ e⁻ˣ. Multiplying the approximations adds the exponents: P ≈ e^−(1 + 2 + … + (k−1))/N = e^−k(k−1)/(2N).
- Set this to ½ and solve: k(k−1) ≈ 2N ln 2, so k ≈ √(2 ln 2 · N) ≈ 1.18 √N.
- 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.
- 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.
- 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).
- Rearranging: ~x = 2ⁿ − 1 − x, so ~x + 1 = 2ⁿ − x, which is exactly −x.
- 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.
- Every access pays the cache's hit time, say 1 ns.
- A fraction of accesses miss (the miss rate, say 5%) and each pays an extra miss penalty, say 100 ns.
- So the average is AMAT = hit time + miss rate × miss penalty = 1 + 0.05 × 100 = 6 ns.
- 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.
- 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.
- 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.
- A flat table with one 8-byte entry per page would need 2³⁶ × 8 bytes = 512 GB, per process. Impossible.
- 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.
- Only the tables covering addresses actually in use need to exist. A small process needs a handful of 4 KB tables, not 512 GB.
- 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.
- TCP can have at most one window of unacknowledged data in flight; it then waits for acknowledgements, which take one round trip.
- So the best throughput is window ÷ RTT.
- To fill a link of bandwidth B, the window must be at least B × RTT: the bandwidth-delay product.
- 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.
- 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.
- 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.
- Observation (the weak generational hypothesis): most objects die young. Temporary strings, iterators and request objects become garbage almost immediately.
- 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.
- Objects that survive several collections are moved to an "old" area that is collected rarely.
- 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.
- Suppose
List<Dog>were a subtype ofList<Animal>. - Then
List<Animal> animals = dogs;would compile, wheredogsis aList<Dog>. animals.add(new Cat())type-checks: aCatis anAnimal.- But
animalsanddogsare the same list, soDog d = dogs.get(0)now returns aCat: the type system has been broken. - 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.
- Let a program take time 1 on one core, of which a fraction p can run in parallel and 1 − p can't.
- On n cores the parallel part takes p/n; the serial part still takes 1 − p.
- Speedup = 1 / ((1 − p) + p/n).
- As n grows without limit, p/n goes to zero, so speedup approaches 1 / (1 − p).
- 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.
- Let requests arrive at an average rate λ per second, and each stay an average W seconds.
- 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.
- Counted per request, the same area is roughly (number of requests) × W = λT × W.
- The average number inside, L, is that area divided by T: L = λW.
- 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.
- Make each task a node and draw an edge from A to B when B needs A's output.
- A valid order runs every task after all its inputs: a topological order of the graph.
- 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.
- 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.
- 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.
- A request passes through three services, A → B → C, and each layer makes up to 3 attempts on failure.
- If C fails every time, B makes 3 calls to C for each call it receives.
- A makes 3 calls to B for each request, and each of those makes 3 calls to C: 3 × 3 = 9 calls to C.
- If the client in front of A also retries 3 times, C receives 3 × 3 × 3 = 27 calls per user action.
- 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.
- Let a cache hit cost h, a miss cost m (the source's latency plus the cache lookup), and the hit rate be p.
- Average latency = p·h + (1 − p)·m.
- 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.
- Load on the source scales with 1 − p: going from 90% to 99% hits cuts source load tenfold.
- 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).
- 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.
- Suppose X → Y: each X value determines exactly one Y.
- 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.
- So the join produces exactly the original rows: the decomposition is lossless.
- 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.
- 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.
- A tree of height h can reach f^h leaves: 500¹ = 500, 500² = 250,000, 500³ = 125 million, 500⁴ = 62.5 billion.
- So four or five levels cover billions of rows, and finding any row means reading that many pages.
- 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.
- 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.
- 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.
- 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).
- 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.
- Even 2ⁿ grows too fast eventually, so PostgreSQL switches to a randomised genetic search above a threshold (12 tables by default).
- 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.
- With
hash mod N, a key stays put only if its hash gives the same remainder mod N and mod N + 1. - 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.
- 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.
- 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.
- 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 for whole numbers.
- is rows, each holding objects (multiplication as rows of a rectangle).
- Draw a vertical line in each row after the first objects. Every row now splits into a part of and a part of , and the line runs straight down the whole rectangle.
- The left of the line is rows of : objects. The right is rows of : .
- Drawing a line moves nothing, so the total is unchanged: .
- 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- numeral.
- Suppose a number is written two ways: , with every digit between 0 and .
- Every term except the last is a multiple of , so and also .
- Both and are between 0 and , so each is the remainder of on division by ; the division algorithm (chapter 4) says there's only one such remainder. So .
- Subtract it and divide by : the remaining digits of both numerals now write the same smaller number, .
- Repeat. At every step the digits agree, and the numbers shrink, so the process ends with the two numerals identical. The bound 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 numbers, no carry is ever more than .
- Each column holds digits, each at most 9, so its digits sum to at most .
- Suppose the carry into this column is at most . Then the column total is at most .
- The carry out is the column total's tens part (the quotient on dividing by 10). Since the total is less than , the quotient is at most .
- The first column has no carry in (0, which is at most ), 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.
- With : carries are at most 1. With : at most 2. The bound is reached, for example by adding 99…9 to itself times.
AN·04 Multiplying and Dividing
Arithmetic and Numbers
Why Karatsuba's method takes about steps.
- To multiply two -digit numbers, split each into halves of digits: , .
- The product is . Done directly that needs four half-size products.
- Karatsuba computes the middle coefficient as , reusing the two outer products, so three half-size products are enough (plus additions, which cost only about steps).
- Apply the same trick to each half-size product, and again, times, until the pieces are single digits. At each level the number of products triples, so the bottom level has single-digit products.
- , against 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.
- Run Euclid's algorithm backwards. For 1071 and 462: , , .
- Rewrite the last useful line as , then replace 147 using the first line: .
- The same steps work for any pair, so the gcd of and can always be written as for some whole numbers and (one of them negative). This is Bézout's identity.
- Now let a prime divide but not . The only factors of are 1 and , so , and step 3 gives .
- Multiply by : . The prime divides and it divides , so it divides the right-hand side, which is .
- 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.
- Suppose and are the same fraction, so (the chapter's test), and add each to .
- The two sums are and . They're equal exactly when the cross-products are equal: and .
- Expand: the first is ; the second is .
- The second terms are identical, and the first terms are equal because (step 1). So the sums are equal: addition is a rule about numbers, not about the particular pairs.
- Try the same with the mediant, against . Nothing in step 1 forces them to match, and they don't: and with give and , and . Addition works because every term of the cross-products carries the equal products and , 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.
- Take in lowest terms with (the only kind that ends, by the chapter's theorem).
- A decimal with places is a whole number over . For to be written that way, must divide , so and .
- Take and multiply top and bottom by : the bottom becomes , so places are enough.
- Fewer won't do: with places the bottom lacks a factor 2 or a factor 5 that needs, and since shares no factor with , it can't make up for it.
- So has exactly decimal places. Check: , with , has 3 places (0.075); has 3 (0.056); 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.
- A group with successes out of has rate ; another, out of , has rate . Combined, the rate is the mediant .
- Rewrite it as a weighted average: , since the first term is and the second .
- The weights and 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).
- 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.
- 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.
- With bits, store an integer in range () as , the floored remainder, which is between 0 and .
- The hardware adds two codes as unsigned numbers and keeps bits: it computes .
- Remainders add (chapter 5): , provided is itself in range, so that its code is defined by step 1.
- So the stored result is exactly the code of the true sum, and reading it as signed gives . No step looked at signs.
- If is out of range, the hardware still produces , which reads as : 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 increases with and stays below 3.
- Expand by the binomial theorem: , and each term is .
- Rewrite the factors as . Each is less than 1, and each grows when grows. So every term grows with , and a larger adds more (positive) terms: the whole expression increases.
- Each term is at most , so the total is at most .
- Since , that's at most (a geometric series, the household capstone's stage 10).
- An increasing sequence that never passes 3 approaches some limit (a property of the real numbers, chapter 12): that limit is , 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.
- Write the measured values as and , where and are the relative errors (positive or negative).
- Their product is by distributivity.
- So the product's relative error is .
- If and are at most 1 % (0.01), the extra term is at most 0.0001, a hundred times smaller than either: negligible. So the relative error is about , at most .
- For a power, , the same argument with equal factors gives about : a 1 % error in a length is about a 2 % error in an area and 3 % in a volume (chapter 10's and 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).
- Take intervals whose widths shrink to zero, such as the bisection intervals for .
- For each number of decimal places , the widths eventually fall below . After that, all the intervals agree on the first decimal places of their points (allowing for the 0.4999… = 0.5 ambiguity, which only affects numbers that end).
- Define a decimal by taking, for each , the th digit that the late intervals agree on. This is an infinite decimal, so it's a real number.
- lies in every interval: if it were outside , 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.
- There can't be two such numbers : 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 questions are needed, and enough, to pick one of possibilities.
- 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.
- Whatever the answer, at least one group has at least half the possibilities. In the worst case you're left with that group.
- So after questions, in the worst case at least possibilities remain. To be sure of one, you need , that is, , so : no strategy can do it in fewer.
- Halving questions ("is it in the first half?") achieve it: each leaves at most half (rounded up), so after questions one possibility remains.
- So the worst case needs exactly questions, and 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 is about , without Stirling's formula.
- , because the logarithm of a product is the sum of the logarithms.
- The sum is close to the area under the curve from 1 to : each term is the area of a strip of width 1 and height , and the curve rises slowly.
- That area is .
- Since , this is .
- The strips overshoot the curve a little (by less than in total), which is the correction in Stirling's formula. For : , 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 -bit values arrives after about values.
- With equally likely values, the chance that the th value avoids the before it is , so all are different with probability (the product rule).
- For small , , so the product is about , because a product of exponentials is the exponential of the sum.
- That's close to when is large, so .
- Setting it to : , so and .
- With , that's : about 77,000 for 32 bits and 5 billion for 64, as the chapter's lab computed. For 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.
- Let be the uncertainty of equally likely outcomes. Shannon asked that grow with and that grouping hold.
- Take equally likely outcomes and group them into groups of . Grouping says : choose the group, then the outcome within it (each group equally likely, so the second stage always costs ). Repeating, .
- For any and at least 2 and any large , pick with . Because grows, , so lies between and .
- Taking logarithms of the same inequality, lies between the same two bounds. So for every : the two ratios are equal.
- So for a constant . Grouping unequal probabilities as fractions of equally likely outcomes then gives (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.
- Each time Huffman merges two trees of weights and , every symbol in them moves one level deeper, so their codewords each gain one digit.
- The symbols in the merged trees have total probability , so the average codeword length grows by exactly at that merge.
- 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: .
- Check on : merges create weights , and 1, which add to , the average length found in the chapter.
- 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 digits for a message of probability .
- After coding, the message owns an interval of width inside .
- Let , so . Binary fractions with digits are spaced apart.
- Take the smallest -digit fraction ; then . The whole range of numbers that start with those digits is , which ends below : inside the interval.
- So the digits identify the interval unambiguously, whatever digits might follow them, and the decoder recovers the message (given its length).
- The cost is : 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.
- The chain rule for entropy, applied to conditional entropies, gives a chain rule for mutual information: : the information that and together carry about is what carries plus what adds once is known.
- The same quantity can be expanded in the other order: .
- In a Markov chain , once is known, is independent of , so .
- Setting the two expansions equal: .
- Conditional mutual information is never negative, so , with equality exactly when keeps everything knew about (a "sufficient statistic").
IT·08 Channels and Noise
Information Theory
Why Hamming codes are perfect.
- A code of length that corrects one error needs every codeword's "ball", the codeword and its neighbours one flip away, to be separate: blocks per codeword.
- With data bits there are codewords, and all the balls must fit among the possible blocks: , that is . This is the Hamming bound for one error.
- With check bits, the bound says .
- Hamming codes have exactly: gives , gives . The balls then fill the whole space with nothing left over: every possible block is within one flip of exactly one codeword.
- 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 .
- The output is , with noise normal, variance , independent of , and .
- . Given , is plus noise, a shifted copy of , and shifting doesn't change differential entropy: .
- 's variance is at most , since and are independent.
- Among all distributions with a given variance, the normal has the largest differential entropy, so , with equality when is normal, which happens when is normal with variance .
- Subtracting: , achieved by normal inputs, so that's the capacity. With bandwidth , the channel allows independent uses per second (the sampling theorem), giving 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).
- Let the source's true probabilities be and the model's be . The model's average surprise per symbol is , its cross-entropy.
- Subtract the entropy : the difference is .
- Using as in chapter 4: .
- So the model's average surprise is at least the entropy, with equality only when . The difference is the Kullback–Leibler divergence, chapter 11's subject.
- 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.
- Data come from an unknown ; a model has parameters .
- Maximum likelihood chooses to maximise , equivalently to minimise , the model's average surprise on the data.
- By the law of large numbers (chapter 6), that average tends to as grows.
- , and doesn't depend on .
- 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.