A diagonal that is not a fraction
Draw a square whose sides are 1 unit long. By the Pythagorean theorem its diagonal satisfies , so . How long is that, exactly?
People have asked this for a very long time. A clay tablet from Old Babylonian Mesopotamia (about 1800–1600 BCE, now in the Yale collection as YBC 7289) shows a square with its diagonals and the number in base sixty — that is, , correct to about six decimal places. The Indian Śulba-sūtras, manuals for building fire altars, give .
These are superb approximations. But is there a fraction that is exactly ? In this lesson we prove that there is not — and then ask what kind of number must be, if not a fraction.
Crowded, and still full of holes
The fractions (rational numbers) are packed tightly on the number line. Between any two of them, , lies their average ; between and that average lies another; and so on forever. There is no "next" fraction after , and every tiny interval, however short, contains infinitely many fractions. You met this density in Rational numbers.
So it is natural to guess that the fractions cover the whole line. They do not. The point at distance from is surrounded by fractions — , , , , each closer than the last — but none of them lands on it. The fractions are like an infinitely fine sieve: dense, yet full of holes.
The real numbers are what we get when we fill in all the holes. Every point of the line is a real number; the rational ones are special, and the others are called irrational.
Definitions
Informally, a real number is a point on the number line, or equivalently an infinite decimal such as or . (A rigorous construction of from is the subject of Constructing ℤ, ℚ and ℝ; here we use the real numbers and their arithmetic and order as familiar, plus one extra property, completeness, stated below.)
Definition— rational and irrational numbers
A real number is rational if for some integers with . The set of rational numbers is . A real number that is not rational is irrational.
Definition— absolute value and distance
The absolute value of a real number is
It is the distance from to , and is the distance between and . Always , , and .
Definition— intervals
For real numbers :
| Notation | Meaning | Endpoints included? |
|---|---|---|
| all with | neither (open interval) | |
| all with | both (closed interval) | |
| all with | only | |
| all with | — ( is not a number) |
An inequality about distance is a statement about an interval: means , i.e. .
Definition— upper bound and least upper bound
Let be a set of real numbers. A number is an upper bound of if for every ; then is bounded above. A least upper bound (or supremum, ) is an upper bound such that no smaller number is an upper bound: if , some element of is bigger than .
The supremum need not belong to the set: , although . A set has at most one least upper bound (if and were both least, then and ).
Theorem— completeness of ℝ (informal statement)
Every non-empty set of real numbers that is bounded above has a least upper bound in .
In this lesson completeness is taken as a basic property of — the property that says "there are no holes". (It can be proved, once has been built from , for example by Dedekind cuts or Cauchy sequences; Lean's library does exactly that.) The rational numbers satisfy all the usual rules of arithmetic and order, but not completeness — we will prove this below.
Worked examples
Example— Decimals and ordering
To compare two decimals, compare digit by digit from the left: , and . One subtlety: some numbers have two decimal expansions. and are the same real number, just as ; this happens exactly for decimals that end in an infinite string of s. (Why is proved in Sequences and series: a decimal means a sum of an infinite series.)
Example— A repeating decimal is a fraction
Let . Then , and subtracting,
The same trick (multiply by , where is the length of the repeating block, and subtract) turns every eventually repeating decimal into a fraction. Conversely, long division of by can only produce the remainders ; as soon as a remainder recurs, the digits repeat. So a decimal is rational exactly when it terminates or eventually repeats, and the repeating block of has at most digits. For instance uses all possible non-zero remainders.
Example— Absolute value inequalities
means "the distance from to is at most ", i.e. , the interval . And means or , so or : the union .
Example— Suprema, attained and not
- . Every element is less than , so is an upper bound. If , choose with ; then , so is not an upper bound. Hence , and .
- has : here the supremum is the maximum.
- is not bounded above, so it has no supremum in at all. Completeness only promises suprema for sets that are bounded above.
Example— Rational or irrational?
- and are rational.
- , , are irrational (proved below).
- is irrational: a rational plus an irrational is irrational.
- is rational, although both factors are irrational.
- is irrational (Lambert, 1761) — so and are approximations, not values.
Proofs
We start with a fact about parity.
Theorem— Lemma 1 (squares and parity)
For an integer : if is even, then is even.
Proof
We prove the contrapositive: if is odd, then is odd. Write . Then , which is odd.
∎
Theorem— Theorem 1 (√2 is irrational)
There are no natural numbers with and . Consequently is irrational.
Proof
Suppose, for a contradiction, that there were such pairs. By the well-ordering principle, choose one, , in which is as small as possible.
Since is even, is even by Lemma 1; write . Then , so . Thus is another solution of the same equation. Moreover (otherwise ), and , because . So is a solution with a smaller second number than — contradicting the choice of . Hence no solution exists.
Finally, if with integers , , then , and would be a solution in natural numbers with . So is not rational.
∎
This is an argument by infinite descent: any solution would produce a smaller one, and the natural numbers cannot go down forever. (The version you may have seen — "write in lowest terms; then both and are even, a contradiction" — is the same argument: "lowest terms" is where the well-ordering hides.)
What about other square roots? The same descent works for every non-square, with a neat trick that needs no factorisation into primes.
Theorem— Theorem 2 (√n for non-squares)
Let be a positive integer that is not a perfect square. Then is irrational.
Proof
Since is not a square, there is an integer with (take the largest integer with ). Suppose with positive integers, and choose such a representation with as small as possible. Put
These are integers. Since , we have , and gives . And
using and . Since , this writes as a fraction of positive integers with the smaller denominator — a contradiction.
∎
Where does the proof use that is not a square? In the strict inequalities , which give . If is a square, then is a whole number, no integer satisfies them, and indeed already has the smallest possible denominator.
Theorem— Theorem 3 (rational + irrational)
If is rational and is irrational, then is irrational.
Proof
Suppose were rational. Then is a difference of two rationals, which is rational. That contradicts the irrationality of .
∎
No such rule holds for two irrationals: and are rational. (Sometimes the answer is irrational, e.g. — try squaring it — but it has to be checked case by case.)
Theorem— Theorem 4 (triangle inequality)
For all real numbers : .
Proof
From and , adding gives
A number with satisfies (whichever of and is , it is at most ). With and this is the claim.
∎
In terms of distance, the inequality reads (put , ): going from to via is never shorter than going directly. That is where the name comes from.
Now the question Chloe asked. Let
is non-empty () and bounded above by (if then ). The heart of the matter is one clever fraction.
Theorem— Lemma 2 (pushing towards √2)
For a rational put . Then
So if , then and still ; if , then and still .
Proof
Both identities are algebra: , and
Since , the signs of and are those of and .
∎
Theorem— Theorem 5 (ℚ is not complete)
The set has no least upper bound in .
Proof
Suppose were a least upper bound of . Since , . By Theorem 1, . Let , a rational number.
- If : by Lemma 2, and , so is bigger than the upper bound . Impossible.
- If : by Lemma 2, and . Then is an upper bound of : if some had , then (as ) , contradicting . So is an upper bound smaller than the least upper bound . Impossible.
Both cases fail, so no rational least upper bound exists.
∎
In , by completeness, does have a least upper bound , and : the argument of Theorem 5 still rules out , and it rules out once we add that between and there is a rational number, which would then lie in above . This is how completeness creates : the hole in is filled by a real number. Lean confirms below that the supremum is exactly .
The proofs, checked by Lean
The Lean module for this lesson uses Mathlib, Lean's library of mathematics. In Mathlib, Irrational x is defined to mean " is not in the image of the map ", and √2 is Real.sqrt 2.
First the descent of Theorem 1, as a strong induction on , and the deduction that is irrational. The second proof writes a rational number as r.num / r.den (Mathlib keeps rationals in lowest terms with a positive denominator) and passes to absolute values:
/-- **Infinite descent.** If `p² = 2q²` for natural numbers `p, q`, then `q = 0`.
Proof by strong induction on `q`: `p²` is even, so `p = 2k`; then `4k² = 2q²`, i.e.
`q² = 2k²`, a *new* solution `(q, k)` with `k < q` (if `q > 0`). The induction hypothesis
gives `k = 0`, so `q² = 0` and `q = 0` after all. -/
theorem no_nat_sq_eq_two_mul_sq : ∀ q p : ℕ, p ^ 2 = 2 * q ^ 2 → q = 0 := by
intro q
induction q using Nat.strong_induction_on with
| _ q ih =>
intro p h
-- `p²` is even, hence `p` is even: `p = k + k`.
have hp : Even p := (Nat.even_pow.mp (h ▸ even_two_mul (q ^ 2))).1
obtain ⟨k, rfl⟩ := hp
-- Dividing by 2: `q² = 2k²`.
have h2 : q ^ 2 = 2 * k ^ 2 := by nlinarith
by_contra hq
-- The new solution is smaller: `k < q`, because `k² < 2k² = q²`.
have hk : k < q := by
have hq0 : 0 < q := Nat.pos_of_ne_zero hq
have hk0 : 0 < k := by
rcases Nat.eq_zero_or_pos k with h0 | h0
· subst h0; simp at h2; omega
· exact h0
have : k ^ 2 < q ^ 2 := by nlinarith
exact lt_of_pow_lt_pow_left₀ 2 (Nat.zero_le q) this
have hk0 : k = 0 := ih k hk q h2
subst hk0
simp at h2
exact hq h2/-- **√2 is irrational**, proved from `no_nat_sq_eq_two_mul_sq`.
Suppose `√2 = r` with `r` rational, and write `r = a/b` in lowest terms (`a = r.num`,
`b = r.den > 0`). Squaring, `a² = 2b²`; taking absolute values gives a solution in natural
numbers with `b ≠ 0`, which infinite descent forbids. -/
theorem sqrt_two_irrational : Irrational (√2) := by
rintro ⟨r, hr⟩
-- `r² = 2` in `ℚ`.
have hr2 : r ^ 2 = 2 := by
have : ((r ^ 2 : ℚ) : ℝ) = 2 := by
push_cast
rw [hr]
exact Real.sq_sqrt (by norm_num)
exact_mod_cast this
-- `a² = 2 b²` in `ℤ`, where `r = a / b`.
have hint : r.num ^ 2 = 2 * (r.den : ℤ) ^ 2 := by
have h := Rat.mul_den_eq_num r
have : ((r.num : ℚ)) ^ 2 = 2 * ((r.den : ℚ)) ^ 2 := by
rw [← h, mul_pow, hr2]
exact_mod_cast this
-- Pass to natural numbers with absolute values.
have hnat : r.num.natAbs ^ 2 = 2 * r.den ^ 2 := by
have := congrArg Int.natAbs hint
simpa [Int.natAbs_pow, Int.natAbs_mul] using this
exact r.den_nz (no_nat_sq_eq_two_mul_sq r.den r.num.natAbs hnat)Mathlib already knows this theorem, and the general criterion of Theorem 2 (stated there with Mathlib's IsSquare). We apply them here rather than re-prove them, and use the criterion for :
/-- The same theorem from Mathlib: `irrational_sqrt_two`. (Mathlib's proof goes through the
general criterion `irrational_sqrt_natCast_iff` below.) -/
theorem sqrt_two_irrational_library : Irrational (√2) := irrational_sqrt_two/-- **√n for every non-square n.** For a natural number `n`, `√n` is irrational if and only if
`n` is not a perfect square. This applies Mathlib's `irrational_sqrt_natCast_iff`. -/
theorem sqrt_irrational_iff_not_square (n : ℕ) : Irrational (√(n : ℝ)) ↔ ¬ IsSquare n :=
irrational_sqrt_natCast_iff/-- An instance of the criterion: `√3` is irrational, since `3` is not a perfect square
(if `3 = r · r` then `r ≤ 2`, and checking `r = 0, 1, 2` finds no square root). -/
theorem sqrt_three_irrational : Irrational (√(3 : ℝ)) := by
have h : ¬ IsSquare 3 := by
rintro ⟨r, hr⟩
have : r ≤ 2 := by nlinarith
interval_cases r <;> omega
exact_mod_cast (sqrt_irrational_iff_not_square 3).mpr hTheorem 3, the example , and the triangle inequality (by hand, and from the library, where it holds in any ordered abelian group with a lattice structure):
/-- **Rational + irrational = irrational.** If `q + x` were a rational number `r`, then
`x = r - q` would be rational too. (Mathlib: `Irrational.ratCast_add`.) -/
theorem rat_add_irrational (q : ℚ) {x : ℝ} (hx : Irrational x) : Irrational (q + x) := by
rintro ⟨r, hr⟩
apply hx
refine ⟨r - q, ?_⟩
push_cast
rw [hr]
ring/-- **Irrational × irrational can be rational:** `√2` is irrational, yet `√2 · √2 = 2`. -/
theorem irrational_mul_irrational_can_be_rational :
∃ x y : ℝ, Irrational x ∧ Irrational y ∧ ¬ Irrational (x * y) := by
refine ⟨√2, √2, sqrt_two_irrational, sqrt_two_irrational, ?_⟩
rw [Real.mul_self_sqrt (by norm_num : (0 : ℝ) ≤ 2)]
intro h
exact h ⟨2, by norm_num⟩/-- **Triangle inequality** `|x + y| ≤ |x| + |y|`. Since `-|x| ≤ x ≤ |x|` and
`-|y| ≤ y ≤ |y|`, adding gives `-(|x| + |y|) ≤ x + y ≤ |x| + |y|`, which says exactly that
`|x + y| ≤ |x| + |y|`. (Mathlib: `abs_add_le`.) -/
theorem triangle_inequality (x y : ℝ) : |x + y| ≤ |x| + |y| := by
have hx1 := neg_abs_le x
have hx2 := le_abs_self x
have hy1 := neg_abs_le y
have hy2 := le_abs_self y
rw [abs_le]
constructor <;> linarith/-- The triangle inequality from Mathlib, `abs_add_le`, which holds in every lattice-ordered
additive commutative group, not only in `ℝ`. -/
theorem triangle_inequality_library (x y : ℝ) : |x + y| ≤ |x| + |y| := abs_add_le x yCompleteness of and the density of in are theorems of Mathlib about its construction of the real numbers:
/-- **Completeness of ℝ.** Every non-empty set of real numbers that is bounded above has a least
upper bound. In Mathlib this is a *theorem* about its construction of `ℝ` (`Real.exists_isLUB`);
in many textbooks it is taken as an axiom. -/
theorem exists_lub (S : Set ℝ) (hne : S.Nonempty) (hbdd : BddAbove S) : ∃ b, IsLUB S b :=
Real.exists_isLUB hne hbdd/-- **ℚ is dense in ℝ.** Between any two different real numbers there is a rational number.
This applies Mathlib's `exists_rat_btwn` (it holds in every Archimedean ordered field). -/
theorem rat_btwn {x y : ℝ} (h : x < y) : ∃ q : ℚ, x < q ∧ (q : ℝ) < y :=
exists_rat_btwn hAnd Theorem 5 with its lemma, in full. IsLUB S b is Mathlib's "b is a least upper bound of S", and {q : ℚ | q ^ 2 < 2} is our set inside :
/-- No rational number squares to `2`: if `q² = 2` then `√2 = |q|` would be rational. -/
theorem rat_sq_ne_two (q : ℚ) : q ^ 2 ≠ 2 := by
intro hq
apply sqrt_two_irrational
refine ⟨|q|, ?_⟩
have hq' : ((q : ℝ)) ^ 2 = 2 := by exact_mod_cast hq
rw [← hq', Real.sqrt_sq_eq_abs]
push_cast
rfl/-- The key identity behind the next theorem. For `p > 0` put `p' = (2p + 2)/(p + 2)`. Then
`p' - p = (2 - p²)/(p + 2)` and `p'² - 2 = 2(p² - 2)/(p + 2)²`. So if `p² < 2` then `p'` is
*bigger* than `p` but still has `p'² < 2`; if `p² > 2` then `p'` is *smaller* than `p` but still
has `p'² > 2`. -/
theorem push_toward_sqrt_two (p : ℚ) (hp : 0 < p) :
(2 * p + 2) / (p + 2) - p = (2 - p ^ 2) / (p + 2) ∧
((2 * p + 2) / (p + 2)) ^ 2 - 2 = 2 * (p ^ 2 - 2) / (p + 2) ^ 2 := by
have h : p + 2 ≠ 0 := by positivity
constructor
· field_simp
ring
· field_simp
ring/-- **ℚ is not complete.** The set `S = {q ∈ ℚ | q² < 2}` is non-empty (`0 ∈ S`) and bounded
above (by `2`), but it has **no least upper bound in ℚ**.
Suppose `b` were one. Then `b ≥ 1 > 0` because `1 ∈ S`, and `b² ≠ 2` (`rat_sq_ne_two`).
Let `b' = (2b + 2)/(b + 2)`.
* If `b² < 2`, then `b' > b` and `b'² < 2`, so `b' ∈ S` is bigger than the upper bound `b`.
* If `b² > 2`, then `b' < b` and `b'² > 2`, so `b'` is a smaller upper bound than `b`. -/
theorem no_rat_lub : ¬ ∃ b : ℚ, IsLUB {q : ℚ | q ^ 2 < 2} b := by
rintro ⟨b, hub, hleast⟩
have hb1 : 1 ≤ b := hub (show (1 : ℚ) ^ 2 < 2 by norm_num)
have hb : 0 < b := by linarith
obtain ⟨h1, h2⟩ := push_toward_sqrt_two b hb
have hden : 0 < b + 2 := by linarith
set b' := (2 * b + 2) / (b + 2) with hb'
rcases lt_trichotomy (b ^ 2) 2 with hlt | heq | hgt
· -- `b' ∈ S` and `b' > b`: `b` is not an upper bound.
have hbig : b < b' := by
have : 0 < (2 - b ^ 2) / (b + 2) := div_pos (by linarith) hden
linarith
have hin : b' ^ 2 < 2 := by
have : 2 * (b ^ 2 - 2) / (b + 2) ^ 2 < 0 :=
div_neg_of_neg_of_pos (by linarith) (by positivity)
linarith
exact absurd (hub hin) (not_le.mpr hbig)
· exact rat_sq_ne_two b heq
· -- `b'` is a smaller upper bound: `b` is not the least one.
have hsmall : b' < b := by
have : (2 - b ^ 2) / (b + 2) < 0 := div_neg_of_neg_of_pos (by linarith) hden
linarith
have hpos : 0 < b' := by rw [hb']; positivity
have hsq : 2 < b' ^ 2 := by
have : 0 < 2 * (b ^ 2 - 2) / (b + 2) ^ 2 := div_pos (by linarith) (by positivity)
linarith
have hupper : b' ∈ upperBounds {q : ℚ | q ^ 2 < 2} := by
intro s hs
-- If `s > b' > 0` then `s² > b'² > 2`, so `s ∉ S`.
by_contra hcon
have hlt : b' < s := lt_of_not_ge hcon
have : b' ^ 2 < s ^ 2 := by nlinarith
have hs' : s ^ 2 < 2 := hs
linarith
exact absurd (hleast hupper) (not_le.mpr hsmall)Finally, viewed inside , the same set of rationals has least upper bound exactly . The proof uses density: below any there is room for a rational between and .
/-- In `ℝ` the same set does have a least upper bound, namely `√2`: the gap in `ℚ` is filled.
Every `q ∈ S` has `q ≤ |q| = √(q²) < √2`; and if `c < √2` is any real number, density gives a
rational `q` with `max c 0 < q < √2`, so `q² < 2` and `q > c`: `c` is not an upper bound. -/
theorem sqrt_two_is_lub_in_reals :
IsLUB {x : ℝ | ∃ q : ℚ, (q : ℝ) = x ∧ q ^ 2 < 2} (√2) := by
constructor
· rintro x ⟨q, rfl, hq⟩
have hq' : ((q : ℝ)) ^ 2 < 2 := by exact_mod_cast hq
calc (q : ℝ) ≤ |(q : ℝ)| := le_abs_self _
_ = √((q : ℝ) ^ 2) := (Real.sqrt_sq_eq_abs _).symm
_ ≤ √2 := Real.sqrt_le_sqrt hq'.le
· intro c hc
by_contra hlt
push Not at hlt
have h0 : max c 0 < √2 := max_lt hlt (by positivity)
obtain ⟨q, hq1, hq2⟩ := exists_rat_btwn h0
have hqpos : (0 : ℝ) < q := lt_of_le_of_lt (le_max_right c 0) hq1
have hsq : ((q : ℝ)) ^ 2 < 2 := by
have := pow_lt_pow_left₀ hq2 hqpos.le (two_ne_zero)
rwa [Real.sq_sqrt (by norm_num)] at this
have hmem : (q : ℝ) ∈ {x : ℝ | ∃ q : ℚ, (q : ℝ) = x ∧ q ^ 2 < 2} :=
⟨q, rfl, by exact_mod_cast hsq⟩
have := hc hmem
linarith [le_max_left c 0]What is not formalised here: decimal expansions (Mathlib has the tools, but we did not state the "terminates or repeats" theorem), and our own proof of Theorem 2. For that we cite Mathlib's theorem, which takes a different route: a whole number that is the square of a fraction is the square of a whole number (Rat.isSquare_natCast_iff).
Squeezing, searching and long division
"""Squeezing sqrt(2) between rationals, and searching for p^2 = 2 q^2.
The rational map p -> (2p + 2)/(p + 2) sends every positive rational with
p^2 < 2 to a *larger* one with the same property, and every rational with
p^2 > 2 to a *smaller* one with the same property. Iterating it in exact
rational arithmetic shows, case by case, why the set {q in Q : q^2 < 2} has
no largest element and no least rational upper bound. A brute-force search
then finds no solution of p^2 = 2 q^2 with 1 <= q <= 100000 (evidence only;
the lesson's descent argument is the proof), while the near misses
p^2 - 2 q^2 = +-1 show how close fractions can get to sqrt(2).
"""
import math
from fractions import Fraction
def push(p):
"""The map p -> (2p + 2)/(p + 2), in exact arithmetic for Fractions."""
return (2 * p + 2) / (p + 2)
def orbit(p0, steps):
"""Return [p0, push(p0), push(push(p0)), ...] with ``steps`` applications."""
if steps < 0:
raise ValueError("steps must be non-negative")
values = [Fraction(p0)]
for _ in range(steps):
values.append(push(values[-1]))
return values
def square_minus_two(p):
"""p^2 - 2 (exact for Fractions): negative below sqrt(2), positive above."""
return p * p - 2
def solutions_sq_eq_two_sq(limit):
"""All (p, q) with 1 <= q <= limit and p^2 = 2 q^2 (there are none)."""
found = []
for q in range(1, limit + 1):
p = math.isqrt(2 * q * q)
if p * p == 2 * q * q:
found.append((p, q))
return found
def near_misses(limit):
"""Pairs (p, q), q <= limit, with p^2 - 2 q^2 = +1 or -1."""
pairs = []
for q in range(1, limit + 1):
for p in (math.isqrt(2 * q * q), math.isqrt(2 * q * q) + 1):
if abs(p * p - 2 * q * q) == 1:
pairs.append((p, q))
return pairs
def main():
root = math.sqrt(2)
for start, side in ((1, "below"), (2, "above")):
print(f"Starting {side} sqrt(2) at p = {start}:")
for p in orbit(start, 5):
sign = "<" if square_minus_two(p) < 0 else ">"
gap = abs(float(p) - root)
print(f" p = {str(p):>9} p^2 {sign} 2 |p - sqrt 2| = {gap:.2e}")
print("Each step stays on its side of sqrt(2) and gets closer: no rational")
print("is the largest below sqrt(2) or the smallest above it.")
print()
limit = 100000
sols = solutions_sq_eq_two_sq(limit)
print(f"Solutions of p^2 = 2q^2 with 1 <= q <= {limit}: {len(sols)}")
misses = near_misses(1000)
print("Near misses p^2 - 2q^2 = +-1 with q <= 1000 (fractions p/q):")
print(" " + ", ".join(f"{p}/{q}" for p, q in misses))
print()
print("Epistemic status: the orbits are exact rational computations, but")
print("only finitely many steps; the lesson's algebra proves the pattern")
print("for every p. The search is exhaustive only up to q = 100000; that")
print("no solution exists at all is proved by infinite descent, not here.")
if __name__ == "__main__":
main()The orbits climb towards from below and descend from above, each step staying on its own side — the two cases of Theorem 5, live. The fractions with are exceptionally good approximations: each is closer to than every fraction with a smaller denominator. The Śulba-sūtras' is one of them. The search finds no exact solution up to , which is evidence, not proof — Theorem 1 covers every at once.
"""Decimal expansions: fractions repeat, sqrt(2) and pi need not.
Long division of p by q can only meet q different remainders, so the digits
of a fraction must eventually repeat, with a period of at most q - 1 digits.
The experiment computes exact expansions (pre-period and period) of a few
fractions, then the first 40 digits of sqrt(2) (exactly, with integer square
roots) and of pi (exactly, with Machin's formula in integer arithmetic), and
compares pi with the famous approximations 22/7 and 355/113.
"""
import math
def decimal_expansion(p, q):
"""Return (whole part, pre-period digits, period digits) of p/q >= 0.
Long division: a remainder that comes back starts the repeating block.
A terminating decimal has period "0".
"""
if q <= 0 or p < 0:
raise ValueError("need p >= 0 and q > 0")
whole, r = divmod(p, q)
digits, seen = [], {}
while r not in seen:
seen[r] = len(digits)
d, r = divmod(10 * r, q)
digits.append(str(d))
start = seen[r]
return whole, "".join(digits[:start]), "".join(digits[start:])
def sqrt_digits(n, k):
"""The first k decimal digits of sqrt(n) after the point (truncated)."""
root = math.isqrt(n * 10 ** (2 * k))
return str(root)[-k:] if k else ""
def arctan_inv(x, scale):
"""scale * arctan(1/x) for an integer x > 1, by the alternating series."""
total, term, k, sign = 0, scale // x, 1, 1
while term:
total += sign * (term // k)
term //= x * x
k += 2
sign = -sign
return total
def pi_digits(k):
"""The first k decimal digits of pi after the point (truncated).
Machin (1706): pi = 16 arctan(1/5) - 4 arctan(1/239); 10 guard digits.
"""
scale = 10 ** (k + 10)
pi_scaled = 16 * arctan_inv(5, scale) - 4 * arctan_inv(239, scale)
return str(pi_scaled // 10 ** 10)[1:k + 1]
def fraction_digits(p, q, k):
"""The first k digits of p/q after the point."""
return str((p % q) * 10 ** k // q).zfill(k)
def agreement(a, b):
"""Number of leading digits two digit strings share."""
n = 0
while n < min(len(a), len(b)) and a[n] == b[n]:
n += 1
return n
def main():
print("Fractions: long division must repeat (period at most q - 1).")
for p, q in [(3, 8), (1, 7), (5, 12), (22, 7), (1, 97)]:
whole, pre, per = decimal_expansion(p, q)
shown = per if len(per) <= 24 else per[:24] + "..."
print(f" {p}/{q} = {whole}.{pre}({shown}) period {len(per)}")
print()
root2 = sqrt_digits(2, 40)
pi = pi_digits(40)
print(f"sqrt(2) = 1.{root2}...")
print(f"pi = 3.{pi}...")
for p, q in [(22, 7), (355, 113)]:
digits = fraction_digits(p, q, 40)
same = agreement(pi, digits)
print(f"{p}/{q} = 3.{digits[:12]}... agrees with pi to {same} decimals")
print("These digits show no repeating block, but finitely many digits")
print("decide nothing: 1/97 needs 96 digits before its block repeats.")
print()
print("Epistemic status: all digits are exact integer computations (the")
print("pi digits rely on Machin's formula with 10 guard digits). Finding no")
print("repetition in finitely many digits proves nothing; sqrt(2) is")
print("irrational by the lesson's proof, and pi by Lambert's (1761).")
if __name__ == "__main__":
main()The long-division experiment shows the remainder argument at work: needs all possible remainders before it repeats. Forty digits of or with no repeating block prove nothing on their own — the next million digits might start repeating, as far as any finite check can tell. Irrationality is decided by proof.
Explore: a staircase to √2
The cobweb below iterates the map of Lemma 2, . A fixed point satisfies , i.e. : the staircase heads for .
Iterating x ↦ (2x + 2)/(x + 2)
Start below √2 (try x₀ = 1) and above it (try x₀ = 2.4). Does an orbit ever cross √2?
Iterates xₖ against k
- y = f(x)
- y = x
- cobweb path
Last iterates: x10 = 1.41421, x11 = 1.41421, x12 = 1.41421
The orbit appears to settle at a fixed point x* ≈ 1.41421.
Fixed points in view (numerical): x* = 1.4142 (attracting: |f′(x*)| < 1)
Based on 3,000 iterations in floating-point arithmetic: numerical evidence, not proof.
Try several starting values. Every positive start converges to , and an orbit that starts below stays below. If every iterate is a fraction, why is the limit not a fraction? Because a limit of rationals need not be rational — which is exactly what it means for to have holes.
Exercises
1. Real numbers and irrationality
Warm-upHumanWhich of these numbers are irrational? (Choose all that apply.)
2. Real numbers and irrationality
Warm-upHumanWrite (the block repeating forever) as a fraction in lowest terms. What is the denominator ?
3. Real numbers and irrationality
Warm-upHumanHow many integers satisfy ?
4. Real numbers and irrationality
CoreHumanIn the proof that has no solution with , we write: "Since is even, is even." Which fact justifies this step?
5. Real numbers and irrationality
CoreHumanA student copies the proof for to "prove" that is irrational: "Suppose with as small as possible. Then is divisible by , so is divisible by ; write . Then , so — a smaller solution." Since , something is wrong. Which step fails?
6. Real numbers and irrationality
CoreHumanLet . Which statement is true?
7. Real numbers and irrationality
CoreHumanWhich pair is a counterexample to the claim "if and are irrational, then is irrational"?
8. Real numbers and irrationality
StretchFormalWhich Lean statement says that is not complete, using the set ? (IsLUB S b means " is a least upper bound of ".)
9. Real numbers and irrationality
StretchComputationalWrite repetend_length(p, q) for integers and : the length of the repeating block of the decimal expansion of , or 0 if the decimal terminates. Use long division and remember the position at which each remainder first appeared. For example gives 6, gives 1, and gives 0.
Common misconceptions
Misconception
"" or "". These are approximations. agrees with only to two decimal places, and Zu Chongzhi's to six. Since is irrational, no fraction and no terminating decimal equals it.
Misconception
"A long decimal that never seems to repeat could still be a fraction." If you know the decimal never repeats, it is not a fraction: every fraction's decimal terminates or repeats with period at most . What a finite list of digits cannot tell you is whether it never repeats — that needs a proof about the number.
Misconception
"The product (or sum) of two irrational numbers is irrational." , , and . Only "rational irrational" and "non-zero rational irrational" are guaranteed irrational.
Misconception
" is just below ." The decimal is the limit of , whose distances from are — eventually below any positive number. A limit is a single number, and here it is exactly .
Misconception
"Irrational numbers are rare exceptions." It is the other way round. The rationals can be listed in one infinite sequence, but the reals cannot (Cantor's diagonal argument, on the How many infinities? trail). In that precise sense almost every real number is irrational.
Other ways of seeing
Geometry— Incommensurable lengths
For Greek geometers the discovery was about lengths, not numbers. Two segments are commensurable if both are whole-number multiples of a common unit. Theorem 1 says the side and diagonal of a square are incommensurable: no unit, however small, measures both exactly. Euclid's Elements (Book X) builds a whole classification of incommensurable lengths, and Eudoxus' theory of ratios (Book V) compares them by asking which fractions lie below and which above — an idea that Dedekind turned into a construction of in 1872.
Number theory— The best fractions for √2
The near misses in the experiment — — are solutions of a Pell equation. Each comes from the previous one by , and they are the convergents of the continued fraction . Dividing by shows : irrational numbers can be approximated remarkably well, and how well is a deep question of number theory (Diophantine approximation).
Analysis— Why calculus needs completeness
Over , the function is negative at and positive at , yet it is never at a rational point: the intermediate value theorem fails in . Completeness is exactly what repairs it, and with it the existence of limits of increasing bounded sequences, of maxima of continuous functions on , and of integrals. Every theorem of real analysis leans on it.
Set theory— Countably many fractions, uncountably many reals
The rationals can be listed as a sequence (go through by increasing ), so is countable. Cantor proved in 1874 that is not: any list of reals misses one. So irrational numbers are not the exception but the rule. See Countability and Cantor's diagonal argument.
Wonder Trails
The irrational numbers outnumber the rationals — in a sense that can be made completely precise.
Wonder Trail · Optional · never gradedHow many infinities?There are infinitely many counting numbers and infinitely many infinite 0–1 sequences. Are these two infinities the same size?Follow the trailHistory and global context
- Mesopotamia and India. The Old Babylonian tablet YBC 7289 (about 1800–1600 BCE) records in base sixty. The Baudhāyana Śulba-sūtra (first millennium BCE) gives the approximation , used for constructing altars of prescribed areas. Neither source asks whether an exact fraction exists.
- Greece. The discovery that side and diagonal are incommensurable was made among the Pythagoreans, probably in the 5th century BCE; the story that Hippasus was drowned for revealing it is a later legend. Plato's Theaetetus reports that Theodorus of Cyrene proved the irrationality of . Aristotle alludes to the classical parity proof for , and Euclid's Elements (about 300 BCE) sets out Eudoxus' theory of proportion and, in Book X, a theory of incommensurable magnitudes.
- China, India and the Islamic world. Zu Chongzhi (5th century CE) showed that lies between and and proposed the approximation ; his bounds were not improved for nearly a thousand years. Āryabhaṭa (499 CE) gave and called it "approximate". In the 11th century Omar Khayyam, commenting on Euclid, argued that ratios of incommensurable magnitudes could be treated as numbers.
- Europe. Simon Stevin popularised decimal fractions (De Thiende, 1585). Johann Heinrich Lambert proved irrational in 1761. In 1872 Richard Dedekind (cuts) and Georg Cantor (Cauchy sequences), building on ideas of Charles Méray and Karl Weierstrass, published rigorous constructions of from , and in 1874 Cantor proved that is uncountable.
Further reading
- Ivan Niven, Numbers: Rational and Irrational (1961) — a short, readable book on exactly this lesson's themes.
- Richard Courant and Herbert Robbins, What Is Mathematics? (1941), chapter II on the number system.
- G. H. Hardy and E. M. Wright, An Introduction to the Theory of Numbers (1938), chapter IV (irrational numbers) and the chapters on continued fractions.
- Richard Dedekind, Continuity and Irrational Numbers (1872; English translation in Essays on the Theory of Numbers, 1901).
- Walter Rudin, Principles of Mathematical Analysis (3rd edition, 1976), chapter 1, which opens with the map — the same map as Lemma 2.
- Michael Spivak, Calculus (1967), chapters 1–2 and 8 on the properties of numbers and least upper bounds.