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

Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers

B1·03

Adding and Subtracting

Around chapter 3: how carrying, borrowing and checking connect to software, three other ways to see them, what the chapter simplifies (exact sums of inexact values, 32-bit truncation, counting fences), how Python's statistics module adds floats exactly, four debugging drills, and interview questions.

6 topics · ~11 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Column addition = expanded form + regrouping by place (commutativity, associativity, distributivity) + carrying (re-bundling a column of ten or more).
  • Carries are bounded (0 or 1 for two numbers, at most n−1 for n) → carry flags, fixed-width adders, overflow when the last carry has nowhere to go.
  • Subtraction: decomposition (re-bundle the top number), equal addition (same difference), counting up (the missing-part story), complements (subtract by adding) → two's complement (chapter 9).
  • Checking: the inverse, an estimate, casting out nines (proved in chapter 5); each has blind spots, so independent checks are combined.
  • In machines: integer addition is exact until it overflows; floating-point addition rounds at every step, so it's commutative but not associative, and sums depend on order.
  • In systems: totals are reconciled against independent sources; money is kept in exact units.

Explain it differently

A cash drawer. A shopkeeper adding up takings counts coins into piles of ten and swaps each pile for a ₹10 note: that's carrying. Giving change from a ₹500 note when the drawer has no ₹1 coins means breaking a ₹10 note into coins: that's borrowing. Nothing in the drawer changes value when a note is broken; only its form changes.

A thermometer. The difference between 32° and 25° is the same as between 37° and 30°: slide both readings up by 5 and the gap stays 7. That's the same-difference rule, and it's why equal addition works.

A ledger with two columns. Double-entry bookkeeping records every amount twice (once as a debit, once as a credit), so the two columns must always total the same. A mismatch proves an error without saying where, like casting out nines, but much more sensitive: it catches any error that doesn't happen to appear identically on both sides.

Gaps and misconceptions

What the chapter oversimplifies

1. "Add the numbers exactly and the answer is exact", when the numbers themselves aren't. The chapter's floating-point experiment shows sums drifting. Even a perfectly exact sum can't fix inputs that were already approximations. Python's statistics module adds floats exactly (code walkthrough), and the exact sum of ten floating-point 0.1s is not 1:

Python
import statistics
data = [1e16, 1.0, -1e16] * 1000
loop = 0.0
for x in data:
    loop += x
print("loop:", loop / len(data), " statistics.mean:", statistics.mean(data), " exact:", 1000 / 3000)
print(statistics._sum([0.1] * 10), (0.1).as_integer_ratio())
print(statistics.mean([0.1, 0.2, 0.3]), sum([0.1, 0.2, 0.3]) / 3)
Text
loop: 0.0  statistics.mean: 0.3333333333333333  exact: 0.3333333333333333
(<class 'float'>, Fraction(18014398509481985, 18014398509481984), 10) (3602879701896397, 36028797018963968)
0.2 0.19999999999999998

The plain loop loses every 1.0 next to 1016 and gets a mean of 0; statistics.mean gets 13. But the exact sum of ten copies of the float 0.1 is 1801439850948198518014398509481984, slightly more than 1, because each stored 0.1 is slightly more than 110 (its exact value is the second fraction on that line). Exact arithmetic on inexact data gives the exact answer to a slightly different question. And statistics.mean([0.1, 0.2, 0.3]) prints 0.2 where the naive average prints 0.19999999999999998: careful summation also decides which way the final rounding falls.

2. "Overflow is when a number is too big", but some languages truncate silently in ordinary-looking code. JavaScript numbers are floats, but its bitwise operators convert to 32-bit integers first. Code that uses | 0 "to keep a value an integer" wraps exactly like a 32-bit register:

JavaScript
let views = 2147483647;          // 2**31 - 1
views = (views + 1) | 0;         // "| 0" keeps it an integer, people say
console.log(views);
console.log((2 ** 32 + 5) | 0, 4000000000 | 0, Math.trunc(4000000000));
Text
-2147483648
5 -294967296 4000000000

231−1+1 becomes −231; 232+5 becomes 5; four billion becomes −294,967,296 (that's 4,000,000,000−232). Math.trunc keeps the value. Debugging drill D3 is this bug.

3. "Subtraction finds the difference", but counting things between two numbers is a different question. From the 3rd of the month to the 10th is 10−3=7 days of difference, but 8 calendar days if you count both ends, and 7 nights at a hotel. Subtraction answers "how far apart"; "how many items from here to there, inclusive" is the difference plus 1. This fencepost error (30 m of fence with a post every 3 m needs 11 posts, not 10) is the most common off-by-one in software; drill D4.

Common misconceptions

Misconception What's actually true Where it's shown
"An exact sum of floats gives the exact total." It gives the exact total of the stored approximations: ten float 0.1s sum to slightly more than 1. What the chapter oversimplifies, point 1
"x | 0 just removes the fraction in JavaScript." It converts to a 32-bit integer and wraps: 4000000000 | 0 is −294,967,296. What the chapter oversimplifies, point 2; drill D3
"The number of days from the 3rd to the 10th is 7." 7 is the difference; counting both ends gives 8 days; a hotel charges 7 nights. Say which you mean. Drill D4
"Comparing money totals with == works if you round first." Rounding hides it in one case and fails at the next boundary; store paise and compare integers. Drill D1
"Borrowing just adds ten to the column." It moves ten from the next place; forgetting to take it away from there inflates the answer. Drill D2

Theoretical gaps: the ideas behind the chapter

  • Why fixed-width arithmetic is "modular": an 8-bit adder computes sums modulo 256, and 32-bit arithmetic modulo 232. Wrap-around isn't a malfunction; it's arithmetic in a different number system, the remainders of chapter 5. Two's complement (chapter 9) works because subtraction modulo 2n is the same operation as addition of the complement.
  • Error analysis of summation: adding n floating-point numbers one by one can accumulate error that grows with n; pairwise summation (adding in a tree) grows with logn, and compensated summation makes it nearly independent of n. Numerical analysis studies exactly this.
  • Associativity and parallelism: exact addition can be split across processors and combined in any order, which is what makes parallel sums possible. Floating-point sums lose that guarantee, so parallel totals can differ from run to run unless the order is fixed or the arithmetic is exact (senior exercise S2 in the exercises).

Applying it

Code walkthrough

Python's statistics module computes means and variances without the summation drift of a plain loop. Its trick is chapter 3's exact arithmetic, done with chapter 6's fractions: every float is converted to its exact value as a fraction, the fractions are added exactly, and only the final result is rounded. Excerpts from Lib/statistics.py in Python 3.13 (on your computer: python3 -c "import statistics; print(statistics.__file__)").

Turning a float into an exact fraction

Python
def _exact_ratio(x):
    """Return Real number x to exact (numerator, denominator) pair.

    >>> _exact_ratio(0.25)
    (1, 4)

    x is expected to be an int, Fraction, Decimal or float.
    """

The heart of it (after a long comment about how large such fractions can get) is x.as_integer_ratio(): a float is a binary fraction, so it is exactly a numerator over a power of two, and Python can say which. (0.1).as_integer_ratio() is (3602879701896397,36028797018963968), the second denominator being 255.

Adding exactly

Python
    count = 0
    types = set()
    types_add = types.add
    partials = {}
    partials_get = partials.get
    for typ, values in groupby(data, type):
        types_add(typ)
        for n, d in map(_exact_ratio, values):
            count += 1
            partials[d] = partials_get(d, 0) + n
    if None in partials:
        # The sum will be a NAN or INF. We can ignore all the finite
        # partials, and just look at this special one.
        total = partials[None]
        assert not _isfinite(total)
    else:
        # Sum all the partial sums using builtin sum.
        total = sum(Fraction(n, d) for d, n in partials.items())

partials maps each denominator to the sum of the numerators with that denominator. That's chapter 6's rule, "same denominator: add the numerators", used as an optimisation: floats with the same exponent share a denominator, so most additions are plain integer additions, exact and cheap. Only at the end are the groups combined as fractions over a common denominator. Nothing is rounded until the very last step, when the mean is converted back to a float.

Read it yourself

The docstring of _sum contains this example:

Python
    # Built-in sum returns zero.
    >>> _sum([1e50, 1, -1e50] * 1000)
    (<class 'float'>, Fraction(1000, 1), 3000)

Explain, using the code above, why _sum gets exactly 1000 here. Then explain this, measured in Python 3.13: the built-in sum of that list does return 0, as the comment says, yet sum([1e50, 1.0, -1e50] * 1000), which differs only in writing 1.0 for 1, returns 1000.0.

Text
>>> sum([1e50, 1, -1e50] * 1000), sum([1e50, 1.0, -1e50] * 1000)
(0.0, 1000.0)

Debugging drills

D1. The bill that didn't equal itself

A checkout compares the sum of three ₹10.10 items with the price list's total of ₹30.30 before charging, and refuses some orders:

Python
items = [10.10, 10.10, 10.10]
total = sum(items)
print(total, total == 30.30, round(total, 2) == 30.30)
paise = [1010, 1010, 1010]
print(sum(paise), sum(paise) == 3030)
Text
30.299999999999997 False True
3030 True

Explain the first line. Is round(total, 2) == 30.30 a fix?

D2. A subtraction that's right only sometimes

Someone writes column subtraction from memory:

Python
def subtract(a, b):
    """A first attempt at column subtraction."""
    top = [int(d) for d in str(a)]
    bot = [int(d) for d in str(b).zfill(len(top))]
    out = []
    for i in range(len(top) - 1, -1, -1):
        if top[i] < bot[i]:
            top[i] += 10             # borrow ten for this column
        out.append(top[i] - bot[i])
    return int("".join(str(d) for d in reversed(out)))

for a, b in [(57, 23), (52, 38), (7032, 2845), (1000, 1)]:
    print(f"{a} - {b} = {subtract(a, b)}   (true: {a - b})")
Text
57 - 23 = 34   (true: 34)
52 - 38 = 24   (true: 14)
7032 - 2845 = 5297   (true: 4187)
1000 - 1 = 1009   (true: 999)

Find the bug, explain the pattern of right and wrong answers, and fix it.

D3. The view counter that went negative in JavaScript

A dashboard keeps a running total with total = (total + n) | 0, copied from code that needed integers. Totals above about two billion go negative. Using the output in "What the chapter oversimplifies", point 2, explain exactly what | 0 does and give the fix.

D4. The hotel bill and the fence

A booking system bills per day of stay, counting from check-in to check-out:

Python
from datetime import date
check_in, check_out = date(2026, 10, 3), date(2026, 10, 10)
nights = (check_out - check_in).days
days_on_site = nights + 1
print("nights:", nights, " days you're there (3rd to 10th inclusive):", days_on_site)
rate = 2400
print("billed for days:", days_on_site * rate, " billed for nights:", nights * rate)
fence = 30             # metres of fence, posts every 3 m
print("gaps:", fence // 3, " posts:", fence // 3 + 1)
Text
nights: 7  days you're there (3rd to 10th inclusive): 8
billed for days: 19200  billed for nights: 16800
gaps: 10  posts: 11

The guest disputes the bill. Who's right, and what's the general lesson?

Career-oriented

Interview prep

Mid level

Q1. Why shouldn't you store money in a float or double? What do you use instead?

How to get there. Representation (binary fractions), what goes wrong (equality, accumulated drift, rounding at boundaries), and the alternatives with their trade-offs.

Q2. How would you test a function that adds two arbitrarily long numbers given as strings?

How to get there. Properties, edge cases, an oracle.

Senior level

Q1. Two runs of the same nightly job produce slightly different floating-point totals. Nothing in the data changed. How is that possible, and what do you do?

How to get there. Non-associativity plus non-deterministic order.

Q2. Design the check that tells you an exported total and an imported total of the same data agree.

How to get there. Exact versus approximate checks, and checks that see different errors.

Staff level

Q1. Your company's ledger occasionally shows a one-paisa difference between the sum of line items and the invoice total. Finance wants it gone. What's the root cause likely to be, and what's the systemic fix?

How to get there. Rounding at different steps, and who owns the rule.

Q2. How would you make "the numbers agree" a property of your whole data platform rather than a hope?

How to get there. Invariants, independent sources, ownership.