Mathematics Book 1 Companion: Arithmetic and NumbersMaths Book 1 · Companion
0 / 0

Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers

B1·06

Fractions

Around chapter 6: how fractions connect division, the gcd, rates and exact arithmetic in software; three other ways to see them; what the chapter simplifies (fractions equal to floats, comparing by converting, negative mixed numbers); how Python's Fraction adds with a smaller gcd than the textbook formula; four debugging drills; and interview questions.

6 topics · ~14 min read
Updated Suggest a correction

Understanding it better

Concept map

  • ab = the number that times b gives a → four readings: part, division, point, scale factor.
  • Equivalent fractions (ab =kakb; test ad=bc) → lowest terms by the gcd (chapter 5), unique → one stored form per value.
  • Compare by common denominator or cross-multiplying → dense: always another fraction between two (average, mediant) → the Farey sequence and best approximations.
  • Add like pieces (common denominator, the lcm) ≠ mediant (combine records) ≠ average of rates.
  • Multiply = area, "of" → divide = multiply by the reciprocal → dividing by less than 1 enlarges.
  • Exactness costs size: denominators grow in long calculations → decimals (chapter 7), rounding rules, number types in code.
  • Next: decimals and percentages (chapter 7), ratio and rates (chapter 8), negative fractions (chapter 9), fractions don't fill the line (chapter 12).

Explain it differently

Fractions as exchange rates. 34 is "3 for every 4": a rate for swapping one kind of thing for another. Multiplying fractions chains exchanges (34 of a litre per kilogram, times 25 kilograms per tin, is 310 of a litre per tin); dividing runs an exchange backwards, which is why it flips.

A common denominator is a common currency. You can't add 3 euros and 5 dollars by adding 3 and 5; you convert both to one currency first. Thirds and quarters are different currencies; twelfths are one both can be changed into without loss. The lcm is the smallest such currency.

The cricket scorer and the baker. A baker with 12 a cake and 13 of a cake has 56 of a cake (adding amounts). A scorer with 1 run off 2 balls and 1 off 3 has 2 off 5 (adding records). Same symbols, different questions; knowing which person you are is most of the problem.

Gaps and misconceptions

What the chapter oversimplifies

1. "110 and 0.1 are the same number", which is false in code. The chapter treats a fraction and its decimal as one number. In software, a float written 0.1 is a different fraction, so exact equality across types surprises people:

Python
from fractions import Fraction as F
print(F(1, 2) == 0.5, hash(F(1, 2)) == hash(0.5), F(1, 10) == 0.1, F(3, 10) == 0.1 * 3)
print(F(0.1) == F(1, 10), F(0.1).limit_denominator(1000), F("0.1") == F(1, 10))
print(len({F(1, 2), 0.5, 1/2}), len({F(1, 10), 0.1}))
Text
True True False False
False 1/10 True
1 2

12 equals the float 0.5 (a binary fraction, exactly representable), and Python even gives them the same hash, so a set holds one of them. 110 is not equal to the float 0.1, so a set holds both. Building a Fraction from the string "0.1" gives 110; from the float it gives the float's exact value, which limit_denominator can round back. Rule: create fractions from strings or integers, not floats.

2. "To compare fractions, convert them to decimals", which can tie numbers that differ. By hand, decimals to enough places always separate two different fractions. Floats keep only about 16 significant digits:

Python
from fractions import Fraction as F
a, b = F(10**17 + 1, 10**17), F(10**17 + 2, 10**17)
print(float(a) == float(b), float(a) < float(b), a < b)
print(sorted([F(2, 3), F(10**17 + 1, 10**17), F(1, 1)], key=float))
print(sorted([F(2, 3), F(10**17 + 1, 10**17), F(1, 1)]))
Text
True False True
[Fraction(2, 3), Fraction(100000000000000001, 100000000000000000), Fraction(1, 1)]
[Fraction(2, 3), Fraction(1, 1), Fraction(100000000000000001, 100000000000000000)]

1+10−17 and 1+2×10−17 both become the float 1.0, so the comparison says they're equal, and sorting by float puts 1+10−17 before 1 (the tie keeps the input order). Cross-multiplying (the chapter's test) is exact. Drill D2 shows that it has its own trap.

3. "A mixed number is the division algorithm", which only works as written for positive fractions. The chapter's fractions are positive. For negative ones, the division algorithm with a remainder from 0 to b−1 gives −7=−4×2+1, so a formatter built on it writes −72 as "−412", which reads as −4.5. Drill D1.

Common misconceptions

Misconception What's actually true Where it's shown
"Fraction(0.1) is one tenth." It's the float's exact value, a fraction with denominator 255; use Fraction("0.1"). What the chapter oversimplifies, point 1
"Converting to decimals is a safe way to compare fractions." Floats can't separate fractions closer than about 10−16 relative; cross-multiply instead. What the chapter oversimplifies, point 2
"Cross-multiplying always compares fractions correctly." Only when both denominators are positive; normalise the sign first. Drill D2
"divmod turns any fraction into a mixed number." For negative fractions it gives a floored whole part; format the sign separately. Drill D1
"Fractions with integer parts are exact in every language." Only with arbitrary-size integers; JavaScript numbers lose exactness past 253. Drill D3
"The average of the daily rates is the overall rate." Records combine as the mediant: total successes over total tries. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Fractions are built from pairs. Formally, a fraction is a pair (a,b) with b≠0, where pairs are treated as the same when ad=bc (an equivalence relation). The same construction, starting from any system where you can multiply but not always divide, builds a "field of fractions"; algebra uses it to build fractions of polynomials, which is what partial fractions in calculus manipulate.
  • Density without completeness. Between any two fractions there's another, yet fractions leave gaps (2 isn't one; chapter 12). Both facts are needed to understand why calculus needs real numbers.
  • Best approximations. Among fractions with denominator at most n, the closest to a given number are found from its continued fraction (chapter 5's companion) or by walking the Stern–Brocot tree (the exercises' "What the chapter leaves out"). This is how gear ratios, calendar cycles and 355113 are chosen.

Applying it

Code walkthrough

The textbook rule ab+cd =ad+bcbd, followed by reducing, works but multiplies big numbers and then takes a gcd of big numbers. Python's Fraction does better. Excerpt from Lib/fractions.py in Python 3.13 (on your computer: python3 -c "import fractions; print(fractions.__file__)"):

Python
    def _add(a, b):
        """a + b"""
        na, da = a._numerator, a._denominator
        nb, db = b._numerator, b._denominator
        g = math.gcd(da, db)
        if g == 1:
            return Fraction._from_coprime_ints(na * db + da * nb, da * db)
        s = da // g
        t = na * (db // g) + nb * s
        g2 = math.gcd(t, g)
        if g2 == 1:
            return Fraction._from_coprime_ints(t, s * db)
        return Fraction._from_coprime_ints(t // g2, s * (db // g2))

Both inputs are already in lowest terms. If the denominators share no factor (g == 1), the textbook result is already in lowest terms (any prime dividing bd divides exactly one of b,d, and can't divide ad+bc), so no reduction is needed. Otherwise it uses the lcm as the common denominator (s×d is lcm(b,d)) and then only checks the numerator against the small number g, because only factors of g can still be shared. _from_coprime_ints builds the result without another gcd. Traced, and timed against the textbook method:

Python
"""Fraction._add's steps, traced, and what they save."""
from fractions import Fraction
from math import gcd
import time

def add_traced(na, da, nb, db):
    g = gcd(da, db)
    if g == 1:
        return f"g=1: {na * db + da * nb}/{da * db}"
    s = da // g
    t = na * (db // g) + nb * s
    g2 = gcd(t, g)
    return f"g={g} s={s} t={t} g2={g2}: {t // g2}/{s * (db // g2)}"

print(add_traced(1, 6, 1, 10), "| Fraction says", Fraction(1, 6) + Fraction(1, 10))
print(add_traced(1, 4, 1, 9), "| Fraction says", Fraction(1, 4) + Fraction(1, 9))
print(add_traced(5, 12, 7, 18), "| Fraction says", Fraction(5, 12) + Fraction(7, 18))

def naive_harmonic(n):
    top, bottom = 0, 1
    for k in range(1, n + 1):
        top, bottom = top * k + bottom, bottom * k     # a/b + 1/k = (ak + b)/(bk)
        g = gcd(top, bottom)
        top, bottom = top // g, bottom // g
    return top, bottom

for f, name in ((naive_harmonic, "naive (a*d + b*c)/(b*d)"),
                (lambda n: sum(Fraction(1, k) for k in range(1, n + 1)), "Fraction._add")):
    t = time.perf_counter()
    r = f(3000)
    print(f"H_3000 with {name}: {(time.perf_counter() - t) * 1000:.0f} ms")
Text
g=2 s=3 t=8 g2=2: 4/15 | Fraction says 4/15
g=1: 13/36 | Fraction says 13/36
g=6 s=2 t=29 g2=1: 29/36 | Fraction says 29/36
H_3000 with naive (a*d + b*c)/(b*d): 51 ms
H_3000 with Fraction._add: 6 ms

For 16+110: g=2, the common denominator is 30, the numerator 8, and gcd(8,2)=2 leaves 415. For 14+19 nothing is shared, and 1336 comes out directly. Summing H3000, whose denominator has over 1,000 digits, the smaller gcds make it several times faster than reducing ad+bcbd every step. This is Knuth's method from The Art of Computer Programming, volume 2, and it's chapter 5's gcd and lcm doing real work.

Read it yourself

Using _add above, explain why gcd(t,g) is enough: why can't t share a factor with s or with d/g? Then predict the trace for 512+718.

Debugging drills

D1. A recipe app that shows minus four and a half

A cooking app shows ingredient changes as mixed numbers ("use 112 cups more"). For reductions it shows nonsense:

Python
from fractions import Fraction as F

def mixed(q):                      # the formatter from the exercises, P4
    whole, part = divmod(q.numerator, q.denominator)
    if part == 0:
        return str(whole)
    return f"{whole} {part}/{q.denominator}" if whole else f"{part}/{q.denominator}"

for q in (F(7, 2), F(-7, 2), F(-1, 3), F(-6, 3)):
    print(f"{str(q):>5} -> {mixed(q):>6}   float {float(q):.4f}")
Text
  7/2 ->  3 1/2   float 3.5000
 -7/2 -> -4 1/2   float -3.5000
 -1/3 -> -1 2/3   float -0.3333
   -2 ->     -2   float -2.0000

Explain, and fix the formatter.

D2. A leaderboard sorted the wrong way round

A hand-written fraction class (code in the output) sorts scores, some of which come from a calculation that produced negative denominators:

Python
class Q:                           # a hand-rolled fraction that skips sign normalisation
    def __init__(self, top, bottom):
        self.top, self.bottom = top, bottom
    def __lt__(self, o):
        return self.top * o.bottom < o.top * self.bottom

half_neg = Q(1, -2)                # -1/2
third = Q(1, 3)
print("-1/2 < 1/3 ?", half_neg < third)
print("1/3 < -1/2 ?", third < half_neg)
print("sorted:", [f"{q.top}/{q.bottom}" for q in sorted([third, half_neg, Q(0, 1)])])
Text
-1/2 < 1/3 ? False
1/3 < -1/2 ? True
sorted: ['0/1', '1/3', '1/-2']

Explain why −12 sorts above 13, and fix it.

D3. Exact fractions that stopped being exact in JavaScript

A JavaScript port of a fraction library adds unit fractions and reduces with a gcd. Up to 30 terms it agrees with Python; at 40 it doesn't:

JavaScript
// Adding fractions with ordinary JavaScript numbers, then with BigInt.
const gcd = (a, b) => { while (b) [a, b] = [b, a % b]; return a; };
function harmonic(n, one) {
  let top = one - one, bottom = one;
  for (let k = one; k <= n; k += one) {
    [top, bottom] = [top * k + bottom, bottom * k];
    const g = gcd(top, bottom);
    [top, bottom] = [top / g, bottom / g];
  }
  return [top, bottom];
}
for (const n of [20, 30, 40]) {
  const [t, b] = harmonic(n, 1);
  const [T, B] = harmonic(BigInt(n), 1n);
  console.log(n, "Number:", `${t}/${b}`, "BigInt:", `${T}/${B}`, "same:", BigInt(t) === T && BigInt(b) === B);
}
Text
20 Number: 55835135/15519504 BigInt: 55835135/15519504 same: true
30 Number: 9304682830147/2329089562800 BigInt: 9304682830147/2329089562800 same: true
40 Number: 3748351260705216/876081232932283 BigInt: 2078178381193813/485721041551200 same: false

Explain, and fix.

D4. A conversion rate that tripled overnight

A dashboard shows the week's conversion rate (orders ÷ visits) as 8.86%, while finance's figure is 3.23%. The dashboard's code:

Python
from fractions import Fraction as F
# day: (orders, visits)
days = {"Mon": (30, 1_000), "Tue": (28, 900), "Wed": (3, 20), "Thu": (35, 1_100), "Fri": (2, 10)}
rates = [F(o, v) for o, v in days.values()]
avg = sum(rates) / len(rates)
overall = F(sum(o for o, _ in days.values()), sum(v for _, v in days.values()))
print("daily rates %:", [round(float(r) * 100, 2) for r in rates])
print(f"average of daily rates: {float(avg) * 100:.2f}%   overall: {float(overall) * 100:.2f}%")
Text
daily rates %: [3.0, 3.11, 15.0, 3.18, 20.0]
average of daily rates: 8.86%   overall: 3.23%

Which is right, and why are they so different?

Career-oriented

Interview prep

Mid level

Q1. Implement addition and comparison for a fraction type. What invariants do you keep, and why?

How to get there. Normalisation, the formulas, and what the invariants buy.

Q2. A product shows "3 of 4 tasks done" for each project. How do you compute the team's overall progress, and how do you sort projects by progress without floating point?

How to get there. Mediant versus average, and exact comparison.

Senior level

Q1. An API returns a price per unit as a JSON number, and clients compute totals from it. Customers report totals a paisa off from invoices. What's wrong and what do you change?

How to get there. JSON numbers, floats, and where rounding happens.

Q2. A feature flag should go to exactly a third of users. Your implementation hashes the user ID into 100 buckets and enables buckets 0 to 32. Review it.

How to get there. Fractions that don't divide the bucket count, and stability.

Staff level

Q1. Several services in your company store and exchange monetary amounts and rates in different ways (floats, decimals, integer minor units, exact fractions). Define a standard.

How to get there. What needs exactness, what needs a convention, and how to migrate.

Q2. A planning tool computes resource shares exactly with fractions, and on large plans it becomes slow and its stored documents huge. What do you do?

How to get there. Why the numbers grow, and which exactness the users actually need.