Kayavak / Concepts / Misconceptions
Concepts
Misconceptions, and what's actually true
704 beliefs that sound right and aren't, each with what's true instead. They come from the companions, where each one is shown with real measured output: follow a chapter's link to see the evidence. Read the left column first and decide whether you agree before reading the right.
Volume 1 Companion: Foundations of Computing
V1·01 Start Here: Computers, Programs and Your Toolbox
- "Python isn't compiled."
- CPython compiles source to bytecode first (cached as
.pycin__pycache__), then interprets the bytecode. The chapter mentions this "twist" in one clause. - "Java is interpreted, so it's slow."
- The JVM interprets at first, then JIT-compiles hot code to machine code. Long-running Java is often close to C speed.
- "Exit code 0 means the output is right."
- 0 means the program reported success. A logic error still exits 0.
- "A relative path is relative to the script's folder."
- It's relative to the process's current working directory.
- "The line in the error message is where the bug is."
- Often it's the line before (C's missing
;), or far away (a bad value created earlier). - "
> filecaptures everything the program prints." - It captures stdout only. Errors still go to the screen unless you add
2>. - "A failing command stops a script."
- Bash carries on after failures unless told otherwise, and a pipeline reports only its last command's status.
- "Memory and storage are the same, just different sizes."
- RAM is volatile and about 1,000× faster than an SSD. Data is only safe once it's on storage and flushed.
V1·02 Programming Fundamentals & Paradigms
- "Java passes objects by reference."
- It passes references by value (call by sharing). The callee can't make your variable point elsewhere.
- "
finalmakes an object immutable." - It makes the variable unassignable. The object it refers to can still change (a
final Listcan still be added to). - "Records are immutable."
- Records are shallowly immutable. A record holding a
Listis only as immutable as that list (the TiffinBox build, stage 2, copies it). - "Removing from a list while looping always throws
ConcurrentModificationException." - Not always: removing the second-to-last element makes the loop end quietly and skip the last element.
- "
==compares values for small numbers, so it's safe for IDs." - It compares references. It only looks right for
Integervalues from −128 to 127, and that range is configurable. - "Go's
go vetcatches loop-variable capture." - It flags captures in
goanddeferstatements, but not closures stored for later. - "Recursion is always slower than a loop."
- With tail calls optimised, it compiles to the same loop. Without them, it costs a frame per call. Clarity, not speed, usually decides.
V1·03 Data Structures
- "O(1) means fast."
- It means the cost doesn't grow with n. Hashing a long key, or a cache miss, can make an O(1) step slower than several O(log n) ones.
- "A trie makes prefix search instant."
- Reaching the prefix's node is instant; collecting and sorting everything under it isn't.
- "A
PriorityQueueis a sorted list." - It's heap-ordered and unstable.
- "Sorted means numeric order."
- A
TreeMap<String, …>sortsk12beforek7, character by character. - "
Arrays.asListturns any array into a list." - Not a primitive array:
Arrays.asList(int[])is a list of one element, the array itself. - "A
subListis a smaller list." - It's a view of the original: it shares storage, keeps the whole original alive, and breaks if the original is structurally modified.
- "Bloom filters never give false negatives."
- True only if items are never removed. Deleting by clearing bits creates false negatives; counting Bloom filters exist for that.
V1·04 Algorithms
- "An O(n log n) algorithm is always faster than an O(n²) one."
- Only beyond some n. Library sorts use insertion sort below 32–44 elements.
- "Sorted input is the worst case for quicksort."
- For naive first-element pivots. Library quicksorts choose pivots from samples and fall back to heapsort; TimSort is fastest on sorted input.
- "A DP solution is polynomial."
- It's polynomial in the table size, which may be exponential in the input's length.
- "If the heap holds an object, updating the object updates the heap."
- The heap doesn't know you changed it; order breaks silently.
- "
binarySearchreturns −1 when not found." - It returns
-(insertion point) - 1, which is −1 only when the key would go first. Any negative means not found. - "Memoisation makes recursion safe."
- It removes repeated work, not depth.
V1·05 Discrete Mathematics
- "
x % nis always in 0…n−1." - In Java, C, C++, Go and Rust it's negative for negative x. Use
Math.floorMod. - "
Math.absreturns a non-negative number." Math.abs(Integer.MIN_VALUE)isInteger.MIN_VALUE: there's no positive 2³¹ in anint.- "
NOT INandNOT EXISTSare the same." - Only when the subquery can't produce NULL.
- "A join just adds columns."
- A join of relations multiplies rows when keys repeat: customer 1 with 2 orders becomes 2 rows, and
SUMafter the join double-counts. - "
java.util.Randomis random enough for tokens." - It's a public recurrence; two outputs predict the third.
- "Passing 1,000 random tests proves it."
- It's evidence about the cases tried. Exhaustive checking of a finite space, or a proof, says something about all cases.
V1·06 Data Representation
- "Only addition and multiplication overflow."
- Negation,
abs, andMIN_VALUE / -1overflow too; in C the division kills the process. - "A cast to a smaller type keeps the low part."
- For integers. For floating point, Java saturates and NaN becomes 0.
- "
Character.isDigitand[0-9]agree." isDigitaccepts hundreds of Unicode digits.- "Rounding is symmetric."
Math.round(-2.5)is −2 whileMath.round(2.5)is 3.- "A
charin an expression is a character." - In arithmetic it's promoted to an
intcode:'A' + 1is 66. - "Formatting with the locale's grouping is a one-liner."
DecimalFormatcan't produce Indian grouping.
V1·07 Computer Architecture
- "An instruction has a fixed cost."
- It depends on data: subnormals, cache misses and mispredictions change it by 10–100×.
- "Division and modulo are cheap."
- Tens of cycles for a variable divisor; constants and powers of two are rewritten by the compiler.
- "
volatilemakes it thread-safe." - It makes reads and writes visible and ordered;
count++is still three steps and still races. - "Parallel is faster."
- Only with enough work per task and idle cores.
- "Faster clock, faster program."
- Clocks stalled around 2005; performance now comes from width, caches and cores (theoretical gap 4).
- "A microbenchmark result is the cost."
- The JIT may have deleted or folded the code (Gaps 3's 0.03 ns).
V1·08 Operating Systems
- "Virtual threads make blocking free."
- Pinned in
synchronizedon JDK 21: back to a pool the size of the core count. - "A file lock protects the file."
- It protects it from processes that also lock (advisory).
- "Two processes appending to a file is safe."
- Only with
O_APPEND, on a local filesystem. - "File errors are
IOExceptions." - Through
mmap, they'reInternalErrors (or crashes). - "
close()flushes to disk." - It flushes Java's buffers to the kernel; the page cache still isn't on disk.
- "A POSIX lock belongs to the file descriptor."
- It belongs to the process: closing any descriptor for the file releases them all.
V1·09 Networking
- "Lowering the DNS TTL makes failover fast."
- Only for clients that honour it; the JVM caches for 30 s, and pools keep old connections.
- "The port answers, so the service is healthy."
- The kernel completes handshakes into the backlog without the program.
- "
write()succeeded, so they got it." - It reached your send buffer; failure shows up on a later call.
- "A write error means the request failed."
- The server may have answered (413, 401) and closed early.
- "HTTPS means the server is who I think it is."
- Only if the hostname is verified against the certificate; raw
SSLSockets don't by default. - "Bandwidth decides how fast a transfer is."
- For one TCP connection over a long path, the window and the round-trip time decide.
V1·10 Compilers and Runtimes
- "If the grammar accepts it, the parser handles it."
- Deep nesting exhausts a recursive parser's stack: bound the depth.
- "A regex in Java is compiled once."
String.matches,replaceAlland multi-charactersplitcompile on every call.- "Operator precedence is common sense."
- It differs between languages (
**, unary minus,&and==). - "Higher optimisation levels give the same results, faster."
- Flags that relax floating-point rules change results.
- "Interpreted means slow, compiled means fast."
- A JIT compiles with run-time information and can beat AOT code on hot paths; an AOT binary starts faster.
- "Garbage collection means no memory leaks."
- Anything still referenced is kept; leaks are references you forgot.
V1·11 Mastery Projects
- "The reference implementation is the answer."
- It's one clear answer to a simplified problem; finding its limits is part of the exercise.
- "A size limit in the code means the input is bounded."
- Only if it's checked before or while reading, not after.
- "fsync before rename makes the swap durable."
- The rename itself needs the directory fsynced.
- "Recovery that keeps the valid prefix is safe."
- Only for a torn tail; mid-log corruption needs a stop, not a truncation.
- "A bigger project is a better project."
- A finished, tested, measured small project beats an unfinished large one.
- "If it passes my tests, it works."
- Your tests encode your assumptions; hostile tests encode an attacker's.
Volume 2 Companion: The Web Frontend
V2·12 The Web Platform
- "If my server's URL parser says the host is X, the browser goes to X."
- Different parsers resolve some strings to different hosts.
- "UTF-8 is the default for web pages."
- Without a declared charset, browsers fall back to a locale-dependent legacy encoding.
- "Allowing
Origin: nullis harmless; it's for local files." - Every sandboxed frame and
data:page has origin null. - "Zero-delay timers are free."
- Nested ones are clamped to 4 ms, and background tabs are throttled harder.
- "CORS stops requests from other sites."
- It stops other sites from reading responses; the request still arrives and acts.
- "Same site means same origin."
- Sites group origins by registrable domain; cookies follow sites, storage follows origins.
V2·13 HTML
- "Forms always send UTF-8."
- They send the page's encoding, with
&#NNNN;for characters it can't represent. - "Enter submits forms."
- Only with a submit button, or a single field.
- "
type=numbersends digits." - It sends any valid floating-point string:
1e1,05,2.0. - "
maxlengthcounts characters." - It counts UTF-16 code units; emoji count double, and names can be cut mid-syllable.
- "A
<button>inside a form is just a button." - Its default
typeissubmit. Usetype="button"for anything else. - "ARIA makes elements accessible."
- ARIA only changes what's announced; it adds no behaviour. Native elements first.
V2·14 CSS
- "The nearer ancestor's rule wins."
- Selectors ignore distance; only
@scopeand inheritance know nearness. - "The
hiddenattribute always hides." - It's a user-agent
display: none, beaten by any authordisplay. - "
1.5emand1.5are the same line height." - Same on the element; different for every descendant with another font size.
- "Invalid CSS is ignored, so an earlier declaration still applies."
- Only parse-time errors. A
var()that turns out invalid makes the property unset. - "
outline: noneis fine if I add a box-shadow ring." - Forced-colours mode removes box-shadows; use a transparent outline.
- "Higher specificity always wins."
- Only after origin, importance, context and layers have tied.
- "Eleven classes beat an ID."
- Specificity columns never carry over.
V2·15 JavaScript
- "
(a, b) => a > bsorts ascending." - It must return a negative number to move anything; a boolean leaves the array unsorted.
- "
try/catchin anasyncfunction catches everything inside it." - Not a promise returned without
await. - "A closure keeps only the variables it uses."
- In V8, all closures from one scope share a context holding every variable any of them uses.
- "Async code loses stack traces."
awaitchains keep them; callbacks and timers don't.- "Circular imports are fine in ES modules."
- They work only if no module uses another's binding during evaluation; the result depends on load order.
- "
structuredClonedeep-copies anything." - Not prototypes, functions, DOM nodes or class instances' methods.
- "
asyncmakes code run in parallel." - It runs on the same thread; it only stops blocking while waiting for I/O.
V2·16 TypeScript
- "Narrowing is reset whenever the value could change."
- In callbacks, yes; across
awaitand function calls, no. - "
readonlymakes a property immutable." - Only through that type; an alias with a mutable type can write it.
- "The type system can model any set of strings."
- Unions are capped at 100,000 members, and large ones slow every check.
- "
skipLibCheckonly skipsnode_modules." - It skips every
.d.ts, and broken declarations becomeany. - "
Omit<T, 'x'>checks thatxexists." Omitaccepts any key, so typos compile;Pickchecks.- "Typed JSON is checked JSON."
JSON.parsereturnsany; nothing checks it unless you do.
V2·17 The DOM and Browser APIs
- "Each tab has its own connections."
- Six HTTP/1.1 connections per origin are shared by all tabs in a browser profile.
- "
EventSourcealways reconnects." - Not after an HTTP error or a wrong content type: it closes for good.
- "Reconnecting clients spread out naturally."
- They reconnect after the same fixed delay, all at once.
- "
Date.now()is the time." - It's the device's clock, which may be minutes off.
- "Every SSE library behaves like
EventSource." - Libraries differ in retrying, back-off, and even in what counts as a message.
V2·18 Browser Internals
- "
font-display: swapis the safe default." - It shows text early and shifts the layout when the font arrives.
- "
size-adjuston the web font fixes font shifts." - It belongs on a local fallback face, with overrides divided by the adjustment.
- "Selector cost is about matching speed."
- It's about how much a change invalidates; a
:has()on a changing class reaches the whole page. - "Speculation rules are just markup."
- Inline rules are script for CSP; use the header under a strict policy.
- "CLS adds up every shift."
- It's the worst burst (session window) of shifts.
- "Fast servers mean fast pages."
- Most load time is in the browser: parsing, fonts, images, scripts and rendering.
V2·19 Frontend Networking
- "A cancelled fetch rejects with
AbortError." - It rejects with the signal's reason:
TimeoutError, your own error, orAbortErroronly without a reason. - "
sendBeaconalways sends." - It returns
falsepast 64 KiB of in-flight keepalive data, shared across the page. - "My code sees 304s."
- The browser hides them unless you set the conditional header yourself, and then the body is empty.
- "Retry libraries make requests safe to repeat."
- They only retry methods assumed idempotent;
POSTneeds a key. - "Exponential back-off spreads retries out."
- Without jitter, everyone backs off by the same amounts and returns together.
- "CORS protects my API."
- It protects users' browsers; any non-browser client ignores it.
V2·20 Accessibility
- "Performance CSS doesn't affect accessibility."
content-visibility: autoleaves off-screen content out of Chromium's tree.- "Decorative CSS content is ignored by screen readers."
- It's part of the name unless given an empty alternative (
content: "→" / ""). - "Disabling a button during a request is harmless."
- It drops keyboard focus; use
aria-disabledand ignore repeat clicks. - "Our tests check names, so they match the browser."
- Test libraries compute names themselves and can disagree with the browser.
- "An aria snapshot is the accessibility tree."
- Playwright's snapshot is computed from the DOM; the browser's tree can differ.
- "Accessibility overlays fix compliance."
- They don't fix the underlying markup and often interfere with users' own tools.
V2·21 UI Architecture
- "A few booleans are simpler than a state machine."
- They allow combinations nobody designed; a machine allows only the states you list.
- "i18n is translating strings."
- Plurals, number grouping, dates and direction need a formatting layer, not concatenation.
- "Full-page screenshots catch visual regressions."
- Any shift floods the diff; test components in isolation.
- "Signals re-run only what changed."
- They re-run what depends on a value that's no longer
===; a computed array is new every time. - "Shared code should be extracted early."
- Extract at the third use, when the shape is known.
- "Micro-frontends fix team coupling."
- They move it to runtime contracts and duplicate frameworks; they solve an organisational problem at a technical cost.
V2·22 React
- "React output is XSS-safe."
- Text and attributes are escaped; raw HTML, inline JSON and URLs are yours to handle.
- "Wrap it in startTransition and it won't block."
- Only updates to React state are interruptible; store updates render synchronously.
- "
useSyncExternalStoreis justuseEffectplususeState." - That's the old shim, and it can commit inconsistent values; the built-in hook prevents tearing.
- "
memomakes a list cheap." - Only if props stay
===; one prop that changes for every row re-renders every row. - "getSnapshot can build an object each time."
- It must return the same value while nothing changed, or React loops.
- "Strict Mode's double effects are a development quirk."
- They rehearse what production remounts do; an effect without cleanup leaks there too.
V2·23 Angular
- "Angular sanitises styles."
- Not since version 10; the browser rejects script in CSS, and the CSP does the rest.
- "If the component renders, its styles work."
- Under a strict CSP, component styles are refused unless they carry the page's nonce.
- "esbuild is what
ng builddoes." - Angular's builder adds optimisations that made the bundle 3.4× smaller.
- "
inject()works anywhere in a component." - Only in an injection context: construction, factories, or
runInInjectionContext. - "An effect that writes its own input will error."
- In Angular 22 it hung the tab, in production and development builds.
- "OnPush plus signals makes inputs free."
- Each new object input marks its component for refresh; a tick cost 5× more.
V2·24 Full-Stack Frameworks
- "SSR makes pages faster."
- It makes content visible sooner; total main-thread work went up.
- "Hydration is cheaper than rendering."
- It took as long as rendering from nothing here.
- "Compression breaks streaming."
- Only where a layer doesn't pass
flush()through. - "
JSON.stringifyis fine for embedding state." - It loses types and doesn't escape
</script>. - "A slow data source just makes the page slow."
- Without a deadline the response never ended.
- "Development and production SSR send the same HTML."
- Development put the server's error message and file paths in the page.
V2·25 State Management
- "
localStorageis always there." - It threw on read in a sandboxed frame and on write at 5 MiB.
- "The storage event keeps all tabs in sync."
- It fired in the other tab, not the one that wrote.
- "Put filters in the URL and you're done."
- Push or replace is a decision; controls must follow Back.
- "Dark mode from localStorage is fine with a fast script."
- A module script let one wrong frame through.
- "Stores only notify when something changed."
- Zustand's merge notified for an unchanged value.
- "Classifying state is a one-off exercise."
- Each new feature adds state to place; the build's filter and theme were both new kinds.
V2·26 Frontend Testing
- "jsdom is a lightweight browser."
- No layout, no
@layer, no resolved custom properties. - "axe passing means the page is accessible."
- axe was identical before and after fixing focus and invalid state.
- "More generated cases make a stronger test."
- 20,000 sequences killed 4 of 15 mutants.
- "Visual tests are too flaky to be strict."
- Zero tolerance held across six runs once data and anti-aliasing were controlled.
- "Two components that look the same render the same."
- Three text nodes instead of one changed 71 pixels.
- "Unreachable inputs don't need tests."
- The snapshot bug needed an input the server never sends, until it does.
V2·27 Frontend Performance
- "Good INP means a responsive app."
- INP stopped at 40–64 ms; the result took 42–204 ms.
- "4× throttling shows a 4× slower device."
- One view got 2.1× slower; long tasks appeared from nothing.
- "A budget test catches regressions."
- Only large ones; a 20 ms change needs about 70 runs per side.
- "INP is the worst interaction."
- It's an estimated 98th percentile, from at most ten candidates.
- "No long tasks means no jank."
- Chunks just under 50 ms still fill frames (stage 23's 44–48 ms passes).
- "Fallbacks are free."
- A newly available feature without one cost the whole palette.
V2·28 Frontend Security
- "Sanitise, then assign to
innerHTML." - Under Trusted Types, a sanitised string is refused; only a trusted value from a named policy works.
- "Send both report-to and report-uri for coverage."
- With report-to present, Chromium ignored report-uri.
- "A nonce is a secret on the page."
- Any running script can read it as a property.
- "Fetch Metadata is enough against CSRF."
- Older browsers don't send it; the build now checks Origin too.
- "CORS stops cross-site requests."
- It controls who reads responses; the request still happens.
- "DOMPurify removes everything risky."
- It keeps what's inert by its rules (a
data:SVG image); context matters.
V2·29 PWAs, Workers and WebAssembly
- "Registering a service worker is one line."
- Under Trusted Types it needs a policy the CSP names.
- "
navigator.onLinetells you if requests will work." - It stayed
truewith the server down. - "IndexedDB is permanent."
- Without persistence it can be evicted;
persist()was refused. - "A queued request can just be sent again."
- Only if the server makes it idempotent, and only in order.
- "
fetchrejects on an error response." - It rejects only when there's no response; a 404 resolves.
- "Cache the whole site and it works offline."
- Pages with per-response secrets (nonces) must never be stored.
- "WebAssembly is faster than JavaScript."
- Only for compute-bound work that doesn't cross the boundary much.
V2·30 Build Tooling and Monorepos
- "Shared types keep client and server in step."
- Not with old data or old deployed clients; contracts need optional fields and expand-then-contract.
- "Deterministic tools make reproducible builds."
- Undeclared inputs (stale files, hand-written files in the output) break it.
- "A workspace has one version of each package."
- Three copies of TypeScript, two of them the same version.
- "If it imports, it's a dependency."
- Hoisting makes undeclared packages importable.
- "
npm installin CI is fine." - It can change the lockfile;
npm ciinstalls exactly it, or fails. - "Dependencies only run in the browser."
- Six packages ran native install scripts on every
npm ci. - "Our code is what makes the bundle big."
- It was 9% of the React view.
V2·31 Frontend Deployment
- "Keep old files and deploys are safe."
- Also in the rollback direction, or rollbacks 404.
- "A proxy passes a stream through."
- nginx's default held it back entirely.
- "The six-connection limit only slows things down."
- The seventh tab couldn't load at all.
- "An ETag tells the browser whether a file changed."
- serve-static's ETag changes when the file's time does, even with the same bytes.
- "Cache-busting query strings are as good as hashed names."
- Some caches ignore query strings, and the file itself can't be kept for old tabs.
- "Content hashes depend only on content."
- esbuild's names changed with the build directory until the paths were made relative.
- "
immutableis what makes assets long-lived." - The year-long
max-agedoes that;immutableonly stops revalidation on reload (Firefox and Safari honour it; Chrome changed its reload behaviour instead).
V2·32 Frontend Observability
- "Send on hide and you'll get everything."
- A page that's never hidden sends nothing.
- "
sendBeaconalways sends." - It refused 63 KB with 17 KB in flight, and said so only by returning false.
- "Group errors by their top frame."
- The top frame was the shared helper
fail. - "INP is the slowest interaction."
- It's about the 98th percentile: web-vitals takes the (n/50)th longest.
- "Source maps are harmless to serve."
- They publish your source, and nothing needs them but your error tool.
- "More tags make better data."
- Each value is a new series; unbounded tags exhaust storage.
- "Field LCP is the same as lab LCP."
- Field LCP stops at the first input, and includes real networks and devices.
V2·33 Frontend Projects
- "A good LCP means a fast page."
- A server-rendered page painted on time and then blocked for 300 ms.
- "Set the budget at the current value."
- The same code varied ±9% between runs.
- "No errors reported means no problem."
- No reports can mean no data yet.
- "Lighthouse CI fails a build when a run is slow."
- Its default (
optimistic) uses the best run. - "Projects are done when the features work."
- Done includes tests, budgets, a11y, docs and a deploy.
- "Eight projects means eight repositories."
- They're one product in layers.
- "A canary needs real users."
- Synthetic views drove it here; real users are better, but the gate logic is the same.
Volume 3 Companion: The Backend
V3·33 Language Foundations
- "
\dandparseIntagree." parseIntreads ١٢٣ as 123;\ddoesn't match it.- "Locales only affect currency display."
- Digits and case mapping change; ß uppercases to two letters.
- "Java is pass-by-reference for objects."
- It passes references by value.
- "
Integer==works for small numbers, so it's fine." 127 == 127is true,128 == 128false:true false true.- "
Math.absis never negative." Math.abs(Integer.MIN_VALUE)is-2147483648.- "
new BigDecimal(0.1)is exact." - It's exactly the double:
0.1000000000000000055511…; useBigDecimal.valueOf. - "A linter that finds nothing is wasted."
- It keeps careful code careful.
V3·34 OOP and Its Alternatives
- "Sealed types tell you every place to change."
- Only
switches in the same compilation; strings, tests and contracts aren't checked. - "Records are immutable."
- Shallowly: a mutable component can change and move the hash.
- "Record equals is field-by-field ==."
- Doubles compare like
Double.compare: NaN equals NaN, 0.0 differs from -0.0. - "Refactoring is safe if the tests pass."
- Tests check what they assert; a golden master checks everything it recorded.
- "Inheritance is for reuse."
- Composition reuses without the fragile base class; inherit for substitutability.
- "OOP and pattern matching are rival styles."
- Most systems need both: data for closed domains, interfaces at open boundaries.
- "A failing test after a valid change means the change is wrong."
- Sometimes the test encoded an assumption, not the rule.
V3·35 Collections
- "Removing in a for-each always throws."
- Removing the second-to-last element ends the loop silently, skipping the last.
- "Immutable collections keep the order I put things in."
List.ofdoes;Set.ofandMap.copyOfrandomise per run.- "PriorityQueue operations are O(log n)."
- Only at the head;
remove(Object)andcontainsare O(n). - "
unmodifiableListmakes a list immutable." - It's a read-only view of a list that can still change.
- "
List.copyOfalways allocates." - Not for an already-immutable list.
- "A TreeSet uses equals."
- It uses the comparator: compare = 0 means duplicate.
- "ConcurrentHashMap makes my code thread-safe."
- Each call is atomic; get-then-put isn't.
V3·36 Generics
- "Generics check types at run time."
- Only the compiler checks; at run time a
Tag<String>is aTag. - "An unchecked warning is noise."
- It marks the exact place the compile-time promise stops holding.
- "Inference errors are unreadable."
- They list each overload's constraints; read the one you meant.
- "A sealed switch must list every subtype."
- Not subtypes the type argument rules out.
- "
List<Object>accepts any list." - Generics are invariant;
List<?>orList<? extends Object>does. - "Typed keys make a container safe."
- Only if names (or numbers) are unique per type.
- "Generics cost nothing in Java."
- No code cost, but boxing for primitives and a cast at each use.
V3·37 Functional Programming
- "No mutation means pure."
- Reading the clock, a static or a system property is a hidden input.
- "
Optionalis a monad, so chains can be regrouped." - Not when a mapped function returns
null. - "A stream is a snapshot of its source."
- Most sources bind when the terminal operation starts.
- "A
ConcurrentModificationExceptionstops the pipeline before damage." ArrayList'sforEachchecks once, at the end: every element was processed.- "
this::mis a value; equal values are equal." - Each evaluation may be a new object, and there's no
equals. - "Parallel streams make pure code faster."
- Only for large, CPU-bound, splittable work.
- "Side effects in
maprun once per element." - They run when, whether and as often as the terminal operation pulls.
V3·38 Concurrency
- "Inject a
Clockfor everything time-related." - Business time from a
Clock; deadlines fromnanoTime. - "
nanoTimevalues can be compared with<." - Compare differences; the counter can wrap.
- "The JVM will tell me about a deadlock."
- Not among virtual threads, on JDK 21.
- "A stress test that passes means the code is safe."
- Only if it can fail; check invariants.
- "
ReentrantLockserves threads in order." - Only
new ReentrantLock(true), at a large cost. - "Virtual threads remove the need for locks."
- They change the cost of blocking, not data races.
- "
cancel(true)stops aCompletableFuture's work." - It doesn't interrupt the task.
V3·39 Modern Java
- "
--release 21makes any newer JDK build my code the same way." - Same API; different lints and different class files.
- "
-Xlint:all -Werroris a fixed standard." - It grows with each compiler.
- "A version constant in the code is the version."
- Only if someone remembers to change it.
- "Heap used shows memory savings."
- Only after a full GC; otherwise it shows GC timing.
- "Adding a method to an interface is always compatible."
- Sources can clash (
getFirst). - "Preview features are safe once they compile."
- They can change or be withdrawn next release.
- "Upgrading the JDK means rewriting code."
- Most gains come with no code change.
V3·40 JVM Internals
- "When
mainthrows, the program exits." - Not while a non-daemon thread runs.
- "The GC will close what a failed constructor opened."
- Maybe, someday; locks and descriptors stay until then.
- "Checking source catches every call."
- Method references and code without source need the class files.
- "A class's constant pool shows what it calls at run time."
- It shows what it names.
- "Ready means fast."
- The first requests run interpreted and load classes.
- "A shutdown hook can report failure with
System.exit." - That hangs the JVM; use
halt. - "Changing a library constant updates its users."
- Constants are inlined at compile time.
V3·41 Memory and Performance
- "A cache that grows with the data isn't a leak."
- It can still keep far more than it needs, and serve stale answers.
- "Immutable objects make caching safe."
- Safe to share, but a cached version is still an old version.
- "The allocation profile shows what's slow."
- It shows what allocates; a scan that allocates nothing is invisible to it.
- "Bytes per object at a small size predict the large size."
- Fixed costs dominate small runs.
- "420 samples is a big sample."
- Not when ten of them carry 81% of the weight.
- "Two profiles that disagree mean the code changed."
- Not necessarily: the same build can rank differently.
- "String replacement is cheap."
- On a whole page it copies the page each time, and changes what you didn't mean to.
- "A regex that runs once a request is fine."
- It's compiled once a request too.
V3·42 Modules and Packaging
- "Fixed timestamps make a JAR reproducible."
- Only with the same compiler; JDK 25 changed 13 of 106 classes.
- "
--release 21gives the same class files on any JDK." - It fixes the API and class file version, not the bytes.
- "A jlink image is the JDK, smaller."
- It drops the CDS archive unless asked, and every module you didn't list.
- "
module-infomakes my internals private." - Only for users who put you on the module path.
- "Binary compatible means users can upgrade without changes."
- Until they recompile, or reflect over your record.
- "Changing a method's return type is safe if callers ignore it."
- The descriptor changes, so old callers fail with
NoSuchMethodError. - "
jdepslists every module the service needs." - Not the ones only operations use, like
jdk.jfr.
V3·43 Build Systems
- "Gradle always runs the tests when something changed."
- Only when something it knows about changed.
- "A system property pointing at a file makes the file an input."
- Only the path is. Declare the file.
- "Compiler arguments are just strings."
- Paths in them are inputs; Gradle refuses the ones it can't track.
- "A new lint rule is a cheap change."
- It changes every compile task's inputs.
- "Content hashing needs nothing from the outputs."
- It needs them reproducible, or every rebuild cascades.
- "If it compiles, the API didn't change."
- Record components and new members change it; only a recorded API shows that.
- "A method body edit recompiles the callers."
- Not with compile avoidance; only ABI changes do.
- "A cached result is always right."
- Only if every input was declared.
V3·44 Backend Fundamentals
- "Graceful shutdown waits for requests in flight."
- It may also wait for idle connections, unless it closes them.
- "Slow tests are slow code."
- Here they were five times slower because of a shutdown wait.
- "Asynchronous logging is always faster."
- Only against a slow destination; a contended queue can cost more than it saves.
- "An async appender never loses logs."
- Full queues drop (or block); know which, and count it.
- "The MDC follows the request."
- Not across threads; an inheritable one can name the wrong request.
- "The top of the stack trace is where it failed."
- Not for wrapped exceptions from other threads.
- "Middleware order doesn't matter."
- It decides what the request id, logging and error mapping can see.
V3·45 HTTP API Design
- "Every client speaks HTTP/1.1."
- A default nginx speaks HTTP/1.0 to its upstream.
- "Responses without caching headers aren't cached."
- Shared caches apply their own defaults.
- "
no-cachemeans don't cache." - It means revalidate; nginx won't store it at all.
- "
max-age=0stops everything from caching." s-maxageoverrides it for shared caches.- "Removing an optional field is safe."
- Readers that used it when present lose it.
- "Adding an enum value is compatible."
- Only for clients that tolerate unknown values.
- "A 304 is free."
- It still costs a round trip to the origin.
V3·46 Spring Core
- "A bad setting fails at startup."
- Only if its type refuses bad values;
TimeZoneturns them into GMT. - "IST is India Standard Time."
- In Java's
TimeZone; elsewhere it's also Israel and Ireland. Use regions. - "A constant isn't a dependency."
- If it can differ between deployments or tests, it is.
- "DI needs a container."
- A composition root does the same job by hand.
- "Spring tells you where a property came from."
- Spring Boot does; the core resolver only logs it at debug level.
- "Every day has 24 hours."
- Not in zones with daylight saving.
- "Annotations work on any call."
- Not on calls from inside the bean (self-invocation).
V3·47 Spring Boot
- "Started means ready means fast."
- The first requests run cold code.
- "A readiness probe makes deploys safe."
- Only if the server waits for it to be seen before stopping.
- "Graceful shutdown means no failed requests."
- It finishes requests that arrived; others may still be on their way.
- "Warm-up warms the application."
- It warms the code it runs.
- "Small pages are fast pages."
- A page just over a buffer size can wait for a delayed ACK.
- "Relaxed binding catches typos."
- A misspelt property or variable matches nothing, silently.
V3·48 Spring Web — MVC and WebFlux
- "Validation makes any input format safe."
- Only what the format names can be checked.
- "Duplicate JSON keys are harmless."
- Parsers disagree on which one wins.
- "Now is now."
- Each reading is a different time; a request needs one.
- "Problem details are always better."
- For clients that read them; others display them.
- "Deprecation headers tell clients to move."
- They label; counting and changing the clients moves them.
- "Controllers are the architecture."
- They translate; the rules live in a service you can test without HTTP.
V3·49 Persistence — JDBC, JPA and Spring Data
- "A file is just bytes; read it."
- Arrays and buffers stop at 2 GiB; read in windows.
- "An append-only log is simple storage."
- Its restart time and memory grow with history until you add checkpoints.
- "Compaction solves growth."
- It removes superseded records; live state still grows.
- "fsync makes a file durable."
- It makes its contents durable; a new or renamed name needs the directory fsynced.
- "Autocommit is fine for bulk writes."
- Each commit waits for a flush: batch them (TiffinBox's group commit).
- "The ORM loads what I use."
- It loads what you touch, one query at a time, unless you say otherwise.
V3·50 Spring Security and Modern Identity
- "Logged-in users can only see their own data."
- Only if every object lookup checks ownership.
- "403 is the honest answer."
- For objects, 404 avoids confirming they exist.
- "Turn on security, then fix what breaks."
- Report first; the breakage is measurable in advance.
- "A valid signature means valid claims."
- Claims can be ambiguous, for another audience, or expired.
- "Tokens belong in headers."
- Browsers'
EventSource, images and navigations only send cookies. - "Rotating a key logs everyone out."
- Not if old keys still verify until their tokens expire.
V3·51 Asynchronous Work, Jobs and Messaging
- "Background work doesn't affect requests."
- It shares locks, CPU and disk with them.
- "A job runs until it's stopped."
- On the JDK's scheduler, until it throws once.
- "Logging every event is enough to act on."
- Someone needs the counts, by who and what.
- "Async means fire and forget."
- It means someone else must remember: a queue, a log, a retry.
- "Exactly-once delivery is a setting."
- Delivery is at-least-once; effects are made once by idempotent consumers.
V3·52 Resilience — Timeouts, Retries, Circuit Breakers and Load Shedding
- "One bad instance out of two halves capacity."
- It can take everything, if clients wait on it.
- "Measure queue depth to detect overload."
- Measure the age of the oldest waiter, where it waits.
- "Readiness should follow the instant's health."
- Without hysteresis it flaps faster than checks.
- "Retrying a 503 is always safe."
- Only when the server guarantees nothing was done.
- "Timeouts on calls are enough."
- Background work needs deadlines too.
- "Retries make systems more reliable."
- Uncapped, they multiply load on the struggling part.
V3·53 Caching
- "Caches are for databases."
- They're for any repeated work, especially under a lock.
- "Every cache needs a TTL."
- With a version in the key, entries are never stale, just unused.
- "Cache the response."
- Cache what's shared; add what's per request.
- "Hit rate measures a cache."
- What it protects does: latency, load, contention.
- "Deleting the key fixes staleness."
- A racing reader can write the old value back.
V3·54 Backend Testing
- "100% of mutants killed: great tests."
- Or a suite that always fails; check the control.
- "Every path has a test."
- Every path someone remembered; mutation finds the rest.
- "Each route has its own security test."
- A loop over all routes catches the one nobody wrote.
- "It passed, so it's not flaky."
- Flakiness is a failure rate; one run can't show it.
- "High coverage means well tested."
- Lines ran; nothing says a wrong line would fail a test.
V3·55 Backend Projects
- "The API's security tests pass, so access is enforced."
- At the API. Every other door needs the same rule and its own check.
- "It's correct under concurrency, so the locking is right."
- Correct and fast are separate questions; a lock can be right in rule and wrong in grouping.
- "The golden master passes, so behaviour is correct."
- It's unchanged, which includes unchanged bugs.
- "0.1 KB doesn't matter."
- It doesn't, once. Budgets exist because it happens every week.
- "Unfinished promises mean the project failed."
- Re-pointing with a reason is scope; silence is drift.
- "A project's README should list the technologies."
- It should give measurements and reproduced failures.
Mathematics Book 1 Companion: Arithmetic and Numbers
B1·01 What Numbers Are
- "00 is undefined, like 0÷0."
- It's a matter of convention: algebra and every mainstream language take 00=1; analysis leaves it undefined.
- "There's only one zero in a computer."
- IEEE 754 floats have +0 and −0; they compare equal, but
1 / -0is-Infinity. - "Brackets in code are only for when you need them."
- Unneeded brackets are often worth keeping for readers;
ast.unparseremoves them, which shows exactly which ones the grammar needs. - "An ID made of digits is a number."
- It's a label; stored as a number it loses leading zeros and, in JavaScript, digits beyond 253.
- "The average of daily averages is the average."
- Only when every day has the same count; otherwise compute from totals.
B1·02 Place Value and Bases
- "A leading zero never changes a number's value."
- In C, older JavaScript and the C library's
inet_aton, a leading 0 means octal:010is 8. - "An IP address is four separate numbers."
- It's one 32-bit number written as four base-256 digits;
192.168.1.10is 3,232,235,786. - "Negative binary numbers are a minus sign and the bits."
- Machines store a fixed-width two's complement pattern; 11111011 is −5 or 251 depending on how it's read.
- "Sorting numbers stored as text works."
- Text sorts character by character: "10" comes before "9".
- "
parseFloatreads a number with commas." - It stops at the first comma:
parseFloat("1,000")is 1.
B1·03 Adding and Subtracting
- "An exact sum of floats gives the exact total."
- It gives the exact total of the stored approximations: ten float 0.1s sum to slightly more than 1.
- "
x | 0just removes the fraction in JavaScript." - It converts to a 32-bit integer and wraps:
4000000000 | 0is −294,967,296. - "The number of days from the 3rd to the 10th is 7."
- 7 is the difference; counting both ends gives 8 days; a hotel charges 7 nights. Say which you mean.
- "Comparing money totals with == works if you round first."
- Rounding hides it in one case and fails at the next boundary; store paise and compare integers.
- "Borrowing just adds ten to the column."
- It moves ten from the next place; forgetting to take it away from there inflates the answer.
B1·04 Multiplying and Dividing
- "Printing a number is free."
- Converting to decimal is repeated division; naive conversion of huge numbers is slow enough that Python limits it to 4,300 digits by default.
- "
math.ceil(n / k)rounds up correctly." - Only while
n / kis exact in floating point; use(n + k - 1) // kfor integers. - "Rounding each share to the paisa keeps the total."
- It can lose or invent paise; give the remainder to some shares explicitly.
- "Multiplying by 1,000,000 just adds zeros, even in JavaScript."
- Above 253, floats are spaced apart: nanosecond timestamps lose their last digits.
- "10k has to be computed by multiplying tens."
- 10k=5k×2k, and multiplying by 2k is a shift: Python builds powers of ten that way.
B1·05 Factors, Multiples and Primes
- "The gcd of 0 and 0 is undefined, so code can ignore it."
- By convention it's 0, and dividing by it fails; handle zero explicitly.
- "
range(2, int(sqrt(n)))tries every divisor up to the square root." - It stops one short: 4, 9, 25 and 143 are reported prime.
- "
int(math.sqrt(n))is the integer square root." - Only while n is small enough for floats; use
math.isqrt. - "
a ** b % mis fine for modular powers." - The power can be huge or rounded; reduce as you go with
pow(a, b, m). - "Euclid's algorithm is only for gcds."
- Its quotients are the continued fraction of a/b, which finds the best simple fractions near any number (22/7, 355/113 for π).
B1·06 Fractions
- "
Fraction(0.1)is one tenth." - It's the float's exact value, a fraction with denominator 255; use
Fraction("0.1"). - "Converting to decimals is a safe way to compare fractions."
- Floats can't separate fractions closer than about 10−16 relative; cross-multiply instead.
- "Cross-multiplying always compares fractions correctly."
- Only when both denominators are positive; normalise the sign first.
- "
divmodturns any fraction into a mixed number." - For negative fractions it gives a floored whole part; format the sign separately.
- "Fractions with integer parts are exact in every language."
- Only with arbitrary-size integers; JavaScript numbers lose exactness past 253.
- "The average of the daily rates is the overall rate."
- Records combine as the mediant: total successes over total tries.
B1·07 Decimals and Percentages
- "Short decimals like 0.1 or 0.35 are exact in a computer."
- Only fractions with power-of-two denominators are; of 0.01 to 0.99, only 0.25, 0.50 and 0.75.
- "Rounding 2.5 gives 3 everywhere."
- Python gives 2 (ties to even); JavaScript's
Math.round(-2.5)gives −2; name the rule you want. - "The average yearly change is the average of the yearly percentages."
- Changes multiply; use the geometric mean.
- "
int(price * 100)converts rupees to paise." - It truncates a float that's often just below the true value: 19.99 becomes 1998.
- "
parseFloatreads any number a person wrote." - It stops at the first character it doesn't expect: "1,234.50" becomes 1.
- "GST is 18 % of the bill."
- For a bill that includes GST, it's 18118 of it.
- "Rounded percentages add up to 100."
- Rounding each can give 99.99 or 101; allocate the rounding.
B1·08 Ratio, Proportion and Rates
- "A table with equal ratios will pass
len(set(y / x)) == 1." - Float rounding can split equal ratios; use exact fractions or a tolerance.
- "Resizing keeps the aspect ratio."
- Rounding to whole pixels makes it drift, except at exact multiples.
- "Any summary of a rate can be combined across groups."
- Totals combine; percentiles and medians don't.
- "Compute the scale factor first, in integers."
new_w // wis 0 when shrinking; multiply first, then divide.- "The rule of three always multiplies by the new amount."
- For inverse proportion it divides: more workers, fewer days.
- "Converting decimals to integers with
int(x * 100)is safe." - Floats just below the value truncate down: 0.29 m becomes 28 cm.
- "A rate rounded to two places is good enough."
- Its error is multiplied by every amount converted, and inverting it rounds again.
B1·09 Negative Numbers
- "There's only one zero."
- Floats have +0.0 and −0.0: equal, but distinguishable.
- "Subtracting a bigger number from a smaller gives a negative result."
- Not in unsigned types: it wraps to a large positive number.
- "Mixing signed and unsigned is harmless."
- It can convert to float (losing precision) or reinterpret −1 as a huge number.
- "Every decimal library rounds division the same way as integers."
- Python's
Decimaltruncates, soDecimal(-17) % 5is −2 while-17 % 5is 3. - "A remainder is a valid array index."
- A truncated remainder can be negative; JavaScript returns
undefinedfor it. - "
Math.absmakes a hash code safe to use as a bucket." Math.abs(Integer.MIN_VALUE)is still negative.- "
sort()sorts numbers." - JavaScript's default sort compares text, so −1 comes before −10 and 10 before 2.
- "Integer division of a timestamp by 86,400 gives the day."
- For times before 1970, truncation gives the next day; floor.
B1·10 Powers, Roots, Scientific Notation and Logarithms
- "Floats obey the exponent laws exactly."
- They round after each step; (1.13)2≠1.16 in the last digit, and 10.0309 overflows.
- "(1+r)n is always safe to compute."
- For tiny r, 1+r rounds to 1; use
log1pandexp. - "Adding 1 to a number always changes it."
- Not above 253 in a double.
- "Fractional powers of fractions stay exact."
Fraction(4, 9) ** Fraction(1, 2)is a float; roots are usually irrational.- "Variance is the mean of squares minus the square of the mean, so compute it that way."
- In floats that subtracts two huge, nearly equal numbers and can even go negative.
- "
^means power." - In Python, JavaScript, C and Java it's bitwise XOR:
2 ^ 10is 8. - "
3 ** 40in JavaScript is exact." - Numbers above 253 are rounded; use BigInt.
- "Taking logs of data is always safe."
- log0=−∞ poisons averages; decide how to handle zeros.
B1·11 Estimation, Rounding, Error and Units
- "The total of 100 measurements is uncertain by 100 times each one's error."
- That's the worst case; independent errors typically grow like the square root of the count.
- "A month is 30 days."
- Months have 28 to 31 days; adding months needs a rule for the last day.
- "
math.ceil(n / k)counts the groups needed." - Only while n fits a float exactly; use integer division.
- "Negative durations print with a minus sign on every part."
timedelta(minutes=-90)is "−1 day, 22:30:00": floored carries.- "A tiny error per step doesn't matter."
- It accumulates: 0.1 s stored with 10−7 error drifts 0.34 s in 100 hours.
- "Multiply by 3.6 to get m/s."
- Divide; write the factors and check that the units cancel.
- "Python's
roundrounds money like a cash register." - It rounds halves to even: 2.5 becomes 2.
- "7 % can be stored as 7."
- A rate must say whether it's a percent or a fraction, or interest is off by 100 times.
B1·12 The Real Number Line
- "If the digits look random, the number is irrational."
- Rational numbers can delay repetition for thousands of digits; only a proof decides.
- "Floats are spread evenly along the line."
- Half of the positive doubles are below 1; spacing is proportional to size.
- "Bisection can reach any tolerance."
- Not below the gap between neighbouring floats.
- "A fraction and a float with the same printed value are equal."
Fraction(1, 10) == 0.1is False: Python compares the float's exact value.- "Bisection returns a root whenever it returns."
- Without a sign change it returns an endpoint with no root nearby.
- "
maxignores missing values." - A NaN can make the result depend on the order of the list.
- "
Number.EPSILONis the right tolerance." - It's the spacing near 1: too strict for big numbers, too loose for tiny ones.
- "
Decimal(19.99)is 19.99." - It's the float's exact value, 19.9899999…; build decimals from strings.
Information Theory Companion
B1·01 Start Here: What Information Is
- "A letter always carries the same information."
- It depends on the model: "u" carries 4.83 bits alone and 0 after "q".
- "If no compressor can shrink it, it's random."
- Pseudo-random bytes from a 60-byte program defeat zlib, bz2 and lzma.
- "Finding one of N needs log₂ N questions, always."
- That's the worst case for equal odds; unequal odds allow fewer on average.
- "A 32-character hex token has 256 bits of security."
- It carries 128 bits: each hex character is 4 bits stored in 8.
- "
math.loggives bits." - It gives nats; bits need
math.log2. - "Percentages work as probabilities."
- Surprise needs p between 0 and 1; percentages give negative "bits".
- "
int(math.log2(n))questions are enough." - It rounds down; the worst case needs ⌈log2n⌉.
- "Compressing a message measures its information."
- Short messages grow, because of fixed headers and checksums.
B1·02 Counting Possibilities: Bits, Logarithms and Questions
- "Sorting always costs n log₂ n comparisons."
- Only for inputs with that much disorder; sorted input took 9,999.
- "Converting a big decimal number to binary is free."
- Python limits it to 4,300 digits by default; the cost grows faster than the length.
- "Sorting n items means telling apart n! orders."
- With duplicates there are far fewer: n!/(c₁! c₂! …).
- "A shuffle uses as many random bits as it has information."
- Python's spends about 380 bits on a 226-bit shuffle.
- "
math.ceil(math.log2(n))is always right." - For n just above a large power of two, floating point rounds it wrong.
- "Compute a combination's bits from factorials."
- Dividing huge factorials as floats overflows; use
math.comborlgamma. - "A number's digits survive a round trip through int."
- Leading zeros vanish unless the width is restored.
- "Swapping each item with a random position shuffles fairly."
- It makes nn equally likely paths onto n! orders, unevenly.
B1·03 The Probability You Need
- "A word's frequency in a file is its probability."
- Frequencies drift through a file: "king" from 0 to 12 per thousand words.
- "Unseen things are rare enough to ignore."
- 7.8 % of the second half's words were absent from the first half.
- "The expected wait is the typical wait."
- Mean 6, median 4, most common 1, longest 71.
- "Weighted random choice checks its weights."
random.choicesaccepts a negative weight and silently never picks some items.- "Probabilities that should add to 1 will compare equal to 1.0."
- Ten 0.1s added in a loop give 0.9999999999999999.
- "P(h after t) is count(th) ÷ count(h)."
- It's count(th) ÷ count(t followed by anything).
- "Two servers fail together with the product of their chances."
- Only if independent; a shared cause makes it 23 times likelier.
- "A million random ids are plenty for 5,000 users."
- About 12 collisions are expected; the test failed every time.
B1·04 Entropy: the Average Surprise of a Source
- "Same entropy means equally compressible."
- The plays, shuffled and sorted have equal order-0 entropy; lzma gives 2.61, 4.91 and 0.004 bits.
- "A code for a 0.08-bit source can use 0.08 bits per symbol."
- Not one symbol at a time: at least 1 digit each; blocks approach 0.08 slowly.
- "Enough text gives the entropy of words."
- The estimate kept rising with all 208,503 words; heavy tails defeat plug-in estimates.
- "scipy.stats.entropy returns bits."
- Its default is nats; pass
base=2. - "Pass counts or probabilities, whichever: same result."
- SciPy normalises, but your own function may not.
- "An entropy function can just skip zero probabilities."
- Only if it's written to:
log2(0)raises an error. - "Output that looks random has high entropy."
- Hashes of a counter score 4.0 bits per hex character and are fully predictable.
B1·05 Codes: Prefix Codes, Kraft's Inequality and Huffman Coding
- "A Huffman code built once works for similar data."
- Symbols it never saw have no codeword at all.
- "Huffman usually wastes up to a bit per symbol."
- For spread-out distributions the excess is at most pmax+0.086, usually far less.
- "Huffman codewords stay short."
- They can reach K−1 digits; formats cap them.
- "Huffman codewords are written high bit first in DEFLATE."
- zlib reverses them: DEFLATE packs bits from the least significant end.
- "Any priority queue implementation will do."
- Without a tie-breaker, Python's heap compares the trees and crashes.
- "Canonical codes are just counting upwards."
- Without shifting when the length grows, the code isn't prefix-free.
- "A one-symbol file needs no special case."
- Zero-length codewords carry nothing; the decoder can't count symbols.
- "Rice codes work for any whole number."
- Negative numbers collide with positive ones unless mapped first.
B1·06 The Source Coding Theorem: Why Entropy Is the Limit
- "Long blocks get steadily closer to the entropy."
- Gains shrink and wobble while tables grow exponentially.
- "An adaptive coder should remember everything it has seen."
- For changing data, forgetting cut 5.10 to 4.21 bits per byte.
- "Universal compressors reach the entropy of any data."
- zlib stayed 13 % above it on 4 MB of independent bytes.
- "Real coders use exact probabilities."
- Zstandard rounds them to a table of size 211 or so, at a measurable cost.
- "Any precision works for an arithmetic coder."
- Too few bits let rare symbols' slices round to zero, and the coder hangs.
- "The decoder can tweak the model it receives."
- Encoder and decoder must use identical probabilities, or the output is garbage.
- "The last few bits don't matter."
- Without the final bits, the last symbol came out wrong.
- "A model trained on a sample covers the data."
- A byte unseen in the sample has no slice at all.
B1·07 Joint and Conditional Entropy, Mutual Information
- "If no pair of variables is related, none of them are."
- Parity: every pair shares 0 bits, the three together are fully dependent.
- "High mutual information means a model will predict well."
- A straight line used none of x's 1.945 bits about x2.
- "A binned estimate of continuous mutual information is the value."
- 2 bins gave 0.27 bits, 1,024 gave 3.9, for a true 0.737.
- "scikit-learn's mutual information is in bits."
- It uses natural logarithms: nats.
- "Raw mutual information compares fairly across label sets."
- Independent 50-value labels scored 1.65 bits; the adjusted score was about 0.
- "Sorting each column of a table doesn't change its statistics."
- It invents dependence: 0.02 bits became 2.87.
- "H(Y given X) is H(Y) minus H(X)."
- It's H(X, Y) minus H(X); the wrong formula even goes negative.
- "Add a small count to each symbol" is enough for smoothing.
- The denominator must add it for every symbol too, or probabilities don't add to 1.
- "Mutual information functions accept measurements."
- Given floats, each value is its own label, and the score is log₂ n.
B1·08 Channels and Noise
- "Any 32-bit checksum spreads over 2³² values."
- 8-letter messages got 31,251 Adler-32 values; CRC-32 behaved like chance.
- "A valid CRC means the data wasn't altered."
- A changed amount was given a matching CRC by choosing 4 bytes.
- "Hamming(7,4) gets close to the channel's limit."
- At p = 0.01 it runs at 0.571 with errors left; the limit is 0.919 with none.
- "zlib computes a modulo for every byte."
- It delays the modulo for 5,552 bytes, the most before the sums could overflow.
- "A Hamming decoder either works or crashes."
- With its check bits in the wrong order, it 'corrected' as many bits as it broke.
- "If the CRC matches, the file is fine; if not, it's damaged."
- Read as a signed number, half of undamaged files failed.
- "A check digit routine that accepts test cards is correct."
- It accepted every 16-digit number and rejected 9 in 10 valid 15-digit ones.
- "Data that passes its CRC was transmitted correctly."
- A CRC computed after the damage made 102 corrupt files pass.
B1·09 Channel Capacity and the Noisy-Channel Coding Theorem
- "A mobile link's capacity is one number."
- At 10 dB average, a fixed rate of 1 bit per use fails 26 % of moments.
- "Any signal set can reach the Gaussian capacity."
- Equally spaced levels need up to 1.53 dB more.
- "Reaching capacity always needs complex codes."
- With feedback, resending lost bits reached 0.7984 of 0.8 with no code.
- "An iterative capacity algorithm's latest value is the answer."
- dit stops only when certified lower and upper bounds meet.
- "The formula gives capacity in bits."
- With natural logarithms it gives nats: 0.368 instead of 0.531.
- "Any matrix of probabilities describes a channel."
- Rows must be P(output given input) and add to 1; transposed, the answer was 0.0007.
- "SNR in the formula can be in decibels."
- It must be a ratio: 20 dB is 100, not 20.
- "The smaller file is the better design."
- Protecting before compressing was smaller and lost everything to one bit in 10,000.
B1·10 Information Everywhere: Language, DNA, Randomness and Passwords
- "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.
- "Equal entropy means equally hard to guess."
- 6 bits each: 32.5 expected guesses for one, 257.2 for the other.
- "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.
- "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.
- "Length times log of the character pool measures strength."
- 'Password1!' scored 65.5 bits by the formula.
- "A long random-looking token is strong."
- A 20-character token seeded with the time was found in about 2,400 guesses.
- "A text in a language the model knows gets a finite score."
- A character outside a model's alphabet gave infinite surprise.
- "DNA can't exceed 2 bits per base."
- Counted with masking case and gaps, it 'had' 2.62.
B1·11 Information in Machine Learning: Cross-Entropy and KL Divergence
- "KL between two samples is a well-defined number."
- Unsmoothed it was infinite; smoothed, it ranged from 0.277 to 0.872 at 100 letters.
- "A perplexity of 2,572 is far worse than 4.38."
- Per word against per character: 2.240 against 2.130 bits per character.
- "A larger KL always means a larger shift."
- Moving 30 bins or 60 gave the same 19.21 bits.
- "Log loss can be arbitrarily large in scikit-learn."
- It clips probabilities, so one certain mistake costs 36.04 nats, 52 bits.
- "If accuracy is fine, the probabilities are fine."
- The wrong column gave 96.5 % accuracy and 12.9 bits per case.
- "KL is KL, whichever way it's computed."
- Reversed, every normal window scored infinity.
- "Perplexity is 2 to the power of the loss."
- Only if the loss is in bits; in nats it's e to the loss.
- "A random split gives an honest test set."
- 741 of 3,278 test lines were also in the training lines.
Arithmetic and Numbers
ch01 Start Here: What Numbers Are
- "Multiplication always makes bigger, division always makes smaller."
- True only for whole numbers above 1. Multiplying by ½ makes smaller; dividing by ½ makes bigger.
- "BODMAS means division comes before multiplication."
- Division and multiplication have equal rank and are done left to right; so do addition and subtraction.
- "Anything divided by zero is infinity (or zero)."
- Division by zero is undefined: no number times 0 gives a non-zero result. Infinity in computers is an engineering convention for floating point.
- "Subtraction and division are commutative, like addition and multiplication."
- They aren't: 7−4≠4−7 and 24÷4≠4÷24.
- "The order of operations is a mathematical truth."
- It's a convention chosen for convenience; tools differ where it's unclear (Excel's
=-3^2is 9). - "A remainder is always rounded down."
- What you do with a remainder depends on the story: buses round up, shares round down or split.
- "Phone numbers and pincodes are numbers."
- They're labels written with digits; arithmetic on them is meaningless, and storing them as numbers loses leading zeros.
ch02 Place Value and Bases
- "Zero means nothing, so leaving it out doesn't matter."
- Zero holds an empty position; without it 307 becomes 37. Place value doesn't work without a placeholder.
- "Base ten is the natural or correct base."
- Ten is a choice, almost certainly from counting on fingers. Base sixty, twenty, twelve, two and sixteen are all in use.
- "Binary numbers are a different kind of number."
- Binary is a different numeral for the same numbers: 1011012 and 45 are the same quantity.
- "The digit 10 in base 16 is written 10."
- In base 16, "10" means sixteen. Ten is the single digit A; base b needs b single-symbol digits.
- "Repeated division gives the digits from left to right."
- The first remainder is the last digit; read the remainders from the bottom up.
- "Multiplying by 10 always means adding a zero."
- Appending a zero multiplies by the base: by 10 in decimal, by 2 in binary. And for decimals (chapter 7) it doesn't work at all: 2.5 × 10 isn't 2.50.
- "Indian grouping and international grouping give different numbers."
- 1,23,456 and 123,456 are the same number, grouped two ways. Separators are reading aids, not digits.
- "parseInt converts text to a number or reports an error."
- It reads as far as it can and stops silently: "12px" gives 12 and
parseInt("12", 2)gives 1.
ch03 Adding and Subtracting, and Why the Methods Work
- "When the top digit is smaller, subtract the other way round."
- Taking the smaller digit from the larger gives 52−38=26 (5−3 tens, 8−2 ones). The ones column must borrow instead, and the answer is 14.
- "Borrowing changes the top number."
- Regrouping changes only how the number is written: 6 thousands, 9 hundreds, 12 tens and 12 ones is still 6000+900+120+12=7032.
- "A carry can be any size."
- Adding two numbers, a carry is always 0 or 1; adding n numbers, at most n−1.
- "Equal addition is a trick that happens to work."
- It's the same-difference rule: adding ten to the top and one ten to the bottom adds the same amount to both.
- "If casting out nines checks out, the answer is right."
- It misses swapped digits and errors of a multiple of nine. It's a quick check, not a proof.
- "Computers add exactly."
- Integers do (until they overflow); floating-point numbers round after every step, so the order of adding can change the result.
- "Left to right is the wrong way to add."
- Either order works; right to left just avoids fixing digits when carries arrive. Mental methods often go left to right.
ch04 Multiplying and Dividing
- "The answer to a division problem is the quotient."
- The situation decides: buses round up, equal shares round down, and "is it divisible?" asks whether the remainder is 0.
- "The remainder can be any leftover amount."
- The remainder must be less than the divisor; 17=2×5+7 is true but 7 isn't the remainder.
- "A zero in the quotient can be skipped."
- Skipping it makes the quotient ten times too small (403 becomes 43); every place needs a digit.
- "The times table has 100 facts to memorise."
- Commutativity, the identities and a few strategies leave only a short list, each buildable from a neighbour.
- "Long multiplication is the only (or fastest) way."
- It takes n2 digit products; Karatsuba's method takes about n1.585, and faster methods exist.
- "% gives the same remainder in every language."
- For negative numbers, Python's
%follows the sign of the divisor (−17 % 5 is 3), JavaScript's, C's and Java's the sign of the dividend (−2). - "Division always makes smaller."
- Only when dividing by a number greater than 1; chapter 6 divides by fractions and makes things bigger.
ch05 Factors, Multiples and Primes
- "1 is a prime number."
- 1 has only one factor; counting it as prime would break the uniqueness of factorisation.
- "All odd numbers are prime."
- 9, 15, 21, 25 are odd and composite. 2 is prime and even.
- "Euclid's number p1⋯pk+1 is always prime."
- It may not be: 2×3×5×7×11×13+1 =59×509. It just has a new prime factor.
- "If a number is divisible by 4 and by 6, it's divisible by 24."
- Only coprime tests combine: 12 is divisible by 4 and 6, not by 24.
- "Digit sums test divisibility by any number."
- They test 3 and 9 (factors of 10−1) only; for 7 they're wrong about a quarter of the time.
- "If casting out nines checks out, the answer is right."
- It misses any error that's a multiple of 9, including swapped digits.
- "The gcd and lcm can only be found by factorising."
- Euclid's algorithm finds the gcd by repeated division, and lcm = ab/gcd.
- "Bigger numbers are more likely to be prime."
- Primes thin out: near x about 1 number in lnx is prime.
ch06 Fractions
- "12+13 =25."
- Unlike pieces must be made alike first: 56. 25 is the mediant, which combines records, not amounts.
- "A bigger denominator means a bigger fraction."
- A bigger denominator means smaller pieces: 18<15.
- "Multiplying always makes bigger; dividing always makes smaller."
- By a fraction less than 1, multiplying shrinks and dividing enlarges: 3÷12=6.
- "You can cancel any matching digits or terms."
- Only common factors of the whole numerator and denominator cancel; 2+32+5≠35.
- "Flip and multiply is just a rule to memorise."
- It follows from the definition of division, or from a common denominator.
- "The average of two rates is the overall rate."
- Combining records gives the mediant, weighted by how much is behind each rate.
- "A fraction is part of a pizza, so it can't be bigger than 1."
- Improper fractions are bigger than 1, and fractions are also divisions, points and scale factors.
ch07 Decimals and Percentages
- "Longer decimals are bigger: 0.45 > 0.5."
- Compare place by place: 0.50 > 0.45.
- "Multiplying by 10 adds a zero."
- It shifts every digit one place left; 2.5×10=25, not 2.50.
- "0.999… is just less than 1."
- It equals 1: 10d−d=9 gives d=1.
- "A 10 % rise then a 10 % fall gets back to the start."
- It multiplies by 0.99: a 1 % loss. Percentages are of the starting value.
- "To remove 18 % GST, take 18 % off the total."
- The total is 118 % of the price: divide by 1.18.
- "A rate rising from 6 % to 8 % has risen by 2 %."
- It has risen by 2 percentage points, which is 33 %.
- "Decimals like 0.1 are exact in a computer."
- 0.1 repeats forever in binary; a float stores a nearby binary fraction.
- "Repeating decimals aren't fractions."
- Every repeating decimal is a fraction, and every fraction ends or repeats.
ch08 Ratio, Proportion and Rates
- "The ratio 2 : 3 means the first part is 23 of the whole."
- It's 25 of the whole; 23 is the first part compared with the second.
- "Sharing in 2 : 3 : 4 means dividing by 2, 3 and 4."
- Count the parts (9), find one part, multiply.
- "Everything that grows together is proportional."
- Only if the ratio is constant; a fixed starting amount (a taxi's flag fare) breaks it.
- "More workers, more days."
- Workers and days for a fixed job are inversely proportional: more workers, fewer days.
- "The average speed is the average of the speeds."
- It's total distance ÷ total time; for equal distances, the harmonic mean.
- "A bigger pack is always cheaper per unit."
- Usually, not always; compute the unit price.
- "If A beats B in every group, A beats B overall."
- Not when the groups are split differently: Simpson's paradox.
- "Doubling a map's scale doubles the area shown."
- Areas scale by the square of the factor.
ch09 Negative Numbers
- "−10 is bigger than −2 because 10 is bigger than 2."
- Order runs left to right on the line: −10<−2. Size is |−10|>|−2|.
- "−a is always negative."
- −a is the opposite of a; if a=−3, then −a=3.
- "Two negatives make a positive" (for addition too).
- Only for multiplication and division; −3+(−4)=−7.
- "Negative times negative is positive by convention."
- It's forced by the distributive law.
- "−22=4."
- −22=−(22)=−4; (−2)2=4.
- "Multiplying both sides of an inequality by a number keeps it true."
- A negative multiplier reverses it.
- "
%always gives a remainder from 0 to b−1." - In C, Java and JavaScript,
-17 % 5is −2. - "The absolute value of a number is never negative."
- In fixed-width types,
absof the most negative value overflows and stays negative.
ch10 Powers, Roots, Scientific Notation and Logarithms
- "23×24=47" or "23+24=27".
- Same base: exponents add when multiplying: 27. Sums of powers don't combine.
- "2−3 is negative."
- It's 18: a negative exponent means divide.
- "a0=0."
- a0=1 for a≠0, forced by an/an.
- "−22=4."
- −(22)=−4; (−2)2=4. Some spreadsheets disagree.
- "a+b =a+b."
- Roots split over products, not sums: 25≠3+4.
- "Doubling the size doubles the area."
- Area scales by k2: four times. Volume by k3: eight times.
- "log(x+y) =logx+logy."
- It's log(xy)=logx+logy; logarithms of sums don't split.
- "
floor(log10(n)) + 1always counts digits." - In floating point it fails, from 1015−1 up.
ch11 Estimation, Rounding, Error and Units
- "Rounding 2.5 always gives 3."
- It depends on the rule: half even gives 2 (Python's
round). - "Rounding in stages is the same as rounding once."
- 1.445 → 1.45 → 1.5, but 1.445 → 1.4.
- "More decimal places means more accurate."
- Only digits that the measurement supports mean anything; 2.50 claims more than 2.5.
- "Errors average out, so the result is as accurate as the inputs."
- Worst-case errors add; differences of close values can be far less accurate than the inputs.
- "1 m² = 100 cm²."
- 1 m2 =1002 =10,000 cm2.
- "To convert km/h to m/s, multiply by 3.6."
- Divide by 3.6: 10003600 =13.6. Write the factors and let the units cancel.
- "2 h 45 min + 1 h 30 min = 3 h 75 min = 3.75 h."
- 75 min = 1 h 15 min, so 4 h 15 min, which is 4.25 h.
- "An estimate is a guess."
- It's a calculation with deliberately rounded inputs, usually within 10 %.
ch12 The Real Number Line
- "2 is 9970 (or 1.414), just to more places than we bother with."
- No fraction equals 2; approximations get close but never reach it.
- "If fractions are dense, they fill the line."
- Dense means another between any two; there are still gaps at 2, π, …
- "π = 22/7."
- 227 is an approximation (3.1428…); π is irrational.
- "A decimal that looks random is irrational."
- Only a proof decides; any finite number of digits fits a fraction.
- "Irrational times irrational is irrational."
- 2×2=2.
- "All infinities are the same size."
- The fractions can be listed; the reals can't.
- "A computer stores √2."
- It stores the nearest of finitely many fractions.
- "Two numbers computed to be equal are equal."
- In floats, equality is luck; use tolerances, or exact types where possible.
Information Theory
ch01 Start Here: What Information Is
- "Information means meaning, or truth."
- In this theory it's resolved uncertainty; a false or meaningless message from a set of possibilities carries information too.
- "A message carries information on its own."
- The amount depends on the set of possible messages and their probabilities.
- "A bit is a 0 or 1 in memory."
- That's a binary digit; a bit of information can take many stored digits, or a fraction of one.
- "A 1 MB file holds 1 MB of information."
- Only if it's unpredictable; a megabyte of zeros holds almost none.
- "The logarithm is just a convenient choice."
- It's the only measure that's additive for independent events.
- "Rare messages are more important."
- They're more informative; importance is a question of meaning, which the theory leaves out.
- "Compression can always shrink a file a bit."
- Random data doesn't shrink; compressors made it slightly larger.
- "You need a whole number of questions, so information is a whole number of bits."
- Surprise can be any non-negative number; averages over many messages get close to it.
ch02 Counting Possibilities: Bits, Logarithms and Questions
- "Doubling a password's length doubles the number of passwords."
- It squares it; it doubles the bits.
- "A code for K symbols needs log₂ K binary digits."
- One at a time it needs ⌈log2K⌉; only blocks approach log2K.
- "Longer blocks always do better."
- Not always: decimal blocks of 5 cost more than blocks of 3.
- "O(n log n) sorting is a fact about merge sort."
- It's a fact about the information any comparison sort must gather.
- "Counting sort breaks the sorting lower bound."
- It asks questions with many answers, not comparisons.
- "The information bound can always be achieved exactly."
- It's a floor: sorting 12 items needs 30 comparisons, not 29.
- "A random generator can produce any shuffle."
- Not if its seed has fewer than 226 bits.
- "Fixed-length codes can compress text a lot."
- Only by the rounding: 8 to 7 bits for Shakespeare; compression needs probabilities.
ch03 The Probability You Need
- "After a run of sixes, a six is less likely."
- Independent rolls have no memory; each is still 16.
- "Frequencies match probabilities in any sample."
- Small samples wander: 20 sixes in 100 rolls happened in the lab.
- "Letters in text are independent."
- "th" occurs 5.8 times as often as independence predicts.
- "An accurate test's positive result is probably right."
- For rare conditions most positives can be false alarms (4.7 % in the chip example).
- "P(A given B) is about the same as P(B given A)."
- They can differ hugely; Bayes' theorem connects them through P(A) and P(B).
- "A symbol never seen has probability zero."
- It has an unknown small probability; zero breaks compressors.
- "You need about 183 people for a shared birthday to be likely."
- 23 are enough: there are 253 pairs.
- "The expected value is the most likely value."
- A die's expectation, 3.5, never comes up.
ch04 Entropy: the Average Surprise of a Source
- "Entropy measures the information in a particular message."
- It's the average surprise of a source; a particular message has a surprise.
- "More symbols always means more entropy."
- A 1,000-symbol source with one dominant symbol can have far less entropy than a fair coin.
- "A biased coin is half as informative if it lands heads 75 % of the time."
- Entropy isn't linear in the bias: h(0.75)≈0.81 bits.
- "English has about 4.2 bits per letter."
- That's letter frequencies only; with context it's around 1 bit.
- "An entropy measured from data is the source's entropy."
- Small samples underestimate it; 10 die rolls gave 2.14 bits instead of 2.585.
- "Word-level entropy shows a word compressor beats lzma."
- Not until the vocabulary's cost and everything left out are counted.
- "Redundancy is waste."
- It's what lets readers and receivers recover from errors.
- "Entropy here is the physicist's entropy."
- Same form, different setting; the connection is real but needs care.
ch05 Codes: Prefix Codes, Kraft's Inequality and Huffman Coding
- "Any set of codewords can be decoded if you're careful."
- {0, 01, 10} is ambiguous: 010 reads as AC or BA.
- "Codes must be prefix codes to be decodable."
- Some non-prefix codes are uniquely decodable, but they can't do better (McMillan).
- "Huffman achieves the entropy."
- It's within 1 bit; it matches only when probabilities are powers of ½.
- "Rounding each surprise up is optimal."
- The Shannon code averaged 4.56 bits for letters; Huffman 4.22.
- "A very likely symbol can take a fraction of a bit."
- Not with Huffman: at least 1 bit per symbol.
- "The decoder needs the whole code tree."
- With canonical codes, the lengths are enough.
- "Huffman codes are unique."
- Tie-breaking gives different trees, all with the same average length.
- "Elias gamma is a good default for any numbers."
- It costs about twice the minimum for large ones; a tuned Rice code was within 1 %.
ch06 The Source Coding Theorem: Why Entropy Is the Limit
- "The most likely sequence is the typical one."
- All heads is likeliest but not typical; typical ones are each less likely and far more numerous.
- "A clever enough compressor can shrink any file."
- No: there are fewer shorter files than files.
- "Compressing twice compresses more."
- Compressed output is near-random; a second pass gains nothing (chapter 4's exercises measured it).
- "Huffman is as good as it gets."
- Arithmetic coding reached 0.082 bits per toss where Huffman needs 1.
- "Arithmetic coding loses a little on every symbol."
- It loses about 2 bits per message, plus tiny rounding.
- "A compressor needs to be told the statistics."
- Adaptive and Lempel–Ziv methods learn them for a small fixed cost.
- "Entropy is the limit for any file."
- It's the limit for a source model; a better model has lower entropy.
- "The theorem's proof shows how to build compressors."
- Its code is a list of 2nH sequences; practical codes get there symbol by symbol.
ch07 Joint and Conditional Entropy, Mutual Information
- "Learning something can make you less certain."
- On average it can't; a single observation can.
- "X tells you about Y more than Y tells you about X."
- Mutual information is symmetric.
- "Zero correlation means no relationship."
- Mutual information catches any dependence; correlation only linear.
- "Each variable on its own shows whether it's informative."
- Two coins each tell nothing about "they match"; together they determine it.
- "A clever enough algorithm can extract more information than the data has."
- Processing can only lose it (data processing inequality).
- "More context always predicts better."
- On unseen text, 7 letters of context did worse than 4.
- "A model's surprise on its training data measures it."
- It's biased low; held-out surprise is the honest measure.
- "A sensor that's right 70 % of the time gives 70 % of the information."
- It gave 1.28 of 3 bits, about 43 %.
ch08 Channels and Noise
- "A channel that flips 10 % of bits delivers 90 % of the information."
- It delivers 0.531 bits per bit: the receiver doesn't know which bits flipped.
- "A very good channel doesn't need protection."
- At one error in a billion, a 1 GB read is error-free 0.03 % of the time.
- "More check bits always mean more protection."
- Hamming(1023,1013) has more check bits than Hamming(7,4) but fails almost every block at p = 0.01.
- "Hamming(7,4) handles two errors badly but harmlessly."
- It "corrects" them into a third error: 1011 came back as 1001.
- "Any check digit catches swapped digits."
- Adding the digits catches none; Luhn misses 09 ↔ 90.
- "A checksum is a checksum."
- An 8-bit sum missed every byte swap; CRC-32 missed nothing.
- "A decompressor will report damaged input."
- Deflate decoded every one of 12 damaged streams without complaint.
- "Erasures and errors cost the same."
- 10 % erased leaves 0.9 bits per use; 10 % flipped leaves 0.531.
ch09 Channel Capacity and the Noisy-Channel Coding Theorem
- "Fewer errors means sending more slowly."
- Below capacity, longer blocks reduce errors at a fixed rate.
- "Capacity is the rate at which errors are tolerable."
- It's the boundary: below, errors can vanish; above, they can't.
- "Longer codes are always better."
- Above capacity, longer random codes lost more: 49 % to 61 %.
- "Equally likely inputs always maximise information."
- For the Z channel the best input has 40 % ones.
- "More power is the way to a faster link."
- Capacity grows with the logarithm of power but in proportion to bandwidth.
- "Sending just 0 and 1 is fine at any signal strength."
- At 20 dB, binary input carries 1 bit per use of a possible 3.3.
- "Shannon showed how to build the codes."
- He proved good codes exist; practical ones took until the 1990s.
- "It's better to protect data and then compress it."
- Compression would remove the protection; compress first, then protect.
ch10 Information Everywhere: Language, DNA, Randomness and Passwords
- "A model's surprise on text measures the entropy of the language."
- It's an upper bound; better models lower it.
- "More context always predicts better."
- Seven letters did worse than five for the blended model.
- "Equal file sizes mean equal information."
- 10,000 bytes held 9,888 English characters or 3,334 Japanese.
- "DNA is just a text, so text compressors work on it."
- lzma used 2.16 bits per base, worse than 2-bit packing.
- "High entropy means hard to guess."
- 6 bits of Shannon entropy can have 1 bit of min-entropy.
- "Random-looking numbers are secure."
- The Mersenne Twister's next 1,000 outputs were predicted from 624.
- "A long key is a strong key."
- A 128-bit key from a 16-bit seed has 16 bits of min-entropy.
- "Composition rules make passwords strong."
- Human choices have under 7 bits of min-entropy; 11 % fall to 1,000 guesses.
ch11 Information in Machine Learning: Cross-Entropy and KL Divergence
- "KL divergence is a distance between distributions."
- It isn't symmetric: 0.263 bits one way, 0.155 the other.
- "Cross-entropy and KL measure different things."
- Cross-entropy is entropy plus KL, exactly.
- "Two models with the same accuracy are equally good."
- 96.5 % each, but 0.155, 0.340 and 0.523 bits per case.
- "A confident model is a better model."
- Five times more confident: one mistake cost 52 bits.
- "Lower training perplexity means a better model."
- Seven letters: training perplexity 2.1, unseen 5.1.
- "Any positive divergence from the reference means drift."
- Normal windows showed 0.02 to 0.04 bits; calibrate first.
- "Minimising KL gives the same answer either way round."
- One direction covers both bumps, the other picks one.
- "Lossy compression is beyond information theory."
- Rate–distortion: 10 % wrong bits needs 0.531 bits per bit.