Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers
B1·01
What Numbers Are
Around chapter 1: how its ideas connect to the rest of the book and to software, the same ideas from other angles, what it simplifies (0⁰, −0, precedence in code), how Python's own source decides where brackets go, four debugging drills, and interview questions.
Understanding it better
Concept map
- Pairing (one-to-one correspondence) defines same size → counting is pairing with the number words → the natural numbers 0, 1, 2, … with a successor for each.
- A number is a quantity; a numeral is a name for it. Numerals are the subject of chapter 2 (place value, bases); the same split appears in software as value versus representation (an integer versus its decimal string, its binary bits, its JSON text).
- Numbers do three jobs: cardinal (how many), ordinal (which position), nominal (a label). Only cardinal numbers, and differences of ordinal ones, support arithmetic.
- The four operations are stories: combine, take away / compare / missing part, repeated addition / area / scaling, share / group. Inverses tie them in pairs.
- Properties (commutative, associative, distributive, identities) follow from the stories; conventions (order of operations, power towers) were agreed.
- Where the stories stop: negative results (chapter 9), fractions (chapter 6), division by zero (never).
- Machine numbers are a finite model: fixed-width integers overflow (chapter 3), floating point rounds (chapters 3 and 7). Software Engineering, Volume 1, chapter 06 covers number representation inside the computer.
Explain it differently
The shepherd's pouch. A shepherd who can't count puts one pebble in a pouch for each sheep that leaves in the morning, and takes one out for each sheep that returns. A pebble left over means a sheep is missing. That's the whole of chapter 1's first idea: you can know two collections are the same size without knowing the size.
The vending machine. A machine that takes ₹10 coins and sells ₹30 drinks does grouping division: insert coins until there are three, release a drink, repeat. Coins left over at the end are the remainder, and the machine's "insert ₹20 more" display is the missing-part story of subtraction.
Value and representation. In code, 42, "42", 0b101010 and 0x2A are four representations; the first, third and fourth are the same integer value, the second is text. Chapter 1's number-versus-numeral is the same distinction a type system enforces, and the bugs in the drills below happen exactly where it's ignored.
Gaps and misconceptions
What the chapter oversimplifies
1. "Division by zero is undefined", but is a different case. The chapter treats undefined expressions as having no value. is the classic case where conventions differ: many mathematicians define it as 1 (it makes formulas for counting and for polynomials work without exceptions), while in analysis it's left undefined, because approaches different values depending on how and approach 0. Programming languages pick 1. Measured:
print(0 ** 0, 0.0 ** 0, pow(0, 0))
import math
print(math.pow(0, 0), (-8) ** (1/3))
try:
print(0 / 0)
except ZeroDivisionError as e:
print("ZeroDivisionError:", e)
1 1.0 1
1.0 (1.0000000000000002+1.7320508075688772j)
ZeroDivisionError: division by zero
Python gives for integers and floats, and still refuses . The second line shows another simplification: "should" be −2, but 1/3 is a float that isn't exactly a third, and Python answers with a complex number (one of the three cube roots of −8 in the complex numbers). Chapter 10 covers roots of negative numbers properly.
2. "Zero is zero", but floating point has two. IEEE 754 floating point has a positive and a negative zero, equal to each other but distinguishable by division:
console.log(0 ** 0, 0 / 0, 1 / 0, -1 / 0, 1 / -0);
1 NaN Infinity -Infinity -Infinity
1 / -0 is -Infinity. Negative zero records the sign of a number that was too small to represent, which matters in some numerical code (a value that underflowed from below). It's an engineering device; in arithmetic there is one zero.
3. "The order of operations is a convention" understates how it's built into tools. Every programming language turns the convention into a precedence table in its grammar, and some cases differ from school mathematics: Python's -x**2 is , like mathematics; Excel's =-x^2 is ; JavaScript refuses -x ** 2. The code walkthrough below reads Python's table.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| " is undefined, like ." | It's a matter of convention: algebra and every mainstream language take ; analysis leaves it undefined. | What the chapter oversimplifies, point 1 |
| "There's only one zero in a computer." | IEEE 754 floats have +0 and −0; they compare equal, but 1 / -0 is -Infinity. |
What the chapter oversimplifies, point 2 |
| "Brackets in code are only for when you need them." | Unneeded brackets are often worth keeping for readers; ast.unparse removes them, which shows exactly which ones the grammar needs. |
Code walkthrough |
| "An ID made of digits is a number." | It's a label; stored as a number it loses leading zeros and, in JavaScript, digits beyond . | Debugging drills D1 and D3 |
| "The average of daily averages is the average." | Only when every day has the same count; otherwise compute from totals. | Debugging drill D4 |
Theoretical gaps: the ideas behind the chapter
- Why the properties hold "for all numbers" needs induction (exercises, "What the chapter leaves out"): the pictures convince, induction proves.
- Why conventions are chosen as they are: precedence follows how often expressions occur. Sums of products are common (), products of sums less so, so products bind tighter and sums need the brackets.
- Operations as functions: is a function from pairs of numbers to numbers. Commutativity and associativity are properties a function may or may not have. Thinking of operations this way is the step from arithmetic to algebra (and to code, where
operator.addis literally a function, as in exercise P2).
Applying it
Code walkthrough
Python's standard library can turn a parsed expression back into source code (ast.unparse), and it must decide where brackets are needed. The decision is chapter 1's order of operations, written as code. Excerpts from Lib/ast.py in Python 3.13 (the file is on your computer if Python 3.13 is installed: python3 -c "import ast; print(ast.__file__)").
The precedence table
@_simple_enum(IntEnum)
class _Precedence:
"""Precedence table that originated from python grammar."""
NAMED_EXPR = auto() # <target> := <expr1>
TUPLE = auto() # <expr1>, <expr2>
YIELD = auto() # 'yield', 'yield from'
TEST = auto() # 'if'-'else', 'lambda'
OR = auto() # 'or'
AND = auto() # 'and'
NOT = auto() # 'not'
CMP = auto() # '<', '>', '==', '>=', '<=', '!=',
# 'in', 'not in', 'is', 'is not'
EXPR = auto()
BOR = EXPR # '|'
BXOR = auto() # '^'
BAND = auto() # '&'
SHIFT = auto() # '<<', '>>'
ARITH = auto() # '+', '-'
TERM = auto() # '*', '@', '/', '%', '//'
FACTOR = auto() # unary '+', '-', '~'
POWER = auto() # '**'
AWAIT = auto() # 'await'
ATOM = auto()
def next(self):
try:
return self.__class__(self + 1)
except ValueError:
return self
Each level is a number, and later means binds tighter: ARITH (, ) < TERM (, ) < FACTOR (unary minus) < POWER (**). That's the school convention (powers, then multiplication and division, then addition and subtraction) with one addition, unary minus, slotted between multiplication and powers. next() gives the level just above, which the next function uses to handle left-to-right reading.
Deciding where brackets go
def visit_BinOp(self, node):
operator = self.binop[node.op.__class__.__name__]
operator_precedence = self.binop_precedence[operator]
with self.require_parens(operator_precedence, node):
if operator in self.binop_rassoc:
left_precedence = operator_precedence.next()
right_precedence = operator_precedence
else:
left_precedence = operator_precedence
right_precedence = operator_precedence.next()
self.set_precedence(left_precedence, node.left)
self.traverse(node.left)
self.write(f" {operator} ")
self.set_precedence(right_precedence, node.right)
self.traverse(node.right)
binop_rassoc is frozenset(("**",)): only ** is right-associative. For every other operator, the right operand is required to bind tighter than the operator itself (next()), so 1 - (2 - 3) keeps its brackets but (1 - 2) - 3 loses them: that's "left to right" for subtraction. For ** it's the other way round, which is "power towers read from the top down". require_parens (a few lines earlier in the file) adds brackets when the precedence the context demands is greater than the operator's own:
def require_parens(self, precedence, node):
"""Shortcut to adding precedence related parens"""
return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
Running it shows the convention at work:
import ast
for src in ["(1 + 2) * 3", "1 + (2 * 3)", "(1 - 2) - 3", "1 - (2 - 3)", "(2 ** 3) ** 2", "2 ** (3 ** 2)", "(-2) ** 2", "-(2 ** 2)"]:
print(f"{src:16} -> {ast.unparse(ast.parse(src))}")
(1 + 2) * 3 -> (1 + 2) * 3
1 + (2 * 3) -> 1 + 2 * 3
(1 - 2) - 3 -> 1 - 2 - 3
1 - (2 - 3) -> 1 - (2 - 3)
(2 ** 3) ** 2 -> (2 ** 3) ** 2
2 ** (3 ** 2) -> 2 ** 3 ** 2
(-2) ** 2 -> (-2) ** 2
-(2 ** 2) -> -2 ** 2
Every bracket the convention makes unnecessary is removed, and every one it needs is kept.
Read it yourself
Here is visit_UnaryOp from the same file. Without running anything, explain why -(2 ** 2) is written back as -2 ** 2 while (-2) ** 2 keeps its brackets. Which two precedence levels are compared in each case?
def visit_UnaryOp(self, node):
operator = self.unop[node.op.__class__.__name__]
operator_precedence = self.unop_precedence[operator]
with self.require_parens(operator_precedence, node):
self.write(operator)
# factor prefixes (+, -, ~) shouldn't be separated
# from the value they belong, (e.g: +1 instead of + 1)
if operator_precedence is not _Precedence.FACTOR:
self.write(" ")
self.set_precedence(operator_precedence, node.operand)
self.traverse(node.operand)
Debugging drills
D1. Phone numbers that lost a digit
A script imports customer landlines from a CSV file into a database and writes them back out for an SMS provider, which rejects every Chennai and Bengaluru number.
import csv, io
rows = list(csv.reader(io.StringIO("name,landline\nAsha,04428112233\nRavi,08025556677\n")))
stored = {name: int(phone) for name, phone in rows[1:]} # the bug: a label stored as a number
print(stored)
print({name: str(n) for name, n in stored.items()}, " <- what gets written back")
{'Asha': 4428112233, 'Ravi': 8025556677}
{'Asha': '4428112233', 'Ravi': '8025556677'} <- what gets written back
What went wrong, and what's the fix? Why can't the data simply be repaired by adding a zero back?
D2. A formula that's right on paper and wrong in code
A physics helper computes the energy term for a displacement x, and a colleague's test expects the square of the negative displacement.
x = 3
print(-x**2, (-x)**2, -x * -x)
-9 9 9
Which value is "right"? Explain each output, and what you'd change so the code and the test can't disagree again.
D3. The order ID that pointed at someone else's order
A JavaScript dashboard reads orders from an API and fetches details by ID. For some orders it shows another customer's details.
const order = JSON.parse('{"orderId": 9007199254740993, "amount": 499}');
console.log(order.orderId, order.orderId === 9007199254740992);
const safe = JSON.parse('{"orderId": "9007199254740993"}');
console.log(safe.orderId, BigInt(safe.orderId) + 1n);
9007199254740992 true
9007199254740993 9007199254740994n
Explain the first line, and why the fix belongs in the API, not in the dashboard.
D4. NaN on the weekly dashboard
A dashboard computes a weekly "average order value" by averaging three daily averages. One shop had a day with no orders.
const days = [{ revenue: 5400, orders: 12 }, { revenue: 0, orders: 0 }, { revenue: 3000, orders: 6 }];
const avgs = days.map((d) => d.revenue / d.orders);
console.log(avgs, avgs.reduce((a, b) => a + b, 0) / avgs.length);
const total = days.reduce((t, d) => ({ revenue: t.revenue + d.revenue, orders: t.orders + d.orders }), { revenue: 0, orders: 0 });
console.log(total.revenue / total.orders);
[ 450, NaN, 500 ] NaN
466.6666666666667
There are two bugs here, not one. Name both.
Career-oriented
Interview prep
Mid level
Q1. A product manager says a report's "average basket size" is wrong because it's the mean of each store's average. Explain the problem and how you'd compute it.
How to get there. Name the two different averages, show a two-store example where they differ, say which question each answers, and give the formula.
Q2. Why might 0.1 + 0.2 == 0.3 be false in most languages, and how would you compare floating-point results correctly?
How to get there. Representation (decimal fractions in binary), rounding per operation, then the fix: tolerance comparisons, or decimal/integer types where exactness matters.
Senior level
Q1. You're designing a public API that returns entity IDs which are 64-bit integers. What type do you use in the JSON, and why?
How to get there. Who consumes the API (JavaScript, spreadsheets, other languages), what each does with a JSON number, and what an ID is.
Q2. A team argues about whether x / 0 in their metrics library should throw, return null, or return Infinity. How do you decide?
How to get there. Who calls it, what happens downstream with each choice, and what the value means.
Staff level
Q1. Your company's finance, analytics and product teams each compute "revenue per user" and get different numbers. How would you make the number trustworthy across the organisation?
How to get there. The arithmetic is easy; the definitions aren't. Talk about what's being counted, what's being divided, ownership and verification.
Q2. A legacy system stores phone numbers, pincodes and account numbers as integers in dozens of services. Plan the fix.
How to get there. Scope, risk, sequencing and data repair, not just the target design.