Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers
B1·12
The Real Number Line
Around chapter 12: how irrational and real numbers complete the book's number systems, and what computers do instead; three other ways to see them; what the chapter simplifies (digits can't reveal irrationality, floats crowd near zero, bisection stalls in floating point); how Python's Fraction compares itself exactly with floats; four debugging drills; and interview questions.
Understanding it better
Concept map
- Fractions (chapter 6): dense, and every decimal ends or repeats (chapter 7).
- Gaps: isn't a fraction (parity proof) → is whole or irrational (unique factorisation, chapter 5) → , , transcendental numbers → decimals that never repeat.
- Real numbers = points of the line = infinite decimals → completeness: shrinking nested intervals close on one number → bisection (and chapter 10's Heron) approximate any real by fractions.
- Both kinds everywhere: a rational and an irrational between any two reals.
- : counting (ch01–05), opposites (ch09), reciprocals (ch06), limits (ch12).
- Sizes of infinity: fractions countable, reals uncountable (Cantor's diagonal) → almost all reals irrational, transcendental, uncomputable.
- Computers: floats are finitely many fractions (ch07, ch10) → tolerances, exact types, symbolic and arbitrary-precision arithmetic.
- Next: limits and calculus, complex numbers, and statistics, beyond this book.
Explain it differently
A ruler with every mark. Mark every fraction on a ruler and the marks are so crowded that no gap between two marks is empty: there's always another mark. Yet a pin pushed in at touches no mark. The real line is the ruler itself, the wood, not the marks.
Decimals as addresses. Each digit of a decimal narrows down a position to a tenth of the previous interval: 1, then 1.4, then 1.41, … An infinite decimal is an infinite sequence of ever-smaller boxes, and completeness says there's always exactly one point inside all of them. A rational number's address eventually repeats; an irrational one's never does.
Countable is "can be called by number". A queue with a first, second, third person, going on for ever, is countable. Fractions can stand in such a queue (the Calkin–Wilf order). Cantor showed the reals can't: whatever queue you form, the diagonal construction finds someone left out.
Gaps and misconceptions
What the chapter oversimplifies
1. "Irrational decimals never repeat", which no number of digits can confirm. The chapter says an irrational number's decimal never repeats. But a rational number's decimal can go a very long way before repeating:
def digits(a, b, n):
out, r = "", a % b
for _ in range(n):
r *= 10
out += str(r // b)
r %= b
return out
print("1/9973 :", digits(1, 9973, 48), "...")
k, r = 1, 10 % 9973
while r != 1:
r, k = r * 10 % 9973, k + 1
print("its period:", k, "digits")
1/9973 : 000100270730973628797753935626190714930311841973 ...
its period: 554 digits
looks random for 48 digits and in fact for 554 before its cycle repeats; fractions with larger denominators can delay repetition for millions of digits. So "the first trillion digits of don't repeat" is evidence about 's digits, not proof of irrationality; only Lambert's proof is. In data, a float or a printed decimal can never be shown irrational at all: every finite decimal is a fraction.
2. "Floats approximate the line", unevenly. The chapter notes that float spacing grows with size. The consequence for where floats are is dramatic:
import struct
def count_below(x):
"""How many positive doubles are smaller than x: the bit patterns of positive doubles are in numeric order."""
return struct.unpack(">Q", struct.pack(">d", x))[0]
total = count_below(float("inf"))
for x in (1e-300, 1.0, 1e6, 1e300):
print(f"positive doubles below {x:g}: {count_below(x) / total:.1%}")
positive doubles below 1e-300: 1.3%
positive doubles below 1: 50.0%
positive doubles below 1e+06: 50.9%
positive doubles below 1e+300: 98.7%
Half of all positive doubles are below 1, and 98.7 % are below : the floats are spread evenly on a logarithmic scale (chapter 10), with the same count in every interval . Between 1 and 2 there are of them; between and , an enormous stretch of the line, fewer than half. Precision is relative, not absolute.
3. "Bisection always closes in", but not past the float spacing. In the real numbers, halving goes on for ever. In floats, an interval eventually has no float strictly inside it:
lo, hi = 1e16, 1e16 + 8
for step in range(1, 60):
mid = (lo + hi) / 2
if mid in (lo, hi):
print(f"step {step}: no float strictly between {lo!r} and {hi!r}; width {hi - lo} can't shrink further")
break
if mid * 1 < 1e16 + 3: # pretend the root is at 1e16 + 3
lo = mid
else:
hi = mid
print("a loop 'while hi - lo > 1e-6' would never end here")
step 3: no float strictly between 1.0000000000000002e+16 and 1.0000000000000004e+16; width 2.0 can't shrink further
a loop 'while hi - lo > 1e-6' would never end here
Near neighbouring doubles are 2 apart, so after a few halvings the midpoint equals an endpoint and the interval can't shrink below width 2. A loop that runs "until the width is below " never finishes. Real implementations stop when the midpoint equals an endpoint, or use a tolerance relative to the size of the numbers, or cap the number of steps.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "If the digits look random, the number is irrational." | Rational numbers can delay repetition for thousands of digits; only a proof decides. | What the chapter oversimplifies, point 1 |
| "Floats are spread evenly along the line." | Half of the positive doubles are below 1; spacing is proportional to size. | What the chapter oversimplifies, point 2 |
| "Bisection can reach any tolerance." | Not below the gap between neighbouring floats. | What the chapter oversimplifies, point 3 |
| "A fraction and a float with the same printed value are equal." | Fraction(1, 10) == 0.1 is False: Python compares the float's exact value. |
Code walkthrough |
| "Bisection returns a root whenever it returns." | Without a sign change it returns an endpoint with no root nearby. | Drill D1 |
"max ignores missing values." |
A NaN can make the result depend on the order of the list. | Drill D2 |
"Number.EPSILON is the right tolerance." |
It's the spacing near 1: too strict for big numbers, too loose for tiny ones. | Drill D3 |
"Decimal(19.99) is 19.99." |
It's the float's exact value, 19.9899999…; build decimals from strings. | Drill D4 |
Theoretical gaps: the ideas behind the chapter
- The least upper bound property. Completeness has several equivalent forms: nested intervals (the chapter), every bounded set has a least upper bound, every Cauchy sequence converges. Analysis (beyond this book) starts from one and derives the others, and from them the intermediate value theorem that justifies bisection: a continuous function that changes sign must cross zero.
- Measure. The rationals are countable, so they can be covered by intervals of total length as small as you like (cover the th fraction by an interval of length ). In the sense of length, the rationals occupy none of the line: a "random" real number is irrational with probability 1.
- Approximation theory. Every irrational has infinitely many fractions with (Dirichlet), found by continued fractions; algebraic numbers can't be approximated much better than that (Roth's theorem, 1955), and numbers that can, like Liouville's, are transcendental. The chapter's Pell fractions for sit right at Dirichlet's bound.
Applying it
Code walkthrough
Every finite float is a fraction, so Python's Fraction can compare itself with a float exactly, by converting the float to the fraction it really is. Excerpts from Lib/fractions.py in Python 3.13 (on your computer: python3 -c "import fractions; print(fractions.__file__)"):
@classmethod
def from_float(cls, f):
"""Converts a finite float to a rational number, exactly.
Beware that Fraction.from_float(0.3) != Fraction(3, 10).
"""
...
return cls._from_coprime_ints(*f.as_integer_ratio())
def __eq__(a, b):
"""a == b"""
...
if isinstance(b, float):
if math.isnan(b) or math.isinf(b):
# comparisons with an infinity or nan should behave in
# the same way for any finite a, so treat a as zero.
return 0.0 == b
else:
return a == a.from_float(b)
float.as_integer_ratio() returns the float's exact value as a numerator and a power-of-two denominator, already in lowest terms (so _from_coprime_ints skips the gcd). The docstring's warning is chapter 7's theorem: the float written 0.3 isn't . In __eq__, a fraction equals a float only if it equals the float's exact fraction; infinities and NaN, which aren't real numbers at all, are handled separately by comparing 0 with them, so every finite fraction is unequal to NaN and less than . Ordering comparisons (_richcmp) do the same, then cross-multiply integers (chapter 6). Measured:
from fractions import Fraction as F
import math
print(F.from_float(0.1), "| == F(1, 10):", F.from_float(0.1) == F(1, 10), "| F(1, 10) == 0.1:", F(1, 10) == 0.1)
print("F(1, 3) > 1/3 (the float):", F(1, 3) > 1 / 3, "| F(1, 4) == 0.25:", F(1, 4) == 0.25)
print("F(10**400) < math.inf:", F(10 ** 400) < math.inf, "| F(1, 2) == math.nan:", F(1, 2) == math.nan)
try:
F.from_float(math.inf)
except (OverflowError, ValueError) as e:
print("from_float(inf):", type(e).__name__, e)
3602879701896397/36028797018963968 | == F(1, 10): False | F(1, 10) == 0.1: False
F(1, 3) > 1/3 (the float): True | F(1, 4) == 0.25: True
F(10**400) < math.inf: True | F(1, 2) == math.nan: False
from_float(inf): OverflowError cannot convert Infinity to integer ratio
The float 0.1 is exactly , so it isn't equal to , and Python says so rather than rounding. The float 1/3 is slightly below , so is strictly greater, while exactly (a power-of-two denominator). A fraction with 401 digits is still less than infinity, and no fraction equals NaN. Converting infinity to a fraction raises an error, because infinity isn't a real number: the boundary of the chapter's line, made visible in code.
Read it yourself
Using the code above, predict Fraction(1, 3) == 1 / 3, Fraction(3, 8) == 0.375 and Fraction(1, 3) < 0.3333333333333333, and explain why comparing exactly is the right design for a fraction type, even though it makes Fraction(1, 10) == 0.1 False.
Debugging drills
D1. A root that isn't there
A solver uses bisection without checking its inputs. On two equations it returns about 5, with no root nearby:
def bisect_unchecked(f, lo, hi, steps=50):
for _ in range(steps):
mid = (lo + hi) / 2
if f(lo) * f(mid) <= 0:
hi = mid
else:
lo = mid
return (lo + hi) / 2
f = lambda t: (t - 2) ** 2 - 1e-12 # dips just below zero near t = 2, two roots very close together
g = lambda t: (t - 2) ** 2 + 1 # never zero
print("f on [0, 5]:", bisect_unchecked(f, 0, 5), "| f(0) * f(5) =", f(0) * f(5))
print("g on [0, 5]:", bisect_unchecked(g, 0, 5), "| g there:", g(bisect_unchecked(g, 0, 5)))
f on [0, 5]: 4.999999999999998 | f(0) * f(5) = 35.999999999987
g on [0, 5]: 4.999999999999998 | g there: 9.99999999999999
Explain, and fix.
D2. The hottest reading depends on the order
A dashboard shows the day's maximum temperature with Python's max. On days when a sensor drops a reading (recorded as NaN), the result changes depending on where the gap falls:
import math
readings = [21.5, math.nan, 23.0, 19.5] # a sensor dropped one reading
print("max:", max(readings), "| max, NaN first:", max([math.nan, 21.5, 23.0, 19.5]), "| sorted:", sorted(readings))
print("ignoring NaN:", max(x for x in readings if not math.isnan(x)))
max: 23.0 | max, NaN first: nan | sorted: [21.5, nan, 19.5, 23.0]
ignoring NaN: 23.0
Explain, and fix.
D3. A tolerance that's wrong at both ends
A JavaScript geometry module compares numbers with Math.abs(a - b) < Number.EPSILON. It says isn't , and that equals :
const close = (a, b) => Math.abs(a - b) < Number.EPSILON;
console.log(close(0.1 + 0.2, 0.3), close(1000.1 + 0.2, 1000.3), close(1e-20, 2e-20), Number.EPSILON);
const rel = (a, b, tol = 1e-12) => Math.abs(a - b) <= tol * Math.max(Math.abs(a), Math.abs(b));
console.log(rel(0.1 + 0.2, 0.3), rel(1000.1 + 0.2, 1000.3), rel(1e-20, 2e-20));
true false true 2.220446049250313e-16
true true false
Explain, and fix.
D4. Prices that lose a paisa in Decimal
A payments service converts incoming float prices to Decimal before truncating to paise, believing Decimal makes them exact:
from decimal import Decimal, ROUND_DOWN
for price in (19.99, 4.35, 0.29):
print(f"{price}: Decimal(float) = {Decimal(price)}")
print(f" truncated to paise: {Decimal(price).quantize(Decimal('0.01'), ROUND_DOWN)} | from the string: {Decimal(str(price)).quantize(Decimal('0.01'), ROUND_DOWN)}")
19.99: Decimal(float) = 19.989999999999998436805981327779591083526611328125
truncated to paise: 19.98 | from the string: 19.99
4.35: Decimal(float) = 4.3499999999999996447286321199499070644378662109375
truncated to paise: 4.34 | from the string: 4.35
0.29: Decimal(float) = 0.289999999999999980015985556747182272374629974365234375
truncated to paise: 0.28 | from the string: 0.29
Explain, and fix.
Career-oriented
Interview prep
Mid level
Q1. Prove that is irrational, and then say how a computer represents it.
How to get there. The parity proof, then floats as fractions.
Q2. Implement a function that finds a root of a continuous function on an interval, and describe its guarantees and stopping rule.
How to get there. Bisection, the sign condition, and floating-point limits.
Senior level
Q1. A service compares geometric results from two implementations and alerts when they differ. It alerts constantly, though both are correct. Design the comparison.
How to get there. Relative and absolute tolerances, and what accuracy each algorithm promises.
Q2. Your product team wants to display "exact" values like and in a calculator feature. What representation do you propose?
How to get there. Rationals, symbolic forms, and arbitrary precision, and their costs.
Staff level
Q1. Write the numeric-representation guidance for your engineering organisation, covering money, measurements, geometry and identifiers.
How to get there. The whole book: integers, fractions, decimals, floats, units and rounding.
Q2. A research team claims their model predicts an irrational-looking ratio in user behaviour, "0.6180339…, the golden ratio". How do you evaluate the claim?
How to get there. Measurement precision, the impossibility of detecting irrationality from data, and alternative explanations.