Skip to content
The Lumenary
Early undergraduateUndergraduate (first year) 120 min

Constructing ℤ, ℚ and ℝ

Starting from nothing but the counting numbers, build the integers from pairs, the fractions from pairs of those, and the real line from cuts or from sequences — and prove that the result is the only complete ordered field there is.

Formally verified · 25 LeanComputationally tested · 2 PythonAI-drafted · awaiting human reviewMathematically reviewed: Awaiting human review
MotivationH

Do the numbers exist?

Since school you have calculated with −3-3, with 25\tfrac25 and with 2\sqrt 2, using rules such as (−a)(−b)=ab(-a)(-b) = ab and "every bounded increasing sequence has a limit". In the lessons on integers and real numbers we derived consequences of such rules. But a list of rules can be contradictory, and nothing so far guarantees that some system actually obeys all of them at once. The axioms of a "complete ordered field", for instance, ask a great deal: a field, with an order compatible with ++ and ×\times, in which every non-empty bounded set has a least upper bound. Is there such a thing?

This lesson answers yes, by building one. Starting only from the natural numbers 0,1,2,…0, 1, 2, \dots and the language of sets, we construct Z\Z, then Q\Q, then R\R — and at the end we prove that the result is essentially unique: any two complete ordered fields are the same field with the elements renamed. Leopold Kronecker is reported to have said that "God made the integers; all else is the work of man". The constructions show how much of that work can be done with the natural numbers alone.

IntuitionH

One idea, used three times

Each construction repairs a defect by adding formal expressions for the missing numbers, and then declaring when two expressions should name the same number.

  • N\N has no solution of x+3=1x + 3 = 1. So we introduce formal differences "a−ba - b" for pairs (a,b)(a, b) of naturals — and since 1−31 - 3 and 5−75 - 7 should be equal, we identify (a,b)(a, b) with (c,d)(c, d) when a+d=c+ba + d = c + b.
  • Z\Z has no solution of 3x=13x = 1. So we introduce formal quotients "a/ba/b" with b≠0b \neq 0, identifying (a,b)(a, b) with (c,d)(c, d) when ad=cbad = cb.
  • Q\Q has no number whose square is 22: the rationals below 2\sqrt 2 have no least upper bound in Q\Q. So we introduce, for each "gap", the set of rationals below it (a Dedekind cut) — or a sequence of rationals crowding towards it (a Cauchy sequence), identifying sequences that crowd towards the same place.

"Identifying" means passing to equivalence classes (see equivalence relations). The price is that every operation must be checked to be well defined: the answer must not depend on which member of a class we compute with. The Remainder families Wonder Trail, linked below, shows the same phenomenon for remainders.

The two sequences below are made of fractions only. The first iterates x↦12(x+2x)x \mapsto \tfrac12\big(x + \tfrac2x\big) from above, the second q↦2q+2q+2q \mapsto \tfrac{2q + 2}{q + 2} from below. Both crowd towards the same point — a point that is not a fraction.

Babylonian iteration: fractions from above

Every term is a fraction; the fixed point x = √2 is not.

f(x) = (x + 2/x)/2

x₀

Iterates xₖ against k

  • y = f(x)
  • y = x
  • cobweb path

Last iterates: x4 = 1.41421, x5 = 1.41421, x6 = 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.

Climbing towards √2 from below

Each step stays in the cut {q : q² < 2} and gets closer to its upper edge.

f(x) = (2·x + 2)/(x + 2)

x₀

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.

DefinitionsH

Definitions

Definition— well-defined operation on classes

Let ∼\sim be an equivalence relation on a set XX with classes [x][x]. A function f:X×X→Xf : X \times X \to X induces an operation on classes, [x]∗[y]=[f(x,y)][x] \ast [y] = [f(x, y)], if it is compatible with ∼\sim: whenever x∼x′x \sim x' and y∼y′y \sim y', also f(x,y)∼f(x′,y′)f(x, y) \sim f(x', y'). We then say the operation is well defined.

Definition— ordered field

An ordered field is a field FF with a total order ≤\le such that x≤yx \le y implies x+z≤y+zx + z \le y + z, and 0≤x0 \le x, 0≤y0 \le y imply 0≤xy0 \le xy. An upper bound of S⊆FS \subseteq F is a bb with s≤bs \le b for all s∈Ss \in S; a least upper bound or supremum is an upper bound below every other upper bound (see order theory). FF is complete if every non-empty subset that is bounded above has a supremum in FF, and Archimedean if for every x∈Fx \in F there is a natural number nn with x<nx < n.

Definition— Dedekind cut

A Dedekind cut is a subset A⊆QA \subseteq \Q such that

  1. A≠∅A \neq \varnothing and A≠QA \neq \Q;
  2. AA is closed downwards: if p∈Ap \in A and q<pq < p, then q∈Aq \in A;
  3. AA has no greatest element: for every p∈Ap \in A there is q∈Aq \in A with p<qp < q.

Picture a cut as "all the rationals strictly to the left of a point on the line". For a rational rr the cut r∗={q∈Q:q<r}r^\ast = \{q \in \Q : q < r\} describes rr itself; condition 3 makes this the only cut describing rr (we do not allow {q≤r}\{q \le r\}).

Definition— Cauchy sequence of rationals

A sequence (qn)(q_n) of rationals is Cauchy if for every rational ε>0\varepsilon > 0 there is NN with ∣qm−qn∣<ε|q_m - q_n| < \varepsilon for all m,n≥Nm, n \geq N. Two Cauchy sequences are equivalent if their difference tends to 00: for every rational ε>0\varepsilon > 0, ∣qn−rn∣<ε|q_n - r_n| < \varepsilon for all large nn.

ProofH

The integers from pairs of naturals

On N×N\N \times \N define (a,b)∼(c,d)(a, b) \sim (c, d) if a+d=c+ba + d = c + b. Think of (a,b)(a, b) as "a−ba - b"; the condition is a−b=c−da - b = c - d rearranged so that it makes sense in N\N, where subtraction is not always possible.

Theorem— Proposition 1

∼\sim is an equivalence relation on N×N\N \times \N.

Proof

Reflexivity (a+b=a+ba + b = a + b) and symmetry are clear. For transitivity, suppose a+d=c+ba + d = c + b and c+f=e+dc + f = e + d. Adding,

(a+f)+(c+d)=(a+d)+(c+f)=(c+b)+(e+d)=(e+b)+(c+d),(a + f) + (c + d) = (a + d) + (c + f) = (c + b) + (e + d) = (e + b) + (c + d),

and cancelling c+dc + d — legitimate in N\N, where x+k=y+kx + k = y + k implies x=yx = y — gives a+f=e+ba + f = e + b, i.e. (a,b)∼(e,f)(a, b) \sim (e, f).

∎

Define Z\Z to be the set of equivalence classes. Guided by (a−b)+(c−d)=(a+c)−(b+d)(a - b) + (c - d) = (a + c) - (b + d) and (a−b)(c−d)=(ac+bd)−(ad+bc)(a - b)(c - d) = (ac + bd) - (ad + bc), set

[(a,b)]+[(c,d)]=[(a+c, b+d)],[(a,b)]⋅[(c,d)]=[(ac+bd, ad+bc)].[(a, b)] + [(c, d)] = [(a + c,\, b + d)], \qquad [(a, b)] \cdot [(c, d)] = [(ac + bd,\, ad + bc)].

Theorem— Proposition 2 (well-definedness)

These formulas define operations on equivalence classes: equivalent inputs give equivalent outputs.

Proof

Addition. If a+b′=a′+ba + b' = a' + b and c+d′=c′+dc + d' = c' + d, then adding the two equations gives (a+c)+(b′+d′)=(a′+c′)+(b+d)(a + c) + (b' + d') = (a' + c') + (b + d), which says (a+c,b+d)∼(a′+c′,b′+d′)(a + c, b + d) \sim (a' + c', b' + d').

Multiplication. It suffices to change one factor at a time, because ∼\sim is transitive. Suppose a+b′=a′+ba + b' = a' + b; we show (ac+bd,ad+bc)∼(a′c+b′d,a′d+b′c)(ac + bd, ad + bc) \sim (a'c + b'd, a'd + b'c), that is,

(ac+bd)+(a′d+b′c)=(a′c+b′d)+(ad+bc).(ac + bd) + (a'd + b'c) = (a'c + b'd) + (ad + bc).

Group the left side as (a+b′)c+(a′+b)d(a + b')c + (a' + b)d and the right side as (a′+b)c+(a+b′)d(a' + b)c + (a + b')d. Since a+b′=a′+ba + b' = a' + b, these are equal. Changing the second factor is the same computation with the roles exchanged.

∎

The ring axioms for Z\Z now follow from those of N\N by computing with representatives; for example associativity of addition reduces to associativity in each coordinate. The class 0=[(0,0)]0 = [(0, 0)] is the additive identity, 1=[(1,0)]1 = [(1, 0)] the multiplicative identity, and −[(a,b)]=[(b,a)]-[(a, b)] = [(b, a)], because (a+b,b+a)∼(0,0)(a + b, b + a) \sim (0, 0). The map n↦[(n,0)]n \mapsto [(n, 0)] embeds N\N in Z\Z preserving ++ and ×\times, and every class is [(n,0)][(n, 0)] or [(0,n)][(0, n)] for a unique nn (subtract the smaller coordinate from both), so Z\Z consists of the natural numbers and their negatives — exactly the integers we know. The order is [(a,b)]≤[(c,d)][(a, b)] \le [(c, d)] if a+d≤c+ba + d \le c + b.

Example— A rule that is not well defined

Why not multiply pairs componentwise, [(a,b)]⋆[(c,d)]=[(ac,bd)][(a, b)] \star [(c, d)] = [(ac, bd)]? Because (0,0)∼(1,1)(0, 0) \sim (1, 1) (both stand for 00) while (0,0)⋆(0,1)=(0,0)(0, 0) \star (0, 1) = (0, 0) and (1,1)⋆(0,1)=(0,1)(1, 1) \star (0, 1) = (0, 1), and (0,0)≁(0,1)(0, 0) \not\sim (0, 1). The "product" of the number 00 and the number −1-1 would depend on how 00 was written. Well-definedness is never automatic.

ProofH

The rationals as a field of fractions

The same recipe works over any integral domain DD — a commutative ring with 0≠10 \neq 1 and no zero divisors (ab=0ab = 0 implies a=0a = 0 or b=0b = 0). On pairs (a,b)∈D×(D∖{0})(a, b) \in D \times (D \setminus \{0\}) define (a,b)∼(c,d)(a, b) \sim (c, d) if ad=cbad = cb.

Theorem— Proposition 3

∼\sim is an equivalence relation, and the operations

[(a,b)]+[(c,d)]=[(ad+cb, bd)],[(a,b)]⋅[(c,d)]=[(ac, bd)][(a, b)] + [(c, d)] = [(ad + cb,\, bd)], \qquad [(a, b)] \cdot [(c, d)] = [(ac,\, bd)]

are well defined. The classes form a field Frac⁡(D)\operatorname{Frac}(D), the field of fractions of DD, and a↦[(a,1)]a \mapsto [(a, 1)] is an injective ring homomorphism D→Frac⁡(D)D \to \operatorname{Frac}(D).

Proof

Transitivity. Suppose ad=cbad = cb and cf=edcf = ed, with b,d,f≠0b, d, f \neq 0. Then

(af)d=(ad)f=(cb)f=b(cf)=b(ed)=(eb)d,(af)d = (ad)f = (cb)f = b(cf) = b(ed) = (eb)d,

and since d≠0d \neq 0 and DD has no zero divisors, (af−eb)d=0(af - eb)d = 0 forces af=ebaf = eb.

The operations make sense: bd≠0bd \neq 0 because b,d≠0b, d \neq 0 — no zero divisors again.

Addition is well defined. Let ab′=a′bab' = a'b. Then (ad+cb)(b′d)=(ab′)d2+cbb′d=(a′b)d2+cbb′d=(a′d+cb′)(bd)(ad + cb)(b'd) = (ab')d^2 + cbb'd = (a'b)d^2 + cbb'd = (a'd + cb')(bd), so (ad+cb,bd)∼(a′d+cb′,b′d)(ad + cb, bd) \sim (a'd + cb', b'd); similarly in the second argument. Multiplication: (ac)(b′d)=(ab′)cd=(a′b)cd=(a′c)(bd)(ac)(b'd) = (ab')cd = (a'b)cd = (a'c)(bd).

Field axioms. They follow from those of DD by computing with representatives; [(0,1)][(0, 1)] and [(1,1)][(1, 1)] are the zero and identity, and if [(a,b)]≠0[(a, b)] \neq 0 then a≠0a \neq 0 and [(b,a)][(b, a)] is its inverse, since (ab,ba)∼(1,1)(ab, ba) \sim (1, 1). Finally [(a,1)]=[(a′,1)][(a, 1)] = [(a', 1)] means a=a′a = a', so a↦[(a,1)]a \mapsto [(a, 1)] is injective.

∎

Taking D=ZD = \Z gives Q\Q. Writing a/ba/b for [(a,b)][(a, b)], the definitions become the familiar rules for fractions. Every fraction has a representative with b>0b > 0, and a/b≤c/da/b \le c/d (with b,d>0b, d > 0) is defined by ad≤cbad \le cb; this makes Q\Q an ordered field.

Example— Where zero divisors break the construction

Over Z/6Z\Z/6\Z, which has zero divisors (2⋅3=02 \cdot 3 = 0), the same definition is not even transitive: 3/1∼0/23/1 \sim 0/2 (as 3⋅2=0=0⋅13 \cdot 2 = 0 = 0 \cdot 1) and 0/2∼0/10/2 \sim 0/1, but 3/1≁0/13/1 \not\sim 0/1 (as 3⋅1≠03 \cdot 1 \neq 0). One would be forced to declare 3=03 = 0. Rings with zero divisors can still be "localised", but only by inverting carefully chosen elements, and information is lost.

Universal property. Frac⁡(D)\operatorname{Frac}(D) is the smallest field containing DD, in a precise sense: every injective ring homomorphism g:D→Kg : D \to K into a field extends to exactly one ring homomorphism Frac⁡(D)→K\operatorname{Frac}(D) \to K, namely a/b↦g(a)g(b)−1a/b \mapsto g(a)g(b)^{-1}. For D=ZD = \Z there is even less freedom: there is at most one ring homomorphism from Q\Q to any ring.

ProofH

The real numbers from Dedekind cuts

Let R\R be the set of Dedekind cuts, ordered by inclusion: A≤BA \le B means A⊆BA \subseteq B. Each rational rr gives the cut r∗={q:q<r}r^\ast = \{q : q < r\}, and r≤sr \le s if and only if r∗⊆s∗r^\ast \subseteq s^\ast, so Q\Q sits inside R\R with its order. But there are new cuts too:

Theorem— Proposition 4 (a cut for √2)

S={q∈Q:q<0 or q2<2}S = \{q \in \Q : q < 0 \text{ or } q^2 < 2\} is a Dedekind cut, and it is not of the form r∗r^\ast for any rational rr.

Proof

0∈S0 \in S and 2∉S2 \notin S. If p∈Sp \in S and q<pq < p: either q<0q < 0, or 0≤q<p0 \le q < p, in which case p≥0p \geq 0, so p2<2p^2 < 2 and q2<p2<2q^2 < p^2 < 2. For no greatest element, let p∈Sp \in S. If p<0p < 0, then 0∈S0 \in S is larger. If p≥0p \geq 0, then p2<2p^2 < 2; put q=2p+2p+2q = \frac{2p + 2}{p + 2}. Then

q−p=2−p2p+2>0,q2−2=(2p+2)2−2(p+2)2(p+2)2=2(p2−2)(p+2)2<0,q - p = \frac{2 - p^2}{p + 2} > 0, \qquad q^2 - 2 = \frac{(2p + 2)^2 - 2(p + 2)^2}{(p + 2)^2} = \frac{2(p^2 - 2)}{(p + 2)^2} < 0,

so q∈Sq \in S and q>pq > p. Finally, if S=r∗S = r^\ast, then r∉Sr \notin S but every rational below rr is in SS; as 1∈S1 \in S, r>1>0r > 1 > 0, and r2≥2r^2 \geq 2. If r2>2r^2 > 2, the same map gives q=2r+2r+2q = \frac{2r + 2}{r + 2} with 0<q<r0 < q < r and q2−2=2(r2−2)(r+2)2>0q^2 - 2 = \frac{2(r^2 - 2)}{(r + 2)^2} > 0, so q∈r∗∖Sq \in r^\ast \setminus S — impossible. Hence r2=2r^2 = 2, contradicting the irrationality of 2\sqrt 2 (proved in the lesson on real numbers).

∎

Theorem— Proposition 5 (cuts are totally ordered)

For any cuts A,BA, B, either A⊆BA \subseteq B or B⊆AB \subseteq A.

Proof

Suppose A⊈BA \not\subseteq B, and pick p∈A∖Bp \in A \setminus B. Let q∈Bq \in B. If q≥pq \geq p, then p∈Bp \in B (as p=qp = q or p<qp < q and BB is closed downwards) — a contradiction. So q<pq < p, and q∈Aq \in A because AA is closed downwards. Thus B⊆AB \subseteq A.

∎

Theorem— Theorem 6 (least-upper-bound property)

Let S\mathcal{S} be a non-empty set of cuts that is bounded above by some cut BB. Then the union U=⋃A∈SAU = \bigcup_{A \in \mathcal{S}} A is a cut, and it is the least upper bound of S\mathcal{S}.

Proof

UU is a cut. It is non-empty, because S\mathcal{S} contains some cut, which is non-empty. It is not all of Q\Q: every A∈SA \in \mathcal{S} is contained in BB, so U⊆B≠QU \subseteq B \neq \Q. It is closed downwards: if p∈Up \in U, then p∈Ap \in A for some A∈SA \in \mathcal{S}, and every q<pq < p lies in A⊆UA \subseteq U. It has no greatest element: if p∈A∈Sp \in A \in \mathcal{S}, then AA contains some q>pq > p, and q∈Uq \in U.

UU is an upper bound, since A⊆UA \subseteq U for every A∈SA \in \mathcal{S}. It is the least one: if CC is a cut with A⊆CA \subseteq C for every A∈SA \in \mathcal{S}, then U⊆CU \subseteq C.

∎

The lattice-theoretic content is striking: in the ordered set of cuts, suprema are simply unions. Everything else is work. Addition is defined by A+B={a+b:a∈A,b∈B}A + B = \{a + b : a \in A, b \in B\} (with 0∗0^\ast as identity), and multiplication first for positive cuts by A⋅B={q:q≤ab for some a∈A,b∈B with a,b>0}A \cdot B = \{q : q \le ab \text{ for some } a \in A, b \in B \text{ with } a, b > 0\}, then extended by the sign rules. Checking that this gives an ordered field takes several pages of routine verification; see Rudin's Principles of Mathematical Analysis, appendix to chapter 1. The result:

Theorem— Theorem 7 (Dedekind)

The Dedekind cuts, with these operations and the inclusion order, form a complete ordered field, and r↦r∗r \mapsto r^\ast embeds Q\Q in it as an ordered subfield.

Proof: completeness is Theorem 6; the field and order axioms are a long verification, which we do not reproduce (see the reading list).

ExplanationH

The real numbers from Cauchy sequences

Cantor and Méray proposed a different construction, closer to how we compute with real numbers. Let C\mathcal{C} be the set of Cauchy sequences of rationals, and identify equivalent ones. The sequences

1, 1.4, 1.41, 1.414, …and2, 32, 1712, 577408, …1,\ 1.4,\ 1.41,\ 1.414,\ \dots \qquad\text{and}\qquad 2,\ \tfrac32,\ \tfrac{17}{12},\ \tfrac{577}{408},\ \dots

(the decimal truncations of 2\sqrt 2 and the Babylonian iteration) are equivalent, and their class is the real number 2\sqrt 2. Similarly 0.9,0.99,0.999,…0.9, 0.99, 0.999, \dots is equivalent to the constant sequence 1,1,1,…1, 1, 1, \dots, which is the precise meaning of 0.999…=10.999\ldots = 1.

Sums and products are computed termwise: [(qn)]+[(rn)]=[(qn+rn)][(q_n)] + [(r_n)] = [(q_n + r_n)] and [(qn)][(rn)]=[(qnrn)][(q_n)][(r_n)] = [(q_n r_n)]. One checks that sums and products of Cauchy sequences are Cauchy (for products one uses that Cauchy sequences are bounded) and that the operations are well defined. A sequence not equivalent to 00 is eventually bounded away from 00, so it can be inverted termwise from some point on; a class is positive if its terms are eventually at least some fixed rational ε>0\varepsilon > 0. The result is again a complete ordered field: completeness is proved by approximating each term of a Cauchy sequence of real numbers xnx_n by a rational qnq_n with ∣xn−qn∣<1/n|x_n - q_n| < 1/n, and showing that (qn)(q_n) is Cauchy and its class is the limit. This is how Mathlib builds R\R (as Real.ofCauchy), and the same construction, with a different notion of distance, produces the pp-adic numbers.

Why are there two constructions? Cuts make the order and completeness easy and the algebra laborious; Cauchy sequences make the algebra easy and the order laborious. The next theorem says it does not matter which one we choose.

ProofH

There is only one complete ordered field

Theorem— Theorem 8 (complete ordered fields are Archimedean)

In a complete ordered field FF, the natural numbers 1,1+1,1+1+1,…1, 1 + 1, 1 + 1 + 1, \dots are not bounded above. Consequently, between any two elements x<yx < y of FF there is a rational number.

Proof

Suppose N⊆F\N \subseteq F were bounded above, with supremum ss. Then s−1s - 1 is not an upper bound, so s−1<ns - 1 < n for some natural number nn. But then s<n+1s < n + 1, and n+1n + 1 is a natural number — contradicting that ss is an upper bound.

For density: choose a natural number m>1/(y−x)m > 1/(y - x), so that 1/m<y−x1/m < y - x. The multiples k/mk/m, k∈Zk \in \Z, are spaced 1/m1/m apart, and there is a least integer kk with k/m>xk/m > x (by the Archimedean property, the set of such kk is non-empty and bounded below). Then (k−1)/m≤x(k - 1)/m \le x, so k/m≤x+1/m<yk/m \le x + 1/m < y.

∎

Theorem— Theorem 9 (uniqueness of the reals)

If FF and GG are complete ordered fields, there is exactly one order-preserving field isomorphism F→GF \to G.

Proof sketch. Every ordered field contains a copy of Q\Q (the multiples of 11 and their quotients), and any field homomorphism must be the identity on it. Define ϕ:F→G\phi : F \to G by

ϕ(x)=sup⁡G{q∈Q:q<x}.\phi(x) = \sup{}_G \{ q \in \Q : q < x \}.

The set is non-empty and bounded above in GG by the Archimedean property, so the supremum exists by completeness of GG. Density of Q\Q (Theorem 8) shows that ϕ\phi is strictly increasing and is the identity on Q\Q, that it has the inverse y↦sup⁡F{q∈Q:q<y}y \mapsto \sup_F\{q \in \Q : q < y\}, and, with more work, that it preserves sums and products. Any order-preserving isomorphism must send xx to this supremum, which gives uniqueness. Mathlib contains a complete formal proof (cited in the formal section). □\square

So the Dedekind reals and the Cauchy reals are isomorphic, and so is any other model of the axioms. "The real numbers" is a meaningful phrase: up to unique isomorphism there is only one complete ordered field.

Formal mathematicsF

The constructions in Lean

Lean's quotient types make the constructions literal: Quotient s is the type of equivalence classes of a Setoid (a type with an equivalence relation), and a function on representatives descends to classes — via Quotient.lift or Quotient.map₂ — only when given a proof that it respects the relation. In Lean, well-definedness cannot be forgotten: the definition does not compile without the proof.

The integers. Transitivity (Proposition 1), with the cancellation step made explicit; the setoid and the type of classes; the well-definedness lemmas of Proposition 2, each a calc following the human grouping; and the operations themselves, whose definitions consume those proofs.

intRel_transLean 4Proved here from basic factsFormally verified
/-- **Transitivity of `(a, b) ~ (c, d) ⟺ a + d = c + b`.** Adding the two hypotheses gives
`(a + f) + (c + d) = (e + b) + (c + d)`, and in `ℕ` we may cancel `c + d`. Cancellation is the one
property of `ℕ` that the construction really needs. -/
theorem intRel_trans {a b c d e f : ℕ} (h₁ : a + d = c + b) (h₂ : c + f = e + d) :
    a + f = e + b := by
  have h : (a + f) + (c + d) = (e + b) + (c + d) :=
    calc (a + f) + (c + d) = (a + d) + (c + f) := by ring
      _ = (c + b) + (e + d) := by rw [h₁, h₂]
      _ = (e + b) + (c + d) := by ring
  exact Nat.add_right_cancel h
Axioms used: propextformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
intSetoidLean 4Formally verified
/-- The equivalence relation on `ℕ × ℕ` whose classes are the integers: `(a, b) ~ (c, d)` means
`a + d = c + b`, i.e. "`a - b = c - d`" written without subtraction. Reflexivity and symmetry are
immediate; transitivity is `intRel_trans`. -/
def intSetoid : Setoid (ℕ × ℕ) where
  r p q := p.1 + q.2 = q.1 + p.2
  iseqv := ⟨fun _ => rfl, fun h => h.symm, fun h₁ h₂ => intRel_trans h₁ h₂⟩
Axioms used: propextformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
PairIntLean 4Formally verified
/-- The constructed integers: equivalence classes of pairs of natural numbers. -/
def PairInt : Type := Quotient intSetoid
Axioms used: propextformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
add_respectsLean 4Proved here from basic factsFormally verified
/-- **Addition of classes is well defined.** If `(a, b) ~ (a', b')` and `(c, d) ~ (c', d')`, then
`(a + c, b + d) ~ (a' + c', b' + d')`: add the two equations. -/
theorem add_respects {a b c d a' b' c' d' : ℕ} (h₁ : a + b' = a' + b) (h₂ : c + d' = c' + d) :
    (a + c) + (b' + d') = (a' + c') + (b + d) := by
  calc (a + c) + (b' + d') = (a + b') + (c + d') := by ring
    _ = (a' + b) + (c' + d) := by rw [h₁, h₂]
    _ = (a' + c') + (b + d) := by ring
Axioms used: propextformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
mul_respects_leftLean 4Proved here from basic factsFormally verified
/-- **Multiplication of classes is well defined (first argument).** With
`(a, b) · (c, d) = (ac + bd, ad + bc)` — the rule `(a - b)(c - d) = (ac + bd) - (ad + bc)` —
replacing `(a, b)` by an equivalent `(a', b')` gives an equivalent product. The key step groups
the terms as `(a + b')c + (a' + b)d` and uses `a + b' = a' + b`. -/
theorem mul_respects_left {a b a' b' c d : ℕ} (h : a + b' = a' + b) :
    (a * c + b * d) + (a' * d + b' * c) = (a' * c + b' * d) + (a * d + b * c) := by
  calc (a * c + b * d) + (a' * d + b' * c) = (a + b') * c + (a' + b) * d := by ring
    _ = (a' + b) * c + (a + b') * d := by rw [h]
    _ = (a' * c + b' * d) + (a * d + b * c) := by ring
Axioms used: propextformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
mul_respects_rightLean 4Proved here from basic factsFormally verified
/-- **Multiplication of classes is well defined (second argument):** the same computation with
the roles of the factors exchanged, grouping as `a(c + d') + b(c' + d)`. -/
theorem mul_respects_right {a b c d c' d' : ℕ} (h : c + d' = c' + d) :
    (a * c + b * d) + (a * d' + b * c') = (a * c' + b * d') + (a * d + b * c) := by
  calc (a * c + b * d) + (a * d' + b * c') = a * (c + d') + b * (c' + d) := by ring
    _ = a * (c' + d) + b * (c + d') := by rw [h]
    _ = (a * c' + b * d') + (a * d + b * c) := by ring
Axioms used: propextformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
addLean 4Formally verified
/-- Addition on the constructed integers: `[(a, b)] + [(c, d)] = [(a + c, b + d)]`. It is
well defined by `add_respects`. -/
def add : PairInt → PairInt → PairInt :=
  Quotient.map₂ (fun p q => (p.1 + q.1, p.2 + q.2))
    (fun _ _ h₁ _ _ h₂ => add_respects h₁ h₂)
Axioms used: propext, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
mulLean 4Formally verified
/-- Multiplication: `[(a, b)] · [(c, d)] = [(ac + bd, ad + bc)]`. Well defined because changing
one argument at a time gives equivalent results (`mul_respects_left`, `mul_respects_right`),
and the relation is transitive. -/
def mul : PairInt → PairInt → PairInt :=
  Quotient.map₂ (fun p q => (p.1 * q.1 + p.2 * q.2, p.1 * q.2 + p.2 * q.1))
    (fun _p p' hp q _q' hq =>
      intRel_trans (mul_respects_left (c := q.1) (d := q.2) hp)
        (mul_respects_right (a := p'.1) (b := p'.2) hq))
Axioms used: propext, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor

To check that the construction really produces the integers, we compare it with Mathlib's ℤ (which is built differently, as an inductive type). The map [(a,b)]↦a−b[(a, b)] \mapsto a - b is well defined, turns the constructed operations into the usual ones, and is a bijection — so it is a ring isomorphism.

toIntLean 4Formally verified
/-- The comparison map to Mathlib's integers: `[(a, b)] ↦ a - b`. It is well defined because
`a + d = c + b` implies `a - b = c - d` in `ℤ`. -/
def toInt : PairInt → ℤ :=
  Quotient.lift (fun p : ℕ × ℕ => (p.1 : ℤ) - p.2)
    (fun p q (h : p.1 + q.2 = q.1 + p.2) => by
      have h' : (p.1 : ℤ) + q.2 = q.1 + p.2 := by exact_mod_cast h
      linear_combination h')
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
toInt_addLean 4Proved here from basic factsFormally verified
/-- The comparison map turns the constructed addition into the addition of `ℤ`:
`(a + c) - (b + d) = (a - b) + (c - d)`. -/
theorem toInt_add (x y : PairInt) : toInt (add x y) = toInt x + toInt y := by
  induction x using Quotient.inductionOn with | h p =>
  induction y using Quotient.inductionOn with | h q =>
  show ((p.1 + q.1 : ℕ) : ℤ) - ((p.2 + q.2 : ℕ) : ℤ) = ((p.1 : ℤ) - p.2) + ((q.1 : ℤ) - q.2)
  push_cast
  ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
toInt_mulLean 4Proved here from basic factsFormally verified
/-- …and the constructed multiplication into the multiplication of `ℤ`:
`(ac + bd) - (ad + bc) = (a - b)(c - d)`. -/
theorem toInt_mul (x y : PairInt) : toInt (mul x y) = toInt x * toInt y := by
  induction x using Quotient.inductionOn with | h p =>
  induction y using Quotient.inductionOn with | h q =>
  show ((p.1 * q.1 + p.2 * q.2 : ℕ) : ℤ) - ((p.1 * q.2 + p.2 * q.1 : ℕ) : ℤ)
    = ((p.1 : ℤ) - p.2) * ((q.1 : ℤ) - q.2)
  push_cast
  ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
toInt_bijectiveLean 4Proved here from basic factsFormally verified
/-- **The construction really produces the integers.** The comparison map is a bijection:
injective because `a - b = c - d` in `ℤ` gives `a + d = c + b` in `ℕ`, and surjective because
`n = n⁺ - n⁻` with `n⁺ = max(n, 0)` and `n⁻ = max(-n, 0)`. Together with `toInt_add` and
`toInt_mul`, it is an isomorphism of rings. -/
theorem toInt_bijective : Function.Bijective toInt := by
  constructor
  · intro x y hxy
    induction x using Quotient.inductionOn with | h p =>
    induction y using Quotient.inductionOn with | h q =>
    change (p.1 : ℤ) - p.2 = (q.1 : ℤ) - q.2 at hxy
    apply Quotient.sound
    show p.1 + q.2 = q.1 + p.2
    omega
  · intro n
    refine ⟨Quotient.mk intSetoid (n.toNat, (-n).toNat), ?_⟩
    show ((n.toNat : ℕ) : ℤ) - (((-n).toNat : ℕ) : ℤ) = n
    omega
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor

Fractions. Transitivity of ad=cbad = cb in any commutative ring without zero divisors, with the cancellation of dd as the crucial last line; the Z/6Z\Z/6\Z counterexample, checked by decide; and Mathlib's statements that Q\Q is the field of fractions of Z\Z and that ring homomorphisms out of Q\Q are unique.

frac_transLean 4Proved here from basic factsFormally verified
/-- **Transitivity of equality of fractions**, `(a, b) ~ (c, d) ⟺ ad = cb`, in any commutative
ring without zero divisors (such as `ℤ`). From `ad = cb` and `cf = ed` we get
`(af)d = (eb)d`, and we cancel `d ≠ 0`. That cancellation is exactly where "no zero divisors"
is used. -/
theorem frac_trans {R : Type*} [CommRing R] [NoZeroDivisors R] {a b c d e f : R} (hd : d ≠ 0)
    (h₁ : a * d = c * b) (h₂ : c * f = e * d) : a * f = e * b := by
  have h : (a * f) * d = (e * b) * d :=
    calc (a * f) * d = (a * d) * f := by ring
      _ = (c * b) * f := by rw [h₁]
      _ = b * (c * f) := by ring
      _ = b * (e * d) := by rw [h₂]
      _ = (e * b) * d := by ring
  exact mul_right_cancel₀ hd h
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
frac_trans_fails_zmod6Lean 4Proved here from basic factsFormally verified
/-- **With zero divisors, "fractions" break.** In `ℤ/6ℤ`, using the same rule
`(a, b) ~ (c, d) ⟺ ad = cb` with non-zero denominators, `3/1 ~ 0/2` and `0/2 ~ 0/1`, but
`3/1 ≁ 0/1`: the relation is not transitive, because `2 · 3 = 0` lets us "cancel" wrongly. -/
theorem frac_trans_fails_zmod6 :
    let r : ZMod 6 × ZMod 6 → ZMod 6 × ZMod 6 → Prop := fun p q => p.1 * q.2 = q.1 * p.2
    r (3, 1) (0, 2) ∧ r (0, 2) (0, 1) ∧ ¬ r (3, 1) (0, 1) := by
  decide
Axioms used: propext, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
rat_isFractionRingLean 4Applies a library theoremFormally verified
/-- **`ℚ` is the field of fractions of `ℤ`.** Mathlib's instance `Rat.isFractionRing`: every
rational is `a / b` with `a, b ∈ ℤ`, `b ≠ 0`, and `a / b = c / d` exactly when `ad = cb`. -/
theorem rat_isFractionRing : IsFractionRing ℤ ℚ := Rat.isFractionRing
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
ringHom_rat_uniqueLean 4Applies a library theoremFormally verified
/-- **A universal property in miniature:** there is at most one ring homomorphism from `ℚ` to
any ring, because it is forced on `ℤ` and then on fractions. Mathlib's `RingHom.ext_rat`. -/
theorem ringHom_rat_unique {R : Type*} [Semiring R] (f g : ℚ →+* R) : f = g :=
  RingHom.ext_rat f g
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor

Dedekind cuts. A cut is a structure carrying a set of rationals together with proofs of the three conditions. The rational cuts and the cut for 2\sqrt 2 (Proposition 4, including the step p↦2p+2p+2p \mapsto \frac{2p + 2}{p + 2}) are constructed; cuts are totally ordered (Proposition 5); and the union of a bounded non-empty family is a cut and its least upper bound (Theorem 6).

CutLean 4Formally verified
/-- A **Dedekind cut**: a set of rationals that is non-empty, not everything, closed downwards,
and has no greatest element. Think of it as "the rationals below a real number". -/
structure Cut where
  /-- The rationals below the real number. -/
  carrier : Set ℚ
  nonempty : carrier.Nonempty
  ne_univ : carrier ≠ Set.univ
  lower : ∀ ⦃p q : ℚ⦄, p ∈ carrier → q < p → q ∈ carrier
  no_max : ∀ p ∈ carrier, ∃ q ∈ carrier, p < q
Axioms used: No axiomsformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
instLELean 4Formally verified
/-- Cuts are ordered by inclusion. -/
instance instLE : LE Cut := ⟨fun A B => A.carrier ⊆ B.carrier⟩
Axioms used: No axiomsformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
ofRatLean 4Formally verified
/-- The cut of a rational number `r`: all rationals below `r`. -/
def ofRat (r : ℚ) : Cut where
  carrier := {q | q < r}
  nonempty := ⟨r - 1, by simp⟩
  ne_univ := fun h => lt_irrefl r (h ▸ Set.mem_univ r : r ∈ {q : ℚ | q < r})
  lower := fun _ _ hp hq => lt_trans hq hp
  no_max := fun p hp => by
    have hp' : p < r := hp
    exact ⟨(p + r) / 2, show (p + r) / 2 < r by linarith, by linarith⟩
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
sqrtTwoLean 4Formally verified
/-- **The cut of `√2`:** the rationals `q` with `q < 0` or `q² < 2`. It has no greatest element:
if `0 ≤ p` and `p² < 2`, the rational `(2p + 2)/(p + 2)` is larger than `p` and its square is
still below `2`. -/
def sqrtTwo : Cut where
  carrier := {q | q < 0 ∨ q * q < 2}
  nonempty := ⟨0, Or.inr (by norm_num)⟩
  ne_univ := by
    intro h
    have h2 : (2 : ℚ) ∈ {q : ℚ | q < 0 ∨ q * q < 2} := h ▸ Set.mem_univ 2
    rcases h2 with h2 | h2 <;> norm_num at h2
  lower := by
    intro p q hp hqp
    rcases lt_or_ge q 0 with hq | hq
    · exact Or.inl hq
    · right
      rcases hp with hp | hp
      · linarith
      · nlinarith
  no_max := by
    intro p hp
    rcases lt_or_ge p 0 with hp0 | hp0
    · exact ⟨0, Or.inr (by norm_num), hp0⟩
    · have hp2 : p * p < 2 := by
        rcases hp with hp | hp
        · linarith
        · exact hp
      have hpos : 0 < p + 2 := by linarith
      refine ⟨(2 * p + 2) / (p + 2), Or.inr ?_, ?_⟩
      · rw [div_mul_div_comm, div_lt_iff₀ (by positivity)]
        nlinarith
      · rw [lt_div_iff₀ hpos]
        nlinarith
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
le_totalLean 4Proved here from basic factsFormally verified
/-- **Cuts are totally ordered.** If `A ⊄ B`, pick `p ∈ A` with `p ∉ B`. Every `q ∈ B` is below
`p` (otherwise `p ≤ q` would put `p` in `B`, which is closed downwards), so `q ∈ A`. -/
theorem le_total (A B : Cut) : A ≤ B ∨ B ≤ A := by
  by_cases h : A ≤ B
  · exact Or.inl h
  · right
    obtain ⟨p, hpA, hpB⟩ := Set.not_subset.mp h
    intro q hqB
    rcases lt_or_ge q p with hqp | hpq
    · exact A.lower hpA hqp
    · exfalso
      rcases hpq.lt_or_eq with hlt | heq
      · exact hpB (B.lower hqB hlt)
      · exact hpB (heq ▸ hqB)
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
supLean 4Formally verified
/-- The **supremum** of a non-empty family `S` of cuts that is bounded above by a cut `B`: the
union of the family. The proofs check that the union is again a cut: it is non-empty because `S`
and its members are; it is not everything because it lies inside `B`; and it is closed
downwards and has no greatest element because each member is and has none. -/
def sup (S : Set Cut) (hS : S.Nonempty) (hB : ∃ B : Cut, ∀ A ∈ S, A ≤ B) : Cut where
  carrier := ⋃ A ∈ S, A.carrier
  nonempty := by
    obtain ⟨A, hA⟩ := hS
    obtain ⟨p, hp⟩ := A.nonempty
    exact ⟨p, Set.mem_biUnion hA hp⟩
  ne_univ := by
    obtain ⟨B, hB⟩ := hB
    obtain ⟨q, hq⟩ : ∃ q, q ∉ B.carrier := by
      by_contra h
      exact B.ne_univ (Set.eq_univ_of_forall fun q => by_contra fun hq => h ⟨q, hq⟩)
    intro h
    have hq' : q ∈ ⋃ A ∈ S, A.carrier := h ▸ Set.mem_univ q
    obtain ⟨A, hA, hqA⟩ := Set.mem_iUnion₂.mp hq'
    exact hq (hB A hA hqA)
  lower := by
    intro p q hp hqp
    obtain ⟨A, hA, hpA⟩ := Set.mem_iUnion₂.mp hp
    exact Set.mem_biUnion hA (A.lower hpA hqp)
  no_max := by
    intro p hp
    obtain ⟨A, hA, hpA⟩ := Set.mem_iUnion₂.mp hp
    obtain ⟨q, hqA, hpq⟩ := A.no_max p hpA
    exact ⟨q, Set.mem_biUnion hA hqA, hpq⟩
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
sup_isLUBLean 4Proved here from basic factsFormally verified
/-- **The least-upper-bound property of the cuts.** The union `sup S` is an upper bound of `S`
(each member is contained in the union) and it is the least one (if every member of `S` lies in
`C`, so does their union). -/
theorem sup_isLUB (S : Set Cut) (hS : S.Nonempty) (hB : ∃ B : Cut, ∀ A ∈ S, A ≤ B) :
    (∀ A ∈ S, A ≤ sup S hS hB) ∧ (∀ C : Cut, (∀ A ∈ S, A ≤ C) → sup S hS hB ≤ C) := by
  constructor
  · intro A hA p hp
    exact Set.mem_biUnion hA hp
  · intro C hC p hp
    obtain ⟨A, hA, hpA⟩ := Set.mem_iUnion₂.mp hp
    exact hC A hA hpA
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor

What Mathlib provides. Completeness of Mathlib's R\R (built from Cauchy sequences), and the isomorphism between any two conditionally complete linearly ordered fields — Theorem 9, formalised in full in Mathlib with exactly the map x↦sup⁡{q∈Q:q<x}x \mapsto \sup\{q \in \Q : q < x\}.

real_completeLean 4Applies a library theoremFormally verified
/-- **Completeness of Mathlib's `ℝ`** (built from Cauchy sequences of rationals): every non-empty
set of reals that is bounded above has a least upper bound. This is `Real.exists_isLUB`. -/
theorem real_complete {S : Set ℝ} (hne : S.Nonempty) (hbdd : BddAbove S) : ∃ x, IsLUB S x :=
  Real.exists_isLUB hne hbdd
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor
complete_ordered_field_uniqueLean 4Applies a library theoremFormally verified
/-- **Uniqueness of the complete ordered field.** Any two conditionally complete linearly
ordered fields are isomorphic as ordered rings: Mathlib's
`ConditionallyCompleteLinearOrderedField.inducedOrderRingIso`, which sends `x` to the supremum
of the rationals below `x`. (Mathlib also proves the isomorphism is unique.) -/
noncomputable def complete_ordered_field_unique (F G : Type*)
    [Field F] [ConditionallyCompleteLinearOrder F] [IsStrictOrderedRing F]
    [Field G] [ConditionallyCompleteLinearOrder G] [IsStrictOrderedRing G] : F ≃+*o G :=
  ConditionallyCompleteLinearOrderedField.inducedOrderRingIso F G
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/NumberSystemConstructions.leanTry it in the Lean web editor

Not formalised here: the ring axioms for the constructed integers (they follow by transport along the bijection toInt, but we do not build the CommRing instance), the field structure on cuts (addition and multiplication of cuts), the fact that the √2 cut is not rational, and the Cauchy construction itself (Mathlib's Real is that construction).

ComputationC

Testing well-definedness, and approaching a gap

An operation on classes is well defined if every choice of representatives gives equivalent answers. A computer can try all small choices. The correct rules pass; the tempting wrong ones — multiplying integer pairs componentwise, or adding fractions by adding numerators and denominators (the mediant) — fail, and the search returns explicit counterexamples. A counterexample is a proof of failure; a pass is only evidence.

Well-definedness tested on every small representativePythonExhaustive finite checkCounterexampleComputationally tested
"""Is an operation on equivalence classes well defined? Test every representative.

Integers are built as classes of pairs (a, b) of naturals with
(a, b) ~ (c, d) iff a + d = c + b, and fractions as classes of pairs (a, b)
with b != 0 and (a, b) ~ (c, d) iff ad = cb. An operation on pairs defines an
operation on classes only if equivalent inputs always give equivalent outputs.
The experiment checks this exhaustively for small pairs: the lesson's addition
and multiplication pass, while two tempting rules - "multiply componentwise"
for integer pairs and the "mediant" (a + c)/(b + d) for fractions - fail, and
it prints a counterexample for each. It also shows "fractions" over Z/6Z
breaking transitivity. Exhaustive for small cases; the general claims are
the lesson's proofs.
"""

import itertools

N = range(7)

def int_rel(p, q):
    """(a, b) ~ (c, d) iff a + d = c + b: both stand for a - b = c - d."""
    return p[0] + q[1] == q[0] + p[1]

def int_add(p, q):
    """(a, b) + (c, d) = (a + c, b + d)."""
    return (p[0] + q[0], p[1] + q[1])

def int_mul(p, q):
    """(a, b)(c, d) = (ac + bd, ad + bc), from (a - b)(c - d)."""
    return (p[0] * q[0] + p[1] * q[1], p[0] * q[1] + p[1] * q[0])

def int_bad(p, q):
    """A tempting but wrong rule: multiply componentwise."""
    return (p[0] * q[0], p[1] * q[1])

def frac_rel(p, q):
    """(a, b) ~ (c, d) iff ad = cb."""
    return p[0] * q[1] == q[0] * p[1]

def frac_add(p, q):
    """a/b + c/d = (ad + cb)/(bd)."""
    return (p[0] * q[1] + q[0] * p[1], p[1] * q[1])

def mediant(p, q):
    """The 'freshman sum' (a + c)/(b + d)."""
    return (p[0] + q[0], p[1] + q[1])

def counterexample(pairs, rel, op):
    """First (p, p', q, q') with p ~ p', q ~ q' but op(p, q) !~ op(p', q')."""
    equiv = [(p, p2) for p in pairs for p2 in pairs if rel(p, p2)]
    for (p, p2), (q, q2) in itertools.product(equiv, repeat=2):
        if not rel(op(p, q), op(p2, q2)):
            return p, p2, q, q2
    return None

def transitivity_failure(n):
    """Pairs in Z/nZ with non-zero second entry breaking transitivity."""
    pairs = [(a, b) for a in range(n) for b in range(1, n)]

    def rel(p, q):
        return (p[0] * q[1] - q[0] * p[1]) % n == 0

    for x, y, z in itertools.product(pairs, repeat=3):
        if rel(x, y) and rel(y, z) and not rel(x, z):
            return x, y, z
    return None

def main():
    ints = [(a, b) for a in N for b in N]
    fracs = [(a, b) for a in range(0, 5) for b in range(1, 6)]
    print(f"Integer pairs (a, b) with 0 <= a, b <= 6: {len(ints)}")
    for name, op in [("(a+c, b+d)", int_add), ("(ac+bd, ad+bc)", int_mul),
                     ("(ac, bd)", int_bad)]:
        bad = counterexample(ints, int_rel, op)
        verdict = "well defined" if bad is None else f"FAILS: {bad}"
        print(f"  {name:<16}{verdict}")
    p, p2, q, q2 = counterexample(ints, int_rel, int_bad)
    print(f"  {p} ~ {p2} and {q} ~ {q2}, but the products")
    print(f"  {int_bad(p, q)} and {int_bad(p2, q2)} are not equivalent")
    print()
    print(f"Fraction pairs a/b with 0 <= a <= 4, 1 <= b <= 5: {len(fracs)}")
    for name, op in [("(ad+cb)/(bd)", frac_add), ("(a+c)/(b+d)", mediant)]:
        bad = counterexample(fracs, frac_rel, op)
        verdict = "well defined" if bad is None else f"FAILS: {bad}"
        print(f"  {name:<16}{verdict}")
    p, p2, q, q2 = counterexample(fracs, frac_rel, mediant)
    m1, m2 = mediant(p, q), mediant(p2, q2)
    print(f"  {p[0]}/{p[1]} = {p2[0]}/{p2[1]} and {q[0]}/{q[1]} = {q2[0]}/{q2[1]},"
          f" but {m1[0]}/{m1[1]} != {m2[0]}/{m2[1]}")
    print()
    for n in (5, 6):
        print(f"'Fractions' over Z/{n}Z, transitivity counterexample:",
              transitivity_failure(n))
    print()
    print("Epistemic status: exhaustive checks over small representatives, plus")
    print("explicit counterexamples. A failure found here is a proof that the")
    print("rule is not well defined; a pass is only evidence. The lesson proves")
    print("well-definedness of the correct operations for all representatives.")

if __name__ == "__main__":
    main()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

The second experiment works entirely inside Q\Q, with exact fractions. The climbing sequence stays inside the 2\sqrt 2 cut and the Babylonian sequence outside it, and the gap between them shrinks rapidly — two equivalent Cauchy sequences of rationals, crowding towards a point that Q\Q does not contain.

Closing in on the square root of 2 with fractionsPythonExact computationExhaustive finite checkComputationally tested
"""Closing in on the square root of 2 with rationals only: cuts and Cauchy sequences.

Two sequences of exact fractions approach the "missing" number sqrt(2): the
Babylonian (Newton) iteration x -> (x + 2/x)/2 from above, and the map
q -> (2q + 2)/(q + 2) from below, which the lesson uses to show that the
Dedekind cut {q : q < 0 or q^2 < 2} has no largest element. The experiment
checks with exact rational arithmetic that the lower terms stay inside the
cut, the upper terms stay outside, the gap between them shrinks, and the two
sequences are equivalent Cauchy sequences (their difference tends to 0). It
also checks that no fraction with denominator up to 1000 squares to 2. All
arithmetic is exact; the statements about limits are not proved by it.
"""

from fractions import Fraction

TWO = Fraction(2)

def in_cut(q):
    """Membership in the Dedekind cut of sqrt(2): q < 0 or q^2 < 2."""
    return q < 0 or q * q < TWO

def babylonian(x):
    """One Newton step for x^2 = 2: the average of x and 2/x."""
    return (x + TWO / x) / 2

def climb(q):
    """The lesson's step inside the cut: (2q + 2)/(q + 2) > q when q^2 < 2."""
    return (2 * q + 2) / (q + 2)

def iterate(step, start, n):
    """The list [start, step(start), ..., step^n(start)]."""
    terms = [Fraction(start)]
    for _ in range(n):
        terms.append(step(terms[-1]))
    return terms

def no_rational_root(max_den):
    """True if no p/q with 1 <= q <= max_den has (p/q)^2 = 2."""
    for q in range(1, max_den + 1):
        p = int((2 * q * q) ** 0.5)
        if any(r * r == 2 * q * q for r in (p - 1, p, p + 1)):
            return False
    return True

def main():
    upper = iterate(babylonian, 2, 5)
    lower = iterate(climb, 1, 5)
    print(" n  lower (in cut)   upper (not in cut)  gap upper - lower")
    for n, (lo, up) in enumerate(zip(lower, upper)):
        lo_s, up_s = f"{lo}", f"{up}"
        if len(up_s) > 18:
            up_s = f"({len(str(up.numerator))} digits)/..."
        gap = float(up - lo)
        print(f"{n:>2}  {lo_s:<15}  {up_s:<18}  {gap:.3e}")
    print("all lower terms in the cut:", all(in_cut(q) for q in lower))
    print("no upper term in the cut:  ", not any(in_cut(x) for x in upper))
    print("lower terms increase:      ",
          all(a < b for a, b in zip(lower, lower[1:])))
    err = [float(x * x - TWO) for x in upper]
    print("upper x^2 - 2:", ", ".join(f"{e:.1e}" for e in err[1:]))
    print("(Newton roughly squares the error at each step.)")
    print("no fraction p/q with q <= 1000 squares to 2:", no_rational_root(1000))
    print()
    print("Epistemic status: exact rational arithmetic for finitely many terms.")
    print("It shows the gap shrinking but cannot show that it tends to 0, nor")
    print("that sqrt(2) is irrational (only that no small fraction works). Those")
    print("are proved in the lesson and in the lesson on real numbers.")

if __name__ == "__main__":
    main()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
Exercises

Exercises

1. Constructing ℤ, ℚ and ℝ

Warm-upHuman

With (a,b)∼(c,d)(a, b) \sim (c, d) iff a+d=c+ba + d = c + b, which pairs of natural numbers lie in the class that represents the integer −2-2? (Choose all that apply.)

Choose all that apply

2. Constructing ℤ, ℚ and ℝ

Warm-upHuman

Using [(a,b)]⋅[(c,d)]=[(ac+bd, ad+bc)][(a, b)] \cdot [(c, d)] = [(ac + bd,\, ad + bc)], compute [(3,5)]⋅[(4,1)][(3, 5)] \cdot [(4, 1)]. Which integer does the resulting class represent?

3. Constructing ℤ, ℚ and ℝ

CoreHuman

In the proof that equality of fractions (ad=cbad = cb) is transitive, from ad=cbad = cb and cf=edcf = ed we derive (af)d=(eb)d(af)d = (eb)d. Which step needs the hypothesis that the ring has no zero divisors?

Choose one

4. Constructing ℤ, ℚ and ℝ

CoreHuman

Each rule below is defined on a representative a/ba/b (or two, a/ba/b and c/dc/d) of a rational number, with b,d≠0b, d \neq 0. Which rules are not well defined as functions of the rational numbers? (Choose all that apply.)

Choose all that apply

5. Constructing ℤ, ℚ and ℝ

CoreHuman

Which of these subsets of Q\Q are Dedekind cuts (non-empty, not all of Q\Q, closed downwards, no greatest element)? (Choose all that apply.)

Choose all that apply

6. Constructing ℤ, ℚ and ℝ

CoreHuman

Which example shows that Q\Q is not complete (that not every non-empty, bounded-above subset has a least upper bound in Q\Q)?

Choose one

7. Constructing ℤ, ℚ and ℝ

CoreFormal

In the lesson's Lean file, PairInt.add is defined with Quotient.map₂ (fun p q => (p.1 + q.1, p.2 + q.2)) (proof). What is the second argument, and what happens if you leave it out?

Choose one

8. Constructing ℤ, ℚ and ℝ

StretchComputational

Implement the integers as pairs of natural numbers. Write canonical(p), returning the representative of the class of p that has a 00 in at least one coordinate, and mul(p, q) using (a,b)(c,d)=(ac+bd,ad+bc)(a, b)(c, d) = (ac + bd, ad + bc). Then check, for all pairs with entries up to 55, that mul is well defined: equivalent inputs give outputs with the same canonical form.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
Common misconceptionsH

Common misconceptions

Misconception

"Operations on equivalence classes are automatically well defined." They are not. Componentwise multiplication of integer pairs, and the mediant a+cb+d\frac{a + c}{b + d} of fractions, are perfectly good operations on pairs that do not respect the equivalence: 12=24\tfrac12 = \tfrac24 but the mediants of these with 13\tfrac13 are 25≠37\tfrac25 \neq \tfrac37. Every operation on classes needs a proof that it does not depend on the representatives.

Misconception

"The constructions tell us what numbers really are." They show that structures with the required properties exist (given N\N and set theory), not that −3-3 "is" a set of pairs or 2\sqrt 2 "is" a set of rationals. The Dedekind and Cauchy constructions produce different sets, yet Theorem 9 says they are isomorphic; what matters is the structure, which is unique up to unique isomorphism.

Misconception

"Q\Q is complete because between any two rationals there is another." Density is not completeness. The rationals are dense, yet {q:q2<2}\{q : q^2 < 2\} is bounded above with no least upper bound in Q\Q, and the Babylonian sequence is Cauchy with no rational limit.

Misconception

"0.999…0.999\ldots is slightly less than 11." In the Cauchy construction 0.999…0.999\ldots is the class of 0.9,0.99,0.999,…0.9, 0.99, 0.999, \dots, which differs from the constant sequence 11 by 10−n→010^{-n} \to 0: the two sequences are equivalent, so they are the same real number. With cuts: the rationals below 0.999…0.999\ldots are exactly the rationals below 11.

Misconception

"A cut is the same as its supremum, so {q≤r}\{q \le r\} is also a cut." Condition 3 (no greatest element) rules out {q≤r}\{q \le r\}; without it, every rational would be described by two different cuts. Conventions differ between books (some use upper sets, or allow a greatest element and exclude the other one), but each makes the correspondence one-to-one.

ViewpointsH

Many ways of seeing

Analysis— Completion of a metric space, and other completions of Q

The Cauchy construction works in any metric space XX: the completion X^\hat X is the set of Cauchy sequences up to equivalence, and XX sits densely inside the complete space X^\hat X; every uniformly continuous map from XX to a complete space extends uniquely to X^\hat X. Completing Q\Q for the usual distance gives R\R. But Q\Q has other distances: for a prime pp, ∣x∣p=p−k|x|_p = p^{-k} when x=pka/bx = p^k a/b with p∤abp \nmid ab. Completing Q\Q for ∣⋅∣p|\cdot|_p gives the field Qp\Q_p of pp-adic numbers, in which 1+p+p2+⋯1 + p + p^2 + \cdots converges (to 1/(1−p)1/(1 - p)). Ostrowski's theorem (1916) says that up to equivalence these are all the non-trivial absolute values on Q\Q: so R\R and the Qp\Q_p are all the completions of Q\Q (see real analysis and congruences).

Topology— Completeness is connectedness

Give an ordered set its order topology. A densely ordered set without endpoints is connected if and only if it is Dedekind complete (every non-empty bounded-above subset has a supremum). So the completeness of R\R is the same thing as its connectedness — the intermediate value theorem in disguise — while Q\Q is totally disconnected: for any irrational α\alpha, the sets {q<α}\{q < \alpha\} and {q>α}\{q > \alpha\} split Q\Q into two disjoint open pieces. The Dedekind construction is an instance of a general order-theoretic completion, the Dedekind–MacNeille completion, which embeds any partially ordered set into a complete lattice (see point-set topology).

Algebra— Group completion and localisation

The construction of Z\Z works for any commutative monoid MM: pairs (a,b)(a, b) modulo (a,b)∼(c,d)(a, b) \sim (c, d) iff a+d+k=c+b+ka + d + k = c + b + k for some kk give an abelian group K(M)K(M), the Grothendieck group, with a universal property — every monoid homomorphism from MM to an abelian group factors uniquely through K(M)K(M). (The extra kk is needed when MM lacks cancellation; for N\N it can be dropped.) Applied to isomorphism classes of vector bundles, this is the starting point of topological K-theory. The construction of Q\Q is localisation: for a multiplicative subset SS of a commutative ring RR, the ring S−1RS^{-1}R of fractions r/sr/s — used constantly in commutative algebra and algebraic geometry.

Logic— Categorical in second-order logic, not in first-order logic

The axioms of a complete ordered field are categorical: by Theorem 9 they have exactly one model up to isomorphism. But the completeness axiom quantifies over all subsets — it is a second-order statement. If we keep only first-order consequences (statements about elements), uniqueness fails: by the compactness theorem there are non-Archimedean ordered fields — such as the hyperreals of non-standard analysis — that satisfy exactly the same first-order sentences as R\R, and by the Löwenheim–Skolem theorem there are countable ones, such as the field of real algebraic numbers. Tarski proved (1948) that this first-order theory, the theory of real closed fields, is decidable (see model theory).

Geometry— Eudoxus, Euclid and the continuous line

Book V of Euclid's Elements (about 300 BCE), usually credited to Eudoxus, defines when two ratios of magnitudes are equal: a:b=c:da : b = c : d if, for all whole numbers m,nm, n, ma>nbma > nb exactly when mc>ndmc > nd, and likewise with == and <<. In modern terms, a ratio is determined by the set of fractions n/mn/m below it — a Dedekind cut, more than two thousand years early. Dedekind discussed the relationship with Euclid's definition in letters to Rudolf Lipschitz (1876). Geometry also motivated completeness: Euclid's very first construction assumes that two circles cross where they ought to, a continuity assumption that rational coordinates do not satisfy. Hilbert's axioms for geometry (1899) acquired, in later editions, an axiom of completeness for exactly this reason, so that the points of a line correspond to the real numbers (see Euclidean geometry).

Wonder Trails

Wonder Trails

History & global context

History and global context

  • Ancient ratios. Greek mathematicians discovered incommensurable magnitudes (the side and diagonal of a square), and Eudoxus's theory of proportion, preserved in Book V of Euclid's Elements, handled them rigorously without numbers. Negative quantities and zero were treated as numbers in Chinese and Indian mathematics many centuries before Europe (see the integers lesson).
  • Decimals. Decimal fractions were used by al-Uqlīdisī (952–953 CE, Damascus) and al-Kāshī (1427, Samarkand), and popularised in Europe by Simon Stevin's De Thiende (1585). An infinite decimal is, implicitly, a Cauchy sequence.
  • Arithmetisation. In the nineteenth century, analysts wanted the foundations of calculus to rest on arithmetic rather than geometric intuition. William Rowan Hamilton (1837) defined complex numbers as pairs of reals. Karl Weierstrass lectured on a construction of the reals in Berlin in the 1860s. In 1872 three constructions appeared: Charles Méray's and Georg Cantor's by sequences (Méray's dated from 1869), and Richard Dedekind's by cuts, in Stetigkeit und irrationale Zahlen, an idea he said he had conceived in 1858 while teaching calculus in Zürich.
  • Foundations of the naturals. Dedekind's Was sind und was sollen die Zahlen? (1888) and Giuseppe Peano's axioms (1889) characterised the natural numbers themselves. David Hilbert (1900) described the reals axiomatically as a complete ordered field, and Edmund Landau's Grundlagen der Analysis (1930) carried out the whole chain of constructions in full detail.
Further reading

Further reading

  • Edmund Landau, Foundations of Analysis (1930; English translation 1951) — every step from the Peano axioms to the complex numbers, in full.
  • Walter Rudin, Principles of Mathematical Analysis (1953; 3rd ed. 1976) — the appendix to chapter 1 constructs R\R from Dedekind cuts.
  • Terence Tao, Analysis I (2006) — constructs Z\Z, Q\Q and R\R (by Cauchy sequences) with careful attention to well-definedness.
  • Richard Dedekind, Essays on the Theory of Numbers (English translation by W. W. Beman, 1901) — Dedekind's own accounts of cuts and of the natural numbers.
  • Heinz-Dieter Ebbinghaus and others, Numbers (German 1983; English 1990) — the number systems, their constructions and their history, from N\N to the octonions and beyond.