Volume 1: Foundations to Precalculus · Part I: Foundations

Chapter 1. Numbers, the Number Line, and Arithmetic

Chapter map: we begin where everything begins — with numbers. Not to relearn how to add, but to reconnect the arithmetic you can already do with the vocabulary, structure, and reasons behind it. We will see why number systems kept having to grow, how place value makes arithmetic (and computers) work, which laws of arithmetic quietly power all of algebra, why a negative times a negative must be positive, why "order of operations" is a convention rather than a law of nature, and how fixed-width integers in a computer behave differently from the integers of mathematics.

Why it matters: every quantity you will ever compute with (a bank balance, a sensor reading, a pixel coordinate, a 64-bit counter) lives in one of these number systems, and most arithmetic bugs, in spreadsheets and in production code alike, come from a value obeying different rules from the ones you assumed. This chapter is where those rules are made explicit.

Where this chapter sits

Prerequisites: none beyond everyday arithmetic. If you have read The Knowledge Map, you know this is the root of the dependency tree.

This chapter unlocks: fractions and decimals (Chapter 2), exponents (Chapter 3), algebraic expressions (Chapter 4), and — through divisibility and primes — number theory (Chapter 23). The arithmetic laws in Section 1.4 are the rules that every algebraic manipulation in the rest of the book relies on.

Time budget: if the mastery check at the end is easy, skim and move on. The sections most worth your time even if you are confident are Section 1.4, Section 1.5, and Section 1.9.

1.1. Kinds of number

1.1.1. The problem

Suppose you only had the counting numbers 1, 2, 3, … . You could count sheep, but you could not:

  • say how many sheep are in an empty field;

  • record that you owe someone three sheep;

  • share two sheep fairly among three people;

  • state the exact length of the diagonal of a square field whose sides are 1 kilometre.

Each of these is a perfectly ordinary question, and each one breaks the number system you had. The history of numbers is largely the history of patching those breaks. Each patch produced a larger system that contains the old one, and each larger system has a name and a symbol you will meet constantly in technical reading.

1.1.2. Intuition: each system fixes a failure of the last

Think of it as a sequence of feature requests.

  • Counting gives the natural numbers. You can add and multiply them freely and always stay inside.

  • Subtraction fails: \(3 - 5\) has no answer among counting numbers. Fix: add zero and the negatives. Now you have the integers.

  • Division fails: \(2 \div 3\) has no answer among integers. Fix: allow ratios of integers. Now you have the rational numbers.

  • Measuring fails: the diagonal of a unit square has length \(\sqrt{2}\), and (as we will prove) no ratio of integers squares to exactly 2. Fix: fill every gap in the line. Now you have the real numbers.

Later in the book (Chapter 15) one more failure — \(x^2 = -1\) has no real solution — will drive one more extension, to the complex numbers.

1.1.3. Vocabulary and notation

Before the vocabulary, one piece of notation. Mathematicians collect objects into sets and write \(x \in S\) to mean "\(x\) is an element of the set \(S\)" (read "x is in S"). The symbol \(\in\) is a stylised Greek epsilon, for the Latin est, "is". Writing \(A \subset B\) means "every element of \(A\) is also an element of \(B\)" (read "A is a subset of B"). We will treat sets properly in Chapter 21; for now these two symbols are all you need.

Natural number

The natural numbers are the counting numbers \(0, 1, 2, 3, \ldots\). The set of them is written \(\mathbb{N}\) (a "blackboard bold" N). Whether \(0 \in \mathbb{N}\) is a convention that varies: computer scientists and logicians almost always include 0; some number theorists start at 1. When it matters, authors write \(\mathbb{N}_0\) (with zero) or \(\mathbb{Z}^+\) (positive integers, without zero). This book includes 0.

Integer

An integer is a whole number that may be positive, negative, or zero: \(\ldots, -3, -2, -1, 0, 1, 2, 3, \ldots\). The set is written \(\mathbb{Z}\), from the German Zahlen, "numbers". The integers are closed under addition, subtraction, and multiplication: doing any of those to two integers gives an integer.

Rational number

A rational number is any number that can be written as a ratio \(\dfrac{p}{q}\) of integers \(p\) and \(q\) with \(q \neq 0\). The set is written \(\mathbb{Q}\), for quotient. Examples: \(\tfrac{1}{2}\), \(-\tfrac{7}{3}\), \(5 = \tfrac{5}{1}\), \(0.125 = \tfrac{1}{8}\). In decimal form a rational number either terminates or eventually repeats (shown in Chapter 2).

Irrational number

An irrational number is a real number that is not rational — it cannot be written as a ratio of integers. Its decimal expansion never terminates and never settles into a repeating block. Examples: \(\sqrt{2} = 1.41421356\ldots\), \(\pi = 3.14159265\ldots\), \(e = 2.71828182\ldots\).

Real number

The real numbers, written \(\mathbb{R}\), are all the rational and irrational numbers together: every point on the number line. Every length, every measurement, every point on a continuous scale is a real number. The defining extra property of \(\mathbb{R}\) over \(\mathbb{Q}\) is that it has no gaps (mathematicians call this completeness).

The systems nest inside one another:

\[\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R}.\]

Every natural number is an integer, every integer is rational (\(n = n/1\)), and every rational is real.

Nested sets N inside Z inside Q inside R with example members
Figure 2. The number systems nest. Each is the previous one plus whatever was needed to repair a failure.

1.1.4. Why it works: \(\sqrt{2}\) really is irrational

It is worth seeing why the rationals are not enough, because the argument is short, beautiful, and the template for a whole style of proof (proof by contradiction, Chapter 22).

Suppose, hoping for a contradiction, that \(\sqrt{2} = p/q\) where \(p\) and \(q\) are integers and the fraction is already in lowest terms (no common factor — we can always cancel until this is true). Then

\[\begin{aligned} \sqrt{2} &= \frac{p}{q} \\ 2 &= \frac{p^2}{q^2} && \text{(square both sides)} \\ 2q^2 &= p^2. && \text{(multiply both sides by } q^2\text{)} \end{aligned}\]

So \(p^2\) is even. The square of an odd number is odd, so \(p\) itself must be even: write \(p = 2k\). Substituting,

\[\begin{aligned} 2q^2 &= (2k)^2 = 4k^2 \\ q^2 &= 2k^2. && \text{(divide both sides by 2)} \end{aligned}\]

So \(q^2\) is even, and therefore \(q\) is even. But now \(p\) and \(q\) are both even, so they share the factor 2 — contradicting "lowest terms". The assumption was impossible: \(\sqrt{2}\) is not a ratio of integers.

The scandal of the diagonal

Legend says the Pythagoreans, who believed "all is number" (meaning whole numbers and their ratios), were so disturbed by the irrationality of \(\sqrt{2}\) that they drowned Hippasus of Metapontum for revealing it. The story is almost certainly embellished, but the mathematical shock was real: the Greeks responded by developing geometry largely separately from arithmetic for the next two thousand years. The word "irrational" originally meant simply "not a ratio", not "unreasonable".

1.1.5. Failure modes

Rational does not mean "has a short decimal"

\(\tfrac{1}{3} = 0.333\ldots\) has an infinite decimal expansion but is perfectly rational. Irrationality is about the expansion never repeating, not about it being long. Conversely, a calculator display of \(1.414213562\) is a rational approximation — the calculator cannot store \(\sqrt{2}\) exactly. Nor can your computer (Chapter 2 explains why even \(0.1\) is out of reach for binary floating point).

1.1.6. Where you’d use this

  • Money. Prices look like decimals but are really integers in disguise: £19.99 is 1999 pence. Payment systems store whole pence or cents (integers, \(\mathbb{Z}\)) precisely so that totals add up exactly; storing money as float is a classic bug (Chapter 2).

  • Measurement. Every physical length, mass, or time is a real number, but every measurement of it is a rational approximation. A bicycle wheel of diameter 0.7 m rolls \(\pi \times 0.7 \approx 2.199\) m per turn; the exact distance is irrational, so an engineer decides how many digits matter (Section 1.10).

  • Counting things. Stock levels, seats, packets, and array indices are natural numbers. A negative stock level or a fractional seat count is a sign that a value has escaped its proper number system, which makes "which set should this live in?" a useful validation rule for any database column.

Computer-science connection: number types are number systems

Programming languages mirror the mathematical hierarchy, imperfectly:

  • int / uint64 / size_t approximate \(\mathbb{Z}\) and \(\mathbb{N}\) — but with a fixed range (Section 1.9). Python’s int is arbitrary precision and genuinely behaves like \(\mathbb{Z}\), limited only by memory.

  • Python’s fractions.Fraction, or a pair of big integers, represents \(\mathbb{Q}\) exactly.

  • float / double are a finite set of rationals with power-of-two denominators, used to approximate \(\mathbb{R}\). No computer type represents all of \(\mathbb{R}\): there are uncountably many reals and only finitely many bit patterns.

When a bug report says "the totals don’t add up", the root cause is very often a value that silently moved between these systems.

US curriculum

Whole numbers and integers are elementary and middle-school (grades 5–7) material. The classification natural / whole / integer / rational / irrational / real appears explicitly in Grade 8 (Common Core 8.NS) and is revisited in Algebra I. Note: many US textbooks say whole numbers for \(\{0, 1, 2, \ldots\}\) and natural numbers or counting numbers for \(\{1, 2, 3, \ldots\}\).

1.2. The number line

1.2.1. Intuition

The single most useful picture in elementary mathematics is a straight line with a point marked 0, a point marked 1 to its right, and every real number occupying exactly one point. Positive numbers lie to the right of zero, negatives to the left, and the distance from zero records size.

A number line from -4 to 4 with -e, -2, -1/2, 1/3, square root of 2 and pi marked
Figure 3. Every real number is a point on the line: integers, fractions, and irrationals alike.

The line turns arithmetic into motion. Adding 3 means stepping 3 units right. Subtracting 3 means stepping 3 units left. Multiplying by 2 means stretching everything away from zero by a factor of 2; multiplying by \(-1\) means reflecting through zero. You will see these geometric readings return in vectors (Chapter 26) and complex numbers (Chapter 15), where multiplication becomes rotation.

1.2.2. Vocabulary and notation

Order and inequality symbols

\(a < b\) means "\(a\) is less than \(b\)": \(a\) lies to the left of \(b\) on the number line. \(a > b\) means "greater than". \(a \le b\) means "less than or equal to", \(a \ge b\) "greater than or equal to", and \(a \neq b\) "not equal to". The narrow end of \(<\) points at the smaller number. A number is positive if it is \(> 0\), negative if \(< 0\), and non-negative if \(\ge 0\); zero is neither positive nor negative.

Two facts about the line deserve to be said out loud, because they become important in calculus:

  • Density. Between any two different rational numbers there is another one (their average). So there is no "next" rational after 0 — the rationals are packed infinitely tightly.

  • Gaps anyway. Despite that density, the rationals miss points such as \(\sqrt{2}\). The reals fill every gap. This "no gaps" property is exactly what makes limits (Chapter 16) work.

Negative numbers and "smaller"

\(-10 < -2\), even though 10 is "bigger" than 2. On the number line \(-10\) is further left. In everyday speech people say "a bigger loss" for \(-10\), which describes magnitude, not order. When order matters, think "further left = less". Magnitude is captured by absolute value (Section 1.7).

Zooming the number line

A number line you can zoom indefinitely. Mark \(\sqrt{2}\) and keep zooming: each zoom reveals another decimal digit, and the nearest rational points with small denominators (\(\tfrac{7}{5}\), \(\tfrac{17}{12}\), \(\tfrac{41}{29}\), …) light up and are left behind, but the point itself never lands on a rational.

1.3. Place value and number bases

1.3.1. The problem

Write down the number of seconds in a year. You probably wrote something like 31536000, and you did not need a new symbol for it. Compare Roman numerals: XXXI million … there is no good way. The reason modern notation handles any size with only ten symbols is place value: the meaning of a digit depends on its position. Understanding place value precisely lets you work in any base — and base 2 and base 16 are the native tongues of computers.

1.3.2. Intuition

In 2047 the "2" means two thousands, the "0" means no hundreds, the "4" means four tens, and the "7" means seven ones. Each position is worth ten times the position to its right. Nothing is special about ten except that we have ten fingers. Make each position worth two times the one to its right, and you have binary; sixteen, and you have hexadecimal.

2047 in decimal and 101101 in binary with the power of the base above each digit
Figure 4. Positional notation: each position is worth a power of the base.

1.3.3. Why it works

In base \(b\) a digit string \(d_{k} d_{k-1} \ldots d_1 d_0\) (each digit \(d_i\) between 0 and \(b-1\)) stands for

\[d_k b^k + d_{k-1} b^{k-1} + \cdots + d_1 b^1 + d_0 b^0 .\]

Here \(b^k\) means \(b\) multiplied by itself \(k\) times, and \(b^0 = 1\) (powers are the subject of Chapter 3, which also explains why \(b^0 = 1\)). The subscripts on \(d_i\) are labels, not exponents: \(d_0\) is "the digit in position 0", the rightmost one.

Every non-negative integer has exactly one such representation (without leading zeros). The reason is division with remainder: dividing by \(b\) peels off the last digit as the remainder and shifts the rest down one position as the quotient. Repeat until nothing is left.

1.3.4. Vocabulary and notation

Base, digit, and positional notation

The base (or radix) \(b\) of a positional system is how many times larger each position is than the one to its right. A digit is one of the symbols \(0, 1, \ldots, b-1\). Positional (or place-value) notation means a digit’s value is the digit times \(b^{\text{position}}\), counting positions from 0 at the right. When the base is not obvious we write it as a subscript: \(101101_2 = 45_{10}\).

Binary, bit, byte, hexadecimal

Binary is base 2, with digits 0 and 1. A single binary digit is a bit; eight bits make a byte. Hexadecimal ("hex") is base 16, with digits \(0\text{–}9\) then A=10, B=11, C=12, D=13, E=14, F=15. Because \(16 = 2^4\), each hex digit corresponds to exactly four bits (a nibble). Octal is base 8 (three bits per digit). Programming languages mark bases with prefixes: 0b101101, 0x2D, 0o55 all mean 45.

1.3.5. The method

Example 2. Procedure — convert a non-negative integer to base \(b\)

Input: a non-negative integer \(n\) and a base \(b \ge 2\).

Steps:

  1. If \(n = 0\), the answer is "0". Stop.

  2. Divide \(n\) by \(b\), obtaining quotient \(q\) and remainder \(r\) (so \(n = qb + r\) with \(0 \le r < b\)).

  3. Record \(r\) as the next digit, working from right to left.

  4. Replace \(n\) by \(q\). If \(n > 0\), go back to step 2.

Output: the recorded digits, read in reverse order of discovery (last remainder is the leftmost digit).

Example 3. Procedure — convert a base-\(b\) digit string to an integer (Horner’s rule)

Input: digits \(d_k, d_{k-1}, \ldots, d_0\) (left to right) and base \(b\).

Steps:

  1. Set \(v = 0\).

  2. For each digit \(d\), from left to right: set \(v = v \cdot b + d\).

Output: \(v\), the value.

Horner’s rule avoids computing powers at all: each step "shifts left one place" by multiplying by \(b\) and then drops the new digit into the empty units position.

1.3.6. Worked examples

Example 1: 45 to binary. Divide repeatedly by 2.

\[\begin{aligned} 45 &= 22 \times 2 + 1 && \text{digit } d_0 = 1\\ 22 &= 11 \times 2 + 0 && \text{digit } d_1 = 0\\ 11 &= 5 \times 2 + 1 && \text{digit } d_2 = 1\\ 5 &= 2 \times 2 + 1 && \text{digit } d_3 = 1\\ 2 &= 1 \times 2 + 0 && \text{digit } d_4 = 0\\ 1 &= 0 \times 2 + 1 && \text{digit } d_5 = 1 \text{ (quotient is 0: stop)} \end{aligned}\]

Reading the digits from \(d_5\) down to \(d_0\): \(45_{10} = 101101_2\). Check by expanding: \(32 + 0 + 8 + 4 + 0 + 1 = 45\). ✓

Example 2: 2047 to hexadecimal.

\[\begin{aligned} 2047 &= 127 \times 16 + 15 && \text{digit F}\\ 127 &= 7 \times 16 + 15 && \text{digit F}\\ 7 &= 0 \times 16 + 7 && \text{digit 7 (stop)} \end{aligned}\]

So \(2047_{10} = \text{7FF}_{16}\). Check: \(7 \times 256 + 15 \times 16 + 15 = 1792 + 240 + 15 = 2047\). ✓

Example 3: \(\text{2D}_{16}\) to decimal by Horner’s rule. Start with \(v = 0\). Digit 2: \(v = 0 \times 16 + 2 = 2\). Digit D (=13): \(v = 2 \times 16 + 13 = 45\). So \(\text{2D}_{16} = 45\).

1.3.7. Alternative approach: grouping bits

Between binary and hex (or octal) there is a much faster route than going via decimal. Since one hex digit is exactly four bits, group the binary digits in fours from the right and translate each group:

\[101101_2 = \underbrace{0010}_{2}\;\underbrace{1101}_{\text{D}} = \text{2D}_{16}.\]

(The underbrace labels what each group of four bits becomes.) Going the other way, expand each hex digit into four bits: \(\text{7FF}_{16} = 0111\;1111\;1111_2\).

The other common method for decimal-to-binary is subtracting powers of two: find the largest power of two not exceeding \(n\), write a 1 there, subtract, repeat. For 45: \(32\) fits (remainder 13), 16 does not, 8 fits (remainder 5), 4 fits (remainder 1), 2 does not, 1 fits. Digits 101101 again.

1.3.8. Choosing a method

  • Binary ↔ hex or octal: always group bits. It is mechanical and nearly error-free.

  • Decimal → binary for small numbers you can see the powers of 2 in (anything under about 1000): subtract powers of two — it is the fastest mental method.

  • Decimal → any base for larger numbers, or in code: repeated division.

  • Any base → decimal: Horner’s rule, which is also how every parseInt is written.

1.3.9. Implementation

DIGITS = "0123456789ABCDEF"

def to_base(n, b):
    """Return the base-b digit string of a non-negative integer n (2 <= b <= 16)."""
    if n == 0:
        return "0"
    digits = []
    while n > 0:
        n, r = divmod(n, b)        # quotient and remainder in one step
        digits.append(DIGITS[r])   # remainders come out least-significant first
    return "".join(reversed(digits))

def from_base(s, b):
    """Inverse: evaluate a digit string in base b (Horner's rule)."""
    value = 0
    for ch in s:
        value = value * b + DIGITS.index(ch.upper())
    return value

print(to_base(45, 2), to_base(2047, 16), to_base(255, 2))
print(from_base("101101", 2), from_base("7FF", 16), int("7FF", 16))
101101 7FF 11111111
45 2047 2047

Python’s built-ins bin, hex, oct, int(s, base), and format strings such as f"{45:08b}" do the same jobs; the point of writing them yourself once is to see that they are just the two procedures above.

A leading zero that changes the number

In C, C++, Java, and JavaScript (non-strict mode), an integer literal with a leading zero is octal: 010 is eight, not ten, and 09 is an error. Zip codes and phone numbers stored as integers have been mangled this way for decades. Python 3 forbids the ambiguous form and requires 0o10. Rule of thumb: identifiers that happen to be made of digits (zip codes, account numbers) are strings, not numbers.

Computer-science connection: why hex is everywhere

Memory addresses, colour codes (#1F5FA8 is red \(\text{1F}_{16} = 31\), green \(\text{5F}_{16} = 95\), blue \(\text{A8}_{16} = 168\)), UUIDs, hashes, and machine code are all written in hex. Not because hex is meaningful to the machine — the machine only has bits — but because hex is the most compact human-readable notation that maps exactly onto bits: one byte is always two hex digits, so you can read bit patterns off at a glance. Decimal does not have this property: the decimal digits of a number do not line up with its bytes.

Base 60 is still on your wrist

The Babylonians used base 60 around 2000 BCE, with a place-value system but (for a long time) no zero symbol, so they had to infer from context whether a gap meant "nothing in this place". We still inherit their base in 60 seconds per minute, 60 minutes per hour, and 360 degrees in a circle. Sixty is convenient because it divides evenly by 2, 3, 4, 5, 6, 10, 12, 15, 20, and 30. A true zero digit, acting as a placeholder, was developed in India by about the 7th century CE and reached Europe through Arabic mathematicians — hence "Hindu–Arabic numerals".

Base explorer

Type a number and watch it displayed simultaneously in bases 2, 8, 10, and 16, with each digit’s place value shown as a stack of blocks. Click a bit to toggle it and see the decimal and hex values update; notice that toggling bit \(k\) always changes the value by exactly \(2^k\).

1.3.10. Exercises

  1. Write \(1011_2\), \(777_8\), and \(\text{FF}_{16}\) in decimal.

  2. Convert 100 to binary by repeated division, then convert your answer to hex by grouping bits.

  3. A colour is stored as 0x00FF7F. What are its red, green, and blue components in decimal?

  4. Explain, using the place-value formula, why appending a 0 to the right of a binary numeral doubles its value. What does appending a 0 do in base \(b\)?

Answers
  1. \(1011_2 = 8 + 0 + 2 + 1 = 11\). \(777_8 = 7 \cdot 64 + 7 \cdot 8 + 7 = 448 + 56 + 7 = 511\). \(\text{FF}_{16} = 15 \cdot 16 + 15 = 255\).

  2. \(100 = 50 \cdot 2 + 0\), \(50 = 25 \cdot 2 + 0\), \(25 = 12 \cdot 2 + 1\), \(12 = 6 \cdot 2 + 0\), \(6 = 3 \cdot 2 + 0\), \(3 = 1 \cdot 2 + 1\), \(1 = 0 \cdot 2 + 1\). Reading remainders upward: \(1100100_2\). Grouping from the right: \(0110\;0100 = \text{64}_{16}\). Check: \(6 \cdot 16 + 4 = 100\). ✓

  3. Red \(\text{00} = 0\), green \(\text{FF} = 255\), blue \(\text{7F} = 7 \cdot 16 + 15 = 127\). (A spring green.)

  4. Appending a digit moves every existing digit up one position, multiplying its place value by the base, and puts 0 in the units place. So in base 2 the value doubles; in base \(b\) it is multiplied by \(b\). This is why a left shift x << 1 multiplies by 2.

US curriculum

Base-ten place value is a core elementary topic (grades 1–5, Common Core NBT strand). Other bases are rarely taught in standard US courses today; they appear in enrichment, in some Pre-Algebra texts, and in AP Computer Science Principles, which covers binary explicitly.

1.4. The four operations and their laws

1.4.1. The problem

How do you work out \(17 \times 25\) in your head? Many people do something like "\(17 \times 100 = 1700\), divide by 4, that’s 425." Or "\(17 \times 25 = 10 \times 25 + 7 \times 25 = 250 + 175 = 425\)." Both are correct. But why are you allowed to do that? Neither is the long-multiplication algorithm you were taught.

The answer is a handful of laws that addition and multiplication obey. They look so obvious that it is easy to skip past them — but they are the entire rulebook of algebra. Every time you "simplify", "expand", "factor", "collect like terms", or "move something to the other side", you are applying one of these laws. Knowing them by name means you can justify every step you take, and spot the step that is not justified.

1.4.2. Vocabulary and notation

Sum, difference, product, quotient

The result of an addition is a sum; its inputs are terms (or addends). The result of a subtraction is a difference. The result of a multiplication is a product; its inputs are factors. The result of a division is a quotient: in \(a \div b\), \(a\) is the dividend and \(b\) the divisor. Multiplication may be written \(a \times b\), \(a \cdot b\), or simply \(ab\) when at least one factor is a letter.

Commutative, associative, distributive

An operation is commutative if order of the inputs does not matter: \(a + b = b + a\), \(ab = ba\). It is associative if grouping does not matter: \((a + b) + c = a + (b + c)\), \((ab)c = a(bc)\). Multiplication distributes over addition: \(a(b + c) = ab + ac\). Mnemonic: commute = move around; associate = who you group with; distribute = hand out to each.

Identity and inverse

An identity element for an operation leaves things unchanged: \(a + 0 = a\) (0 is the additive identity), \(a \times 1 = a\) (1 is the multiplicative identity). An inverse undoes: \(-a\) is the additive inverse (or opposite) of \(a\) because \(a + (-a) = 0\); \(\tfrac{1}{a}\) is the multiplicative inverse (or reciprocal) of \(a \neq 0\) because \(a \cdot \tfrac{1}{a} = 1\).

Collected in one place, for all real numbers \(a, b, c\):

\[\begin{array}{lll} \textbf{Law} & \textbf{Addition} & \textbf{Multiplication} \\[4pt] \text{Commutative} & a + b = b + a & ab = ba \\ \text{Associative} & (a + b) + c = a + (b + c) & (ab)c = a(bc) \\ \text{Identity} & a + 0 = a & a \cdot 1 = a \\ \text{Inverse} & a + (-a) = 0 & a \cdot \tfrac{1}{a} = 1 \quad (a \neq 0) \\[4pt] \text{Distributive} & \text{(links } + \text{ and } \times\text{)} & a(b + c) = ab + ac \end{array}\]

1.4.3. Intuition

The distributive law is the one that does the heavy lifting, and it has a lovely picture: a rectangle of height \(a\) and width \(b + c\) has the same area as two rectangles of widths \(b\) and \(c\) placed side by side.

A 3 by 8 rectangle split into 3 by 5 and 3 by 3 parts
Figure 5. The distributive law as area: \(a(b+c)\) is the whole rectangle; \(ab + ac\) is the sum of its two parts.

Commutativity of multiplication has a picture too: a grid of 3 rows of 5 dots is the same grid as 5 columns of 3 dots, just turned sideways.

1.4.4. What about subtraction and division?

Subtraction and division are not commutative (\(5 - 3 \neq 3 - 5\), \(6 \div 2 \neq 2 \div 6\)) and not associative:

\[(8 - 4) - 2 = 2 \quad\text{but}\quad 8 - (4 - 2) = 6 .\]

The clean way to think about this — and the way algebra will treat it — is that subtraction and division are not really separate operations. They are addition and multiplication by an inverse:

\[a - b = a + (-b), \qquad a \div b = a \cdot \frac{1}{b}.\]

Rewrite every subtraction as "add the opposite" and every division as "multiply by the reciprocal", and you are back in the world where everything commutes and associates. \(8 - 4 - 2\) becomes \(8 + (-4) + (-2)\), which you can group and reorder however you like.

1.4.5. Why these laws matter later

When you solve \(3x + 5 = 20\) in Chapter 5, the steps are:

\[\begin{aligned} 3x + 5 &= 20 \\ 3x + 5 + (-5) &= 20 + (-5) && \text{(add the additive inverse of 5 to both sides)} \\ 3x + 0 &= 15 && \text{(inverse: } 5 + (-5) = 0\text{)} \\ 3x &= 15 && \text{(identity: } 3x + 0 = 3x\text{)} \\ \tfrac{1}{3}(3x) &= \tfrac{1}{3} \cdot 15 && \text{(multiply both sides by the reciprocal of 3)} \\ (\tfrac{1}{3} \cdot 3)x &= 5 && \text{(associative law)} \\ 1 \cdot x &= 5 && \text{(inverse)} \\ x &= 5 && \text{(identity)} \end{aligned}\]

You would never write it out this laboriously in practice. But every "move it to the other side" is secretly this chain. When you meet matrices (Chapter 27), multiplication will stop being commutative (\(AB \neq BA\) in general), and suddenly it matters a great deal which laws you were relying on. Mathematicians give names to structures by which laws they obey: a set with \(+\) and \(\times\) obeying all of the laws above is called a field. \(\mathbb{Q}\) and \(\mathbb{R}\) are fields; \(\mathbb{Z}\) is not (2 has no integer reciprocal).

1.4.6. Worked example: mental arithmetic as applied algebra

Compute \(98 \times 7\) mentally, justifying each step.

\[\begin{aligned} 98 \times 7 &= (100 - 2) \times 7 && \text{(rewrite 98)} \\ &= 100 \times 7 - 2 \times 7 && \text{(distributive law)} \\ &= 700 - 14 \\ &= 686 . \end{aligned}\]

Compute \(4 \times 37 \times 25\).

\[\begin{aligned} 4 \times 37 \times 25 &= 37 \times 4 \times 25 && \text{(commutative law)} \\ &= 37 \times (4 \times 25) && \text{(associative law)} \\ &= 37 \times 100 = 3700 . \end{aligned}\]

The second example shows why these laws are really about freedom: you are allowed to choose the order that makes the work easy.

1.4.7. Where you’d use this

  • Shopping and tipping. Four items at £2.99: \(4 \times 2.99 = 4 \times (3 - 0.01) = 12 - 0.04 = 11.96\) (distributive law). A 15% tip on a $46 bill: 10% is $4.60 and 5% is half of that, $2.30, so the tip is $6.90, because \(0.15 \times 46 = (0.10 + 0.05) \times 46\).

  • Mechanics. A constant force of 30 N pushes a crate 4 m and then a further 6 m. The work done is \(30 \times 4 + 30 \times 6 = 30 \times (4 + 6) = 300\) J. Factoring out the common force is the distributive law, and it is why physicists can add displacements first and multiply once.

  • Compilers and databases. An optimising compiler rewrites x*8 + x*2 as x*10 (distributive law) and (x*4)*25 as x*100 (associative law). A database evaluating SUM(price * 1.2) may compute 1.2 * SUM(price) instead: one multiplication instead of a million. Both rewrites are legal for integers and real numbers, and only approximately legal for floats, which is exactly the subject of the sidebar below.

1.4.8. Division by zero

Why you cannot divide by zero

"\(a \div b = c\)" means "\(c\) is the number with \(c \times b = a\)". Try \(6 \div 0 = c\): we need \(c \times 0 = 6\), but anything times 0 is 0, so no \(c\) works. Try \(0 \div 0 = c\): we need \(c \times 0 = 0\), and every \(c\) works, so there is no single answer. Either way, division by zero has no sensible value, so it is left undefined. Zero is the one real number with no reciprocal. Many algebra "proofs" that \(1 = 2\) hide a division by an expression that equals zero.

Computer-science connection: floating-point addition is not associative

The laws above hold for real numbers. They do not all hold for the floating-point numbers in your computer, because every operation rounds its result:

>>> (0.1 + 0.2) + 0.3
0.6000000000000001
>>> 0.1 + (0.2 + 0.3)
0.6
>>> 1e16 + 1 - 1e16
0.0

This matters more than it looks. A parallel sum (map-reduce, GPU reduction, multithreaded sum) adds numbers in an order that depends on scheduling, so the same data can give slightly different totals on different runs. Compilers are forbidden to reorder floating-point arithmetic unless you pass flags like -ffast-math, precisely because associativity fails. Conversely, string concatenation is associative but not commutative, and integer addition in a fixed-width register is associative and commutative even when it overflows (Section 1.9) — which is one reason wraparound arithmetic is so convenient for hardware.

Why "distributive"?

The names "commutative" and "distributive" were coined by the French mathematician François-Joseph Servois in 1814; "associative" came from William Rowan Hamilton in the 1840s, who needed the word because he had just invented the quaternions, a number system in which multiplication is associative but not commutative. Until people built systems where the laws failed, nobody had needed names for them.

Laws as tiles

Drag the dividing line in a \(a \times (b + c)\) rectangle and watch the two partial areas and their sum update. Then switch to "floating-point mode": generate a random list of 1,000 floats, sum it in forward, reverse, and shuffled order, and display the differing totals.

1.4.9. Exercises

  1. Name the law used in each step: (a) \(3 + x = x + 3\); (b) \(2(x + 5) = 2x + 10\); (c) \((5 \cdot x) \cdot 2 = 5 \cdot (x \cdot 2)\).

  2. Compute \(999 \times 6\) and \(25 \times 48\) mentally, writing down the law behind each step.

  3. Show by example that division is not associative.

  4. Expand \((a + b)(c + d)\) using only the distributive law (twice), and draw the matching area picture.

Answers
  1. (a) Commutative law of addition. (b) Distributive law. (c) Associative law of multiplication.

  2. \(999 \times 6 = (1000 - 1) \times 6 = 6000 - 6 = 5994\) (distributive). \(25 \times 48 = 25 \times (4 \times 12) = (25 \times 4) \times 12 = 100 \times 12 = 1200\) (associative).

  3. \((16 \div 4) \div 2 = 4 \div 2 = 2\), but \(16 \div (4 \div 2) = 16 \div 2 = 8\).

  4. Treat \((a + b)\) as a single number and distribute it over \(c + d\): \((a + b)(c + d) = (a + b)c + (a + b)d\). Distribute again (with commutativity to put the factor on the left): \(= ac + bc + ad + bd\). The picture is a rectangle of width \(a + b\) and height \(c + d\) cut into four smaller rectangles. This is the origin of "FOIL", which Chapter 7 generalises.

US curriculum

The properties of operations are named and used from grade 3 onward (Common Core 3.OA.5), and formalised in Pre-Algebra and Algebra I, where students justify equation-solving steps by citing them.

1.5. Negative numbers

1.5.1. The problem

A bank account holds $40 and you write a cheque for $70. The balance is \(-30\). The temperature is \(-5^\circ\text{C}\) and falls by 8 degrees: it is now \(-13^\circ\text{C}\). These are easy. But what is \((-3) \times (-4)\)? School says 12 — "two negatives make a positive" — but if you were never told why, the rule feels arbitrary, and arbitrary rules are the ones that get misremembered.

1.5.2. Intuition: adding and subtracting on the line

On the number line, a negative number is a step to the left.

  • \(5 + (-8)\): start at 5, step 8 left, land on \(-3\).

  • \(5 - 8\): the same thing, since \(a - b = a + (-b)\).

  • \(5 - (-8)\): "subtracting a step to the left" — undoing a debt — is a step to the right: \(5 - (-8) = 5 + 8 = 13\).

The last one is just the observation that the opposite of the opposite is the original: \(-(-8) = 8\), because 8 is the number that, added to \(-8\), gives 0.

Number line from -4 to 14 with an arc from 5 back to -3 labelled 5 + (-8) = -3 and an arc from 5 forward to 13 labelled 5 - (-8) = 13
Figure 6. Signed numbers as hops: adding \(-8\) steps 8 left; subtracting \(-8\) undoes a step left, so it steps 8 right.

1.5.3. Why negative times negative is positive

There are two good arguments. The first is a pattern argument that convinces; the second is an algebraic argument that proves.

Pattern. Multiply \(-2\) by a factor that decreases by 1 each line:

\[\begin{aligned} 3 \times (-2) &= -6 \\ 2 \times (-2) &= -4 \\ 1 \times (-2) &= -2 \\ 0 \times (-2) &= 0 \\ (-1) \times (-2) &= \;? \\ (-2) \times (-2) &= \;? \end{aligned}\]

The first four lines are uncontroversial (\(3 \times (-2)\) is three debts of 2). Each time the first factor drops by 1, the product rises by 2. If the pattern continues — and anything else would put a kink in a straight line — then \((-1) \times (-2) = 2\) and \((-2) \times (-2) = 4\).

Points (x, -2x) for x from -3 to 3 lying on a straight line
Figure 7. Multiplying by \(-2\): the products lie on a straight line. Continuing it to the left forces negative × negative to be positive.

Proof from the laws. The pattern is persuasive, but here is the real reason: if we want the distributive law to keep working for negative numbers, we have no choice. We use only the laws from Section 1.4.

First, anything times zero is zero. For any number \(a\):

\[\begin{aligned} a \cdot 0 &= a \cdot (0 + 0) && \text{(0 is the additive identity: } 0 + 0 = 0\text{)} \\ a \cdot 0 &= a \cdot 0 + a \cdot 0 && \text{(distributive law)} \\ 0 &= a \cdot 0 && \text{(add } -(a \cdot 0) \text{ to both sides)} \end{aligned}\]

Now the main event. Start from something we know is zero and expand it two ways:

\[\begin{aligned} (-1) \cdot \big(1 + (-1)\big) &= (-1) \cdot 0 = 0 && \text{(since } 1 + (-1) = 0\text{)} \\ (-1) \cdot \big(1 + (-1)\big) &= (-1)\cdot 1 + (-1)(-1) && \text{(distributive law)} \\ &= -1 + (-1)(-1) . && \text{(1 is the multiplicative identity)} \end{aligned}\]

Putting the two lines together, \(-1 + (-1)(-1) = 0\). So \((-1)(-1)\) is the number that, added to \(-1\), gives zero. That number is 1. Hence

\[(-1)(-1) = 1 .\]

The general case follows by writing \(-a = (-1)a\): \((-a)(-b) = (-1)(-1)ab = ab\).

The moral: "negative times negative is positive" is not a rule someone chose. It is forced by the distributive law. Any other answer would break the arithmetic that lets you expand brackets.

1.5.4. The method

Example 4. Procedure — signs in multiplication and division

Input: a product or quotient of signed numbers.

Steps:

  1. Ignore the signs and compute with the sizes (absolute values).

  2. Count the negative factors (dividing by a negative counts as a negative factor).

  3. If the count is even, the result is positive; if odd, negative.

Output: the signed result.

Worked example. \(\dfrac{(-6) \times 4 \times (-5)}{-3}\). Sizes: \(6 \times 4 \times 5 / 3 = 120 / 3 = 40\). Negatives: \(-6\), \(-5\), \(-3\) — three, odd. Result: \(-40\).

1.5.5. Where you’d use this

  • Everyday. The temperature rises from \(-5^\circ\text{C}\) overnight to \(3^\circ\text{C}\) at noon: the change is \(3 - (-5) = 8\) degrees. A golfer at \(-3\) (three under par) who scores \(+2\) on the next hole is at \(-1\).

  • Physics. In mechanics a sign encodes a direction. Take "up" as positive and throw a ball upward at 12 m/s; gravity gives an acceleration of \(-9.8\ \text{m/s}^2\). After 2 seconds the velocity is \(12 + (-9.8)(2) = -7.6\) m/s: the negative sign tells you the ball is now falling. Charge, current direction, and profit/loss work the same way.

  • Computing. Screen coordinates usually have \(y\) increasing downward, so "move up 10 pixels" is \(\Delta y = -10\). Python’s a[-1] is the last element of a list, a[-2] the one before. File seeks, timezone offsets (UTC \(-5\)), and version diffs are all signed quantities.

1.5.6. Failure modes

\(-3^2\) is not \((-3)^2\)

By the standard convention (Section 1.6), exponents bind more tightly than the leading minus sign. So \(-3^2\) means \(-(3^2) = -9\), while \((-3)^2 = 9\). Python agrees: -3**2 is -9. Spreadsheets (Excel, Google Sheets) disagree and evaluate =-3^2 as 9. When the sign matters, add brackets.

Two minus signs that mean different things

The symbol "−" does two jobs. In \(7 - 3\) it is binary subtraction (two inputs). In \(-3\) or \(-x\) it is unary negation ("the opposite of"). \(-x\) is not necessarily a negative number: if \(x = -5\) then \(-x = 5\). Read \(-x\) as "the opposite of \(x\)", never as "negative \(x\)", and many sign errors disappear.

A latecomer

Negative numbers were used routinely in China (red rods for positive, black for negative) and in India by the 7th century, where Brahmagupta gave the sign rules explicitly in terms of "fortunes" and "debts". European mathematicians resisted them for over a thousand years longer: as late as the 18th century, some respected authors called them "absurd" or "fictitious". Accountants, who had been using red ink for debts all along, were ahead of the mathematicians.

1.5.7. Exercises

  1. Compute: (a) \(-7 + 12\); (b) \(-7 - 12\); (c) \(-7 - (-12)\); (d) \((-7)(-12)\).

  2. Compute \((-1)^{5}\), \((-1)^{6}\), and \((-2)^3 \times (-1)^2\).

  3. Using the same style as the proof above, show that \((-1) \cdot a = -a\) for any \(a\). (Hint: show \(a + (-1)a = 0\).)

Answers
  1. (a) 5. (b) \(-19\). (c) \(-7 + 12 = 5\). (d) 84.

  2. Five negative factors (odd): \(-1\). Six (even): \(1\). \((-2)^3 = -8\), \((-1)^2 = 1\), product \(-8\).

  3. \(a + (-1)a = 1 \cdot a + (-1)a = (1 + (-1))a = 0 \cdot a = 0\) (identity, distributive, inverse, and the "times zero" fact). So \((-1)a\) is a number which added to \(a\) gives 0 — by definition, that is \(-a\).

US curriculum

Operations with negative numbers (integers and rational numbers) are a grade 6–7 topic (Common Core 6.NS, 7.NS). Grade 7 standards explicitly ask students to understand that \((-1)(-1) = 1\) follows from the distributive property.

1.6. Order of operations

1.6.1. The problem

Every few months an expression such as

\[8 \div 2(2 + 2)\]

goes viral, with half the internet insisting the answer is 16 and the other half insisting it is 1. Who is right? The uncomfortable truth is that the question has no mathematical answer. Order of operations is a convention — an agreement about how to read a string of symbols — and this expression sits exactly where the conventions are ambiguous.

1.6.2. Intuition

A string like \(2 + 3 \times 4\) could mean \((2 + 3) \times 4 = 20\) or \(2 + (3 \times 4) = 14\). Arithmetic itself does not care; it is the notation that needs a rule. The convention that multiplication goes first was adopted because it makes the most common expressions short: polynomials like \(3x^2 + 2x + 1\) would otherwise need brackets everywhere.

1.6.3. The convention

Order of operations (precedence)

Precedence says which operations are done first. The standard order is:

  1. Brackets (parentheses) — innermost first;

  2. Exponents (powers and roots);

  3. Multiplication and division — equal rank, left to right;

  4. Addition and subtraction — equal rank, left to right.

US mnemonic: PEMDAS ("Please Excuse My Dear Aunt Sally"). UK: BODMAS or BIDMAS (Brackets, Orders/Indices, Division, Multiplication, Addition, Subtraction). They are the same rule.

Associativity of operators (left/right)

When operators of equal rank appear in a row, operator associativity decides grouping. Subtraction and division are left-associative: \(a - b - c = (a - b) - c\). Exponentiation is right-associative: \(a^{b^c} = a^{(b^c)}\), so \(2^{3^2} = 2^9 = 512\), not \(8^2 = 64\). (This is a different meaning of "associative" from the law in Section 1.4: here it is a parsing rule for notation.)

1.6.4. The method

Example 5. Procedure — evaluate an arithmetic expression by hand

Input: an expression with numbers, brackets, and operators.

Steps:

  1. Find an innermost pair of brackets and evaluate inside it using steps 2–4. Replace the bracket by its value. Repeat until no brackets remain.

  2. Evaluate all exponents, right to left when stacked.

  3. Sweep left to right, performing each multiplication or division as you meet it.

  4. Sweep left to right, performing each addition or subtraction as you meet it.

Output: a single number.

1.6.5. Worked example

Evaluate \(20 - 3 \times (4 - 1)^2 \div 9 + 2\).

\[\begin{aligned} 20 - 3 \times (4 - 1)^2 \div 9 + 2 &= 20 - 3 \times 3^2 \div 9 + 2 && \text{(brackets)} \\ &= 20 - 3 \times 9 \div 9 + 2 && \text{(exponent)} \\ &= 20 - 27 \div 9 + 2 && \text{(multiply: leftmost of } \times, \div\text{)} \\ &= 20 - 3 + 2 && \text{(divide)} \\ &= 17 + 2 && \text{(subtract: leftmost of } +, -\text{)} \\ &= 19 . && \text{(add)} \end{aligned}\]

A common mistake is to do all additions before subtractions: \(20 - (3 + 2) = 15\). Wrong — they have equal rank and go left to right.

1.6.6. Alternative approach: the expression tree

Precedence rules are really instructions for building a tree: each operator is a node whose children are its operands. \(2 + 3 \times 4\) is a \(+\) node with children 2 and (a \(\times\) node with children 3 and 4). Evaluate the tree from the leaves upward. Once you see expressions as trees, precedence stops being a list to memorise and becomes a question of "which operator is at the root?" Chapter 4 develops this view.

1.6.7. Back to the viral problem

In \(8 \div 2(2 + 2)\), strict PEMDAS gives \(8 \div 2 \times 4 = 4 \times 4 = 16\). But many mathematicians, physicists, and textbooks treat implied multiplication (juxtaposition, writing \(2(\ldots)\) or \(2x\) with no symbol) as binding more tightly than an explicit \(\div\), so \(1/2x\) means \(1/(2x)\). Under that reading the answer is \(8 \div 8 = 1\). Neither convention is wrong; the expression is simply badly written. Real mathematics avoids \(\div\) entirely after primary school and uses fraction bars, which make grouping visible: \(\dfrac{8}{2}(2 + 2)\) or \(\dfrac{8}{2(2 + 2)}\). Try it: Parse 8÷2(2+2) five ways.

Choosing how to write it

If an expression’s meaning depends on a precedence rule that a reasonable reader might not share, add brackets. This applies doubly to code. Brackets are free; misreadings are not.

1.6.8. Where you’d use this

  • Spreadsheets. To average three test scores in cells holding 70, 80, and 90, typing =A1+B1+C1/3 gives \(70 + 80 + 90/3 = 180\), not 80. The fix is =(A1+B1+C1)/3. This exact bug turns up in real gradebooks and budgets. Try it: See the gradebook bug’s tree.

  • Physics formulas. Kinetic energy is \(\tfrac{1}{2}mv^2\): the exponent applies to \(v\) alone. For a 2 kg ball at 3 m/s that is \(\tfrac{1}{2} \times 2 \times 3^2 = 9\) J. Squaring \(mv\) instead gives \(\tfrac{1}{2}(2 \times 3)^2 = 18\) J, which is twice as large and wrong.

  • Finance. Compound interest \(P(1 + r)^n\) needs its brackets: the exponent must apply to the whole growth factor \(1 + r\), not to \(r\) alone (Chapter 3).

Computer-science connection: operator precedence in languages

Every language has a precedence table, and they differ in exactly the places where human conventions are fuzzy:

  • Python: -2**2 == -4 (power binds tighter than unary minus), 2**3**2 == 512 (right-associative), -7 // 2 == -4 (floor division rounds toward \(-\infty\)).

  • C, C++, Java: -7 / 2 == -3 (truncates toward zero). And the bitwise operators &, |, ^ have lower precedence than ==, a historical accident Dennis Ritchie later regretted: x & 1 == 0 parses as x & (1 == 0).

  • In C, ^ is XOR, not power — 2 ^ 3 is 1.

  • Excel: =-3^2 is 9 (unary minus first), the opposite of Python.

Parsers implement precedence with techniques such as recursive descent (one function per precedence level) or Dijkstra’s shunting-yard algorithm, which converts infix notation to Reverse Polish Notation — postfix, as on old HP calculators: 3 4 2 * +. RPN needs no precedence rules and no brackets at all, because the order is explicit.

Precedence playground

Type an expression and see its parse tree drawn, with a selector for convention: "strict PEMDAS", "implied multiplication binds tighter", "Python", "C", "Excel". Watch the tree — and the answer — change for \(8 \div 2(2 + 2)\) and \(-3^2\).

1.6.9. Exercises

  1. Evaluate \(6 + 18 \div 3 \times 2 - 4\).

  2. Evaluate \((2 + 3)^2 - 2 + 3^2\).

  3. Without brackets, \(2 \times 3 + 4^2 - 1 = 21\). Insert one pair of brackets to make the result (a) 97, (b) 36, (c) 10.

  4. What does Python print for 2 ** -1, -2 ** 0.5 and (-8) // 3? Explain each.

Answers
  1. \(18 \div 3 = 6\), then \(6 \times 2 = 12\); so \(6 + 12 - 4 = 14\).

  2. \(5^2 - 2 + 9 = 25 - 2 + 9 = 32\).

  3. (a) \(2 \times (3 + 4)^2 - 1 = 2 \times 49 - 1 = 97\). (b) \(2 \times (3 + 4^2 - 1) = 2 \times 18 = 36\). (c) \(2 \times 3 + 4^{(2 - 1)} = 6 + 4 = 10\) (or \((2 \times 3 + 4)^{(2-1)} = 10\)). Brackets change which operation sits at the root of the expression tree; the same symbols can produce very different values.

  4. 0.5: \(2^{-1} = \tfrac{1}{2}\) (Chapter 3). -1.4142135623730951: parsed as \(-(2^{0.5})\). -3: floor of \(-2.666\ldots\) is \(-3\) (Python floors toward \(-\infty\)).

US curriculum

Order of operations is taught in grades 5–6 (Common Core 5.OA.1, 6.EE.2c) with the PEMDAS mnemonic, and used constantly in Pre-Algebra and Algebra I.

1.7. Absolute value

1.7.1. The problem

Two sensors read \(-3.2\) and \(1.8\). How far apart are their readings? A stock moved by \(-4\%\); how big was the move? We often need the size of a number without its sign, or the distance between two numbers without caring which is larger.

1.7.2. Intuition and definition

The absolute value of a number is its distance from zero on the number line. Distance is never negative.

Absolute value

The absolute value (or magnitude, or modulus) of \(x\), written \(|x|\), is its distance from 0:

\[|x| = \begin{cases} x & \text{if } x \ge 0, \\ -x & \text{if } x < 0. \end{cases}\]

The large brace introduces a piecewise definition: read each line as "this value, under this condition". So \(|5| = 5\), \(|-5| = -(-5) = 5\), \(|0| = 0\). The distance between \(a\) and \(b\) on the line is \(|a - b|\).

The second line of the definition, \(-x\) when \(x < 0\), trips people up: it looks like it makes things negative. But when \(x\) is negative, \(-x\) (the opposite of \(x\)) is positive. This is the unary-minus point from Section 1.5 again.

Number line showing |-4| = 4, |4| = 4 and |2 - (-3)| = 5 as segment lengths
Figure 8. Absolute value as distance: from zero, or between two points.

1.7.3. Properties

For all real \(a, b\):

\[\begin{aligned} |a| &\ge 0, \text{ and } |a| = 0 \text{ only when } a = 0 \\ |ab| &= |a|\,|b| \\ |a + b| &\le |a| + |b| \qquad \text{(the triangle inequality)} \end{aligned}\]

The triangle inequality says a detour is never shorter than the direct route. Equality holds when \(a\) and \(b\) have the same sign; when they have opposite signs they partly cancel. It sounds modest but it is one of the most-used inequalities in all of analysis, and it reappears for vectors in Chapter 26.

1.7.4. Worked example

The two sensors: \(|(-3.2) - 1.8| = |-5| = 5\). Equivalently \(|1.8 - (-3.2)| = |5| = 5\): order does not matter, which is exactly why we use absolute value for distance.

Which numbers \(x\) satisfy \(|x - 2| < 3\)? Read it as "the distance from \(x\) to 2 is less than 3". So \(x\) is within 3 of 2: \(-1 < x < 5\). Translating absolute-value inequalities into distance statements is far more reliable than manipulating them symbolically; Chapter 5 returns to this.

1.7.5. Where you’d use this

  • Manufacturing tolerances. A bolt is specified as \(10.00 \pm 0.05\) mm. A bolt of diameter \(d\) passes inspection when \(|d - 10.00| \le 0.05\): 9.97 mm passes (off by 0.03), 10.06 mm fails (off by 0.06). The same test checks a medicine dose, a thermostat, or a bathroom scale.

  • Measuring error. A weather model’s temperature forecasts are off by \(-2\), \(+3\), and \(-1\) degrees. The plain average error is 0, which suggests a perfect forecast. The mean absolute error is \((2 + 3 + 1)/3 = 2\) degrees, which is the honest answer. Machine-learning models are trained against error measures of exactly this form (Chapter 31).

  • Games and robots on a grid. A piece that moves only along rows and columns needs \(|x_1 - x_2| + |y_1 - y_2|\) moves to get from one square to another: from \((2, 7)\) to \((5, 3)\) that is \(3 + 4 = 7\). This Manhattan distance is the standard heuristic in A* path-finding on grid maps.

Computer-science connection: abs can overflow

Testing floating-point results for equality is almost always wrong (see the associativity sidebar). The standard replacement is a tolerance: abs(x - y) < eps, which is literally "the distance between \(x\) and \(y\) is less than \(\varepsilon\)". Python provides math.isclose, which combines an absolute and a relative tolerance.

A subtler trap: in a 32-bit signed integer type, abs(INT_MIN) is undefined behaviour in C and returns INT_MIN itself (a negative number!) in Java. The reason is that \(-2^{31}\) is representable but \(+2^{31}\) is not — see Section 1.9. "The absolute value is non-negative" is a theorem about \(\mathbb{Z}\), not about int.

US curriculum

Absolute value as distance from zero is introduced in grade 6 (Common Core 6.NS.7). Absolute-value equations and inequalities appear in Algebra I, and absolute-value functions and their graphs in Algebra I/II.

1.8. Divisibility, primes, and factorisation

1.8.1. The problem

You need to arrange 360 chairs in a rectangular grid. What shapes are possible? You want to schedule something every 12 days and something else every 18 days; when do they coincide? A hash table works best when its size has no small factors in common with patterns in the keys. All of these are questions about how whole numbers break into products — about divisibility.

This section is a working toolkit. The deep theory (modular arithmetic, the Euclidean algorithm, cryptography) is Chapter 23.

1.8.2. Vocabulary and notation

Division with remainder

For integers \(a\) and \(b > 0\) there are unique integers \(q\) (the quotient) and \(r\) (the remainder) with

\[a = qb + r, \qquad 0 \le r < b .\]

Example: \(47 = 6 \times 7 + 5\), so dividing 47 by 7 gives quotient 6, remainder 5. In code, q, r = divmod(a, b), or a // b and a % b.

Divides, factor, multiple

\(b\) divides \(a\), written \(b \mid a\) (a vertical bar, read "b divides a"), if the remainder is 0, i.e. \(a = qb\) for some integer \(q\). Then \(b\) is a factor (or divisor) of \(a\), and \(a\) is a multiple of \(b\). So \(3 \mid 12\) and \(5 \nmid 12\). Do not confuse \(b \mid a\) (a true/false statement) with \(b / a\) (a number).

Prime and composite

A prime is a natural number greater than 1 whose only positive divisors are 1 and itself: \(2, 3, 5, 7, 11, 13, \ldots\). A natural number greater than 1 that is not prime is composite: it can be written as a product of two smaller natural numbers. 1 is neither prime nor composite. 2 is the only even prime.

1.8.3. The fundamental theorem of arithmetic

Every integer greater than 1 can be written as a product of primes, and this product is unique apart from the order of the factors:

\[360 = 2 \times 2 \times 2 \times 3 \times 3 \times 5 = 2^3 \cdot 3^2 \cdot 5 .\]

Primes are the atoms of multiplication; the prime factorisation is a number’s chemical formula. Existence is easy to see: if a number is not prime, split it into two smaller factors, and keep splitting until every piece is prime. Uniqueness is subtler and is proved in Chapter 23.

Why 1 is not prime

If 1 counted as prime, factorisations would not be unique: \(6 = 2 \times 3 = 1 \times 2 \times 3 = 1 \times 1 \times 2 \times 3 \ldots\). Excluding 1 is not a deep fact about 1 — it is a definition chosen so that the fundamental theorem can be stated cleanly. Until the late 19th century, plenty of mathematicians did list 1 as a prime.

1.8.4. Divisibility tests

Shortcuts for spotting small factors, with the reason each works:

  • 2, 5, 10: look at the last digit. Since \(10 = 2 \times 5\), every digit except the last contributes a multiple of 10, so only the units digit decides.

  • 4: last two digits form a multiple of 4 (because 100 is a multiple of 4).

  • 3 and 9: the digit sum is a multiple of 3 (or 9). Why: \(10 = 9 + 1\), \(100 = 99 + 1\), \(1000 = 999 + 1\), … each power of 10 is "a multiple of 9, plus 1". So

    \[\begin{aligned} 2475 &= 2 \cdot 1000 + 4 \cdot 100 + 7 \cdot 10 + 5 \\ &= 2(999 + 1) + 4(99 + 1) + 7(9 + 1) + 5 \\ &= \underbrace{(2 \cdot 999 + 4 \cdot 99 + 7 \cdot 9)}_{\text{multiple of 9}} + (2 + 4 + 7 + 5) . \end{aligned}\]

    The number and its digit sum (here 18) leave the same remainder on division by 9 — and also by 3. Since 18 is a multiple of 9, so is 2475 (\(= 9 \times 275\)).

  • 11: alternating digit sum. Since \(10 = 11 - 1\), powers of 10 alternate between "multiple of 11 plus 1" and "multiple of 11 minus 1". For 9273: \(3 - 7 + 2 - 9 = -11\), a multiple of 11, so \(11 \mid 9273\) (\(= 11 \times 843\)).

1.8.5. The method: trial division

Example 6. Procedure — prime factorisation by trial division

Input: an integer \(n \ge 2\).

Steps:

  1. Set the trial divisor \(d = 2\).

  2. While \(d \times d \le n\):

    1. While \(d \mid n\): record \(d\) as a factor and replace \(n\) by \(n / d\).

    2. Increase \(d\) by 1.

  3. If \(n > 1\) now, record \(n\) — it is prime.

Output: the list of prime factors of the original number, with repetition, in increasing order.

Two details make this correct and fast:

  • We never record a composite \(d\). By the time we try, say, \(d = 6\), all factors 2 and 3 have already been divided out, so 6 cannot divide what remains.

  • We can stop at \(\sqrt{n}\). If \(n = ab\) with both factors bigger than \(\sqrt{n}\), then \(ab > \sqrt{n}\sqrt{n} = n\), which is impossible. So any composite \(n\) has a factor no larger than \(\sqrt{n}\). If no \(d\) up to \(\sqrt{n}\) divides \(n\), it is prime. (The test \(d \times d \le n\) is this condition without computing a square root.)

1.8.6. Worked examples

360. Each split in the tree below records one division.

Factor tree of 360 splitting into 2, 2, 2, 3, 3, 5
Figure 9. A factor tree for 360. The leaves (orange) are the prime factors.

By trial division: \(360 / 2 = 180\), \(180 / 2 = 90\), \(90 / 2 = 45\); 2 no longer divides 45. Try 3: \(45 / 3 = 15\), \(15 / 3 = 5\); 3 no longer divides 5. Try 4: \(4 \times 4 = 16 > 5\), stop. Remaining \(5 > 1\) is prime. So \(360 = 2^3 \cdot 3^2 \cdot 5\).

97. \(\sqrt{97} \approx 9.85\), so only divisors 2 through 9 need checking. 97 is odd (not 2), digit sum 16 (not 3), does not end in 0 or 5 (not 5), and \(97 = 13 \times 7 + 6\) (not 7). (4, 6, 8, 9 cannot divide it if 2 and 3 do not.) So 97 is prime. Try it: Why 97 is prime.

1001. \(1001 = 7 \times 143 = 7 \times 11 \times 13\). (The alternating digit sum \(1 - 0 + 0 - 1 = 0\) would have flagged 11 immediately.)

def factorise(n):
    """Return the prime factors of n >= 2 in ascending order, with repetition."""
    factors = []
    d = 2
    while d * d <= n:            # only need to try divisors up to sqrt(n)
        while n % d == 0:
            factors.append(d)
            n //= d
        d += 1
    if n > 1:                    # whatever is left is itself prime
        factors.append(n)
    return factors

print(factorise(360))
print(factorise(1001))
print(factorise(97))
print(factorise(2**10 * 3 * 1_000_003))
[2, 2, 2, 3, 3, 5]
[7, 11, 13]
[97]
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 1000003]

1.8.7. Choosing a method and its limits

For numbers up to a few million, trial division is instant and is the right tool. Its cost grows like \(\sqrt{n}\) steps: a 20-digit number may need \(10^{10}\) trial divisions, and a 600-digit number is utterly beyond reach. For testing whether a large number is prime (without finding its factors) there are fast probabilistic tests (Miller–Rabin) that you will meet in Chapter 23. For factorising large numbers, no fast method is known — and that is not a gap in this book but a gap in human knowledge on which much of internet security rests.

1.8.8. Where you’d use this

Two quantities fall straight out of factorisations. The least common multiple (LCM) takes each prime to the highest power found in either number; the greatest common divisor (GCD) takes each prime to the lowest power. (Chapter 23 gives a much faster way to find the GCD.)

  • Scheduling. The opening question: one task every 12 days, another every 18. Since \(12 = 2^2 \cdot 3\) and \(18 = 2 \cdot 3^2\), the LCM is \(2^2 \cdot 3^2 = 36\). They coincide every 36 days. The same calculation tells you when two buses with 12- and 18-minute headways leave the depot together again.

  • Tiling. The largest square tile that exactly covers a 360 cm by 270 cm floor has side \(\gcd(360, 270)\). With \(360 = 2^3 \cdot 3^2 \cdot 5\) and \(270 = 2 \cdot 3^3 \cdot 5\), that is \(2 \cdot 3^2 \cdot 5 = 90\) cm, giving a \(4 \times 3\) grid of tiles.

  • Engineering. Two meshing gears with 12 and 18 teeth bring the same pair of teeth together every \(\operatorname{lcm}(12, 18) = 36\) teeth, so any flaw on one tooth keeps hitting the same few teeth on the other. Designers prefer counts with no common factor (a "hunting tooth"): 13 and 18 teeth meet again only after \(13 \times 18 = 234\) teeth, which spreads the wear.

  • Error detection. An ISBN-10 is valid when \(10d_1 + 9d_2 + \cdots + 1 \cdot d_{10}\) is divisible by 11. For 0-306-40615-2 the sum is 132 = \(12 \times 11\), which is valid. Mistype any single digit, or swap two adjacent digits, and the sum stops being a multiple of 11.

Computer-science connection: primes in the wild
  • Cryptography. RSA keys are built by multiplying two huge random primes. Multiplying is easy; recovering the primes from the product is (as far as anyone knows) infeasible for classical computers.

  • Hashing. Hash-table sizes and multiplicative hash constants are often prime, so that regular patterns in keys (all multiples of 8, say) do not pile up in the same buckets.

  • Negative remainders. Languages disagree on division with remainder for negative numbers. Python: -7 // 2 == -4, -7 % 2 == 1 (remainder always has the sign of the divisor, matching the mathematical convention \(0 \le r < b\)). C, Java, JavaScript: -7 / 2 == -3, -7 % 2 == -1. Code like if (n % 2 == 1) to test oddness silently fails for negative n in C.

Factor explorer

Enter a number and watch trial division run step by step: the current divisor, the shrinking value, the growing factor list, and a marker showing \(\sqrt{n}\) where the search may stop. Then plot the number of steps against \(n\) for \(n\) up to a million and see primes (worst case) form the top envelope.

1.8.9. Exercises

  1. Is 2,345,678 divisible by 2? by 3? by 9? by 11? Justify with the tests.

  2. Find the prime factorisation of 1260 and of 2310.

  3. Why does trial division never need to try \(d = 15\) separately, in the sense that 15 can never divide the remaining \(n\) when it is reached?

  4. How many different rectangular grids (rows × columns, order mattering) can 36 chairs form? Use the factorisation \(36 = 2^2 \cdot 3^2\) to count without listing.

Answers
  1. Last digit 8: divisible by 2. Digit sum \(2 + 3 + 4 + 5 + 6 + 7 + 8 = 35\): not a multiple of 3, so neither 3 nor 9. Alternating sum from the right: \(8 - 7 + 6 - 5 + 4 - 3 + 2 = 5\): not a multiple of 11.

  2. \(1260 = 2 \cdot 630 = 2^2 \cdot 315 = 2^2 \cdot 3 \cdot 105 = 2^2 \cdot 3^2 \cdot 35 = 2^2 \cdot 3^2 \cdot 5 \cdot 7\). \(2310 = 2 \cdot 3 \cdot 5 \cdot 7 \cdot 11\).

  3. By the time \(d = 15\), every factor 3 and every factor 5 has been divided out of \(n\) (at \(d = 3\) and \(d = 5\)). A number with no factor 3 cannot be a multiple of 15.

  4. A divisor of 36 has the form \(2^i 3^j\) with \(i \in \{0, 1, 2\}\) and \(j \in \{0, 1, 2\}\): \(3 \times 3 = 9\) divisors. Each divisor \(r\) gives the grid "\(r\) rows × \(36/r\) columns", so there are 9 grids (1×36, 2×18, 3×12, 4×9, 6×6, 9×4, 12×3, 18×2, 36×1). Counting by exponents like this is a first taste of Chapter 24.

US curriculum

Factors, multiples, and primes appear in grade 4 (Common Core 4.OA.4); prime factorisation, greatest common factor, and least common multiple in grade 6 (6.NS.4). The fundamental theorem of arithmetic is usually stated without proof; the proof belongs to college discrete mathematics or number theory.

1.9. Integers inside a computer: two’s complement and overflow

1.9.1. The problem

In mathematics, \(\mathbb{Z}\) is infinite: you can always add 1. In a computer, an int32 has exactly \(2^{32}\) possible bit patterns. So what happens when you add 1 to the largest one? And how does a register that only holds bits represent \(-5\) at all?

In December 2014 the YouTube view counter for the video "Gangnam Style" approached \(2\,147\,483\,647 = 2^{31} - 1\), the largest value of a signed 32-bit integer. YouTube upgraded the counter to 64 bits before it overflowed. Many systems have not been so lucky; the "Year 2038 problem" is the same story for 32-bit timestamps counting seconds since 1 January 1970.

1.9.2. Intuition: a clock, not a line

A fixed-width integer does not live on a number line; it lives on a circle, like the hours on a clock. With 4 bits there are 16 patterns, \(0000\) to \(1111\). Adding 1 moves one step clockwise. After \(1111\) comes \(0000\) again — the carry out of the top bit is simply lost.

The question is just how to label the 16 positions. Unsigned integers label them 0 to 15. Two’s complement keeps 0 to 7 for the patterns with top bit 0 and labels the other half \(-8\) to \(-1\), so that stepping counter-clockwise from 0 gives \(-1\), \(-2\), … — exactly as on the number line.

Sixteen 4-bit patterns around a circle labelled 0 to 7 and -8 to -1
Figure 10. 4-bit two’s complement. Each pattern is a position on a circle; adding 1 steps clockwise. The jump from 7 to \(-8\) is overflow.

1.9.3. Why it works

On the 16-position clock, moving 16 steps brings you back to where you started, so the patterns cannot tell the difference between \(x\) and \(x + 16\) or \(x - 16\). Mathematicians say the arithmetic is modulo 16 (Chapter 23 develops this as modular arithmetic). The pattern for \(-3\) is therefore the same as the pattern for \(16 - 3 = 13 = 1101_2\). Try it: Step past 7 on the clock; −3 is 1101 in 4 bits.

In general, with \(n\) bits, the negative number \(-x\) is stored as the bit pattern of \(2^n - x\). And since \(2^n - x = (2^n - 1 - x) + 1\), and \(2^n - 1\) is all ones (\(1111_2 = 15\)), subtracting \(x\) from all-ones simply flips every bit. Hence the famous rule:

Example 7. Procedure — negate a two’s-complement integer

Input: the \(n\)-bit pattern of an integer \(x\).

Steps:

  1. Invert every bit (0 ↔ 1). This computes \(2^n - 1 - x\).

  2. Add 1, discarding any carry out of the top bit. This gives \(2^n - x\).

Output: the \(n\)-bit pattern of \(-x\).

Worked example (8 bits). Represent \(-5\): Try it: −5 in 8 bits.

\[\begin{aligned} 5 &= 0000\,0101_2 \\ \text{invert} &\to 1111\,1010_2 \\ \text{add 1} &\to 1111\,1011_2 = \text{FB}_{16} . \end{aligned}\]

Check: unsigned, \(\text{FB}_{16} = 251 = 256 - 5\). ✓ And \(5 + (-5)\): \(0000\,0101 + 1111\,1011 = 1\,0000\,0000\); the ninth bit falls off, leaving \(0000\,0000\). ✓

The beauty of the scheme is that the hardware adder does not need to know whether numbers are signed: the same circuit adds unsigned and two’s-complement integers correctly, because both are just arithmetic modulo \(2^n\) with different labels.

1.9.4. Vocabulary

Two’s complement, overflow, signed and unsigned

An unsigned \(n\)-bit integer represents \(0\) to \(2^n - 1\). A signed \(n\)-bit integer in two’s complement represents \(-2^{n-1}\) to \(2^{n-1} - 1\); the top bit is the sign bit (1 = negative). Overflow is when the true mathematical result of an operation lies outside the representable range, so the stored result wraps around. For 32 bits the signed range is \(-2\,147\,483\,648\) to \(2\,147\,483\,647\).

The range is lopsided — one more negative than positive — because zero takes one of the "non-negative" patterns. This is why \(-(-2^{31})\) overflows back to \(-2^{31}\), and why abs(INT_MIN) misbehaves.

1.9.5. Simulating it

Python’s integers never overflow, which makes them a good laboratory: we can simulate a 32-bit register by keeping only the low 32 bits.

def wrap_int32(x):
    """Reduce x to what a 32-bit two's-complement register would hold."""
    x &= 0xFFFFFFFF                  # keep the low 32 bits
    return x - (1 << 32) if x & 0x80000000 else x   # top bit set => negative

big = 2_147_483_647                  # 2^31 - 1, the largest int32
print(wrap_int32(big + 1))
print(wrap_int32(-big - 1 - 1))
print(wrap_int32(-5), hex(-5 & 0xFFFFFFFF))
-2147483648
2147483647
-5 0xfffffffb

1.9.6. Failure modes

Overflow is silent

Most languages do not stop when integers overflow. In C and C++ signed overflow is undefined behaviour — the compiler may assume it never happens and optimise accordingly, sometimes deleting your overflow check. Java and Go wrap silently. Rust panics in debug builds and wraps in release builds. A classic bug: the midpoint (lo + hi) / 2 in binary search overflows when lo + hi > INT_MAX; the safe form is lo + (hi - lo) / 2. That bug sat in the Java standard library’s binary search for about nine years before it was found in 2006.

Computer-science connection: choosing integer widths

Rules of thumb that follow from this section:

  • Counts that can only grow (views, bytes transferred, IDs) should be 64-bit from day one. \(2^{63} - 1 \approx 9.2 \times 10^{18}\) is effectively unreachable; \(2^{31} - 1 \approx 2.1 \times 10^9\) is reached by successful products.

  • Use unsigned types for bit manipulation and sizes; be careful mixing them with signed values, since in C -1 < 0u is false (the \(-1\) is converted to \(2^{32} - 1\)).

  • Wraparound is a feature for hashing, checksums, and random-number generators, which are deliberately computed modulo \(2^{32}\) or \(2^{64}\).

Ones' complement and the two zeros

Early computers tried other schemes. Sign-magnitude used the top bit as a minus sign; ones' complement negated by flipping bits without adding 1. Both have two zeros (\(+0\) and \(-0\)) and need special adder logic. Two’s complement won because the plain unsigned adder just works. Floating point, interestingly, still uses sign-magnitude, which is why IEEE 754 has both 0.0 and -0.0.

Overflow clock

An \(n\)-bit clock with a slider for \(n\) from 3 to 8. Each position shows its bit pattern and both its unsigned and signed labels. Add or subtract a chosen amount and watch the hand move; the overflow boundary flashes when crossed. A second mode multiplies, showing that multiplication modulo \(2^n\) also wraps.

1.9.7. Exercises

  1. What range of values does a signed 8-bit integer hold? An unsigned 16-bit integer?

  2. Find the 8-bit two’s-complement pattern for \(-1\), \(-128\), and \(-100\).

  3. What signed 8-bit value does the pattern \(1001\,0110_2\) represent?

  4. In 8-bit signed arithmetic, compute \(100 + 50\). What value is stored, and why?

Answers
  1. Signed 8-bit: \(-2^7 = -128\) to \(2^7 - 1 = 127\). Unsigned 16-bit: 0 to \(2^{16} - 1 = 65\,535\).

  2. \(-1\): invert \(0000\,0001\) to \(1111\,1110\), add 1: \(1111\,1111\). \(-128\): \(256 - 128 = 128 = 1000\,0000\). \(-100\): \(256 - 100 = 156 = 1001\,1100\).

  3. Top bit is 1, so negative. Unsigned value \(128 + 16 + 4 + 2 = 150\); signed value \(150 - 256 = -106\). (Or: invert to \(0110\,1001 = 105\), add 1: 106, so the value is \(-106\).)

  4. The true sum 150 exceeds 127. The stored pattern is that of 150, which read as signed is \(150 - 256 = -106\). The result wrapped around the clock.

US curriculum

Two’s complement is not part of the standard US mathematics sequence. It is taught in AP Computer Science (lightly) and in college computer organisation / architecture courses. The underlying modular arithmetic appears in discrete mathematics.

1.10. Estimation and rounding

1.10.1. The problem

A cloud bill says a job processed 3.8 TB at $0.023 per GB. Is the $87.40 charge plausible? A colleague claims a loop over 50,000 records with a 2 ms database call each "takes a couple of seconds". Right? You do not need a calculator to answer either; you need estimation. Estimation is how you catch errors — your own, a spreadsheet’s, a program’s — before they cost you.

1.10.2. Rounding

Rounding, significant figures, truncation

To round a number is to replace it by a nearby number with fewer digits. Rounding "to the nearest 10", "to 2 decimal places" (2 d.p.), or "to 3 significant figures" (3 s.f.) specifies which digit is the last one kept. The standard rule: look at the first digit dropped; if it is 5 or more round up, otherwise round down. Truncation simply drops digits (always toward zero). The symbol \(\approx\) means "approximately equal to".

Example 8. Procedure — round to a given place

Input: a number \(x\) and the place to keep (e.g. hundredths).

Steps:

  1. Identify the rounding digit — the last digit to keep.

  2. Look at the digit immediately to its right (the decider).

  3. If the decider is 0–4, keep the rounding digit. If 5–9, increase it by 1 (carrying if it was 9).

  4. Drop all digits after the rounding digit (replacing them with zeros if they are to the left of the decimal point).

Output: the rounded number.

Worked examples. \(3.14159\) to 2 d.p.: rounding digit 4, decider 1, so \(3.14\). \(2.7183\) to 1 d.p.: rounding digit 7, decider 1, so \(2.7\). \(47\,862\) to the nearest thousand: rounding digit 7, decider 8, so \(48\,000\). \(9.96\) to 1 d.p.: rounding digit 9, decider 6, so the 9 becomes 10, carry: \(10.0\) (keep the trailing zero to show the precision).

Significant figures count from the first non-zero digit: \(0.004\,072\) to 2 s.f. is \(0.0041\). They get a fuller treatment alongside scientific notation in Chapter 3.

1.10.3. Alternative rounding rules

"Round half up" is biased: over many values ending in exactly 5, it always goes up, nudging totals upward. Round half to even ("banker’s rounding") sends an exact half to whichever neighbour is even: \(2.5 \to 2\), \(3.5 \to 4\). Over many values, the ups and downs cancel. IEEE 754 floating-point uses round-half-to-even by default, and so does Python’s round:

>>> round(2.5), round(3.5), round(0.125, 2), round(2.675, 2)
(2, 4, 0.12, 2.67)

The last one is not banker’s rounding: \(2.675\) cannot be stored exactly in binary and is actually stored as a value slightly below 2.675, so it rounds down. That is a story for Chapter 2.

1.10.4. Choosing a method

  • Everyday reporting: round half up — it is what readers expect.

  • Accumulating many rounded values (financial ledgers, statistics): round half to even, or better, do not round until the end.

  • Converting to an integer index or a count of whole items: truncation or floor, deliberately.

Rounding too early

Round only at the end. Rounding intermediate results compounds errors: \(0.4 + 0.4 + 0.4 = 1.2\), which rounds to 1, but rounding each term first gives \(0 + 0 + 0 = 0\). Double rounding is a related trap: \(1.45\) to 1 d.p. is \(1.5\) (half up), then to the nearest whole is 2; but \(1.45\) rounded directly to the nearest whole is 1.

1.10.5. Estimation

Estimation means replacing numbers by round values that are easy to work with, computing, and judging whether the true answer is close.

The cloud bill. \(3.8 \text{ TB} \approx 4000 \text{ GB}\) (rounding up a little). \(\$0.023 \approx \$0.02\) (rounding down a little — the errors partly cancel). \(4000 \times 0.02 = 80\). So about $80–$90: the $87.40 charge is plausible. (Exactly: \(3800 \times 0.023 = 87.40\).)

The loop. \(50\,000 \times 2 \text{ ms} = 100\,000 \text{ ms} = 100 \text{ s}\), nearly two minutes, not "a couple of seconds". The colleague is out by a factor of about 50 — the kind of error estimation is built to catch.

Order-of-magnitude (Fermi) estimates. How many piano tuners are in Chicago? Enrico Fermi famously posed such questions to students: chain together rough guesses (people, households, pianos per household, tunings per year, tunings per tuner per year), each rounded to a power of ten. Individual errors tend to partially cancel, and the result is often within a factor of 3 of the truth. Chapter 3 develops the power-of-ten thinking that makes this work.

Computer-science connection: back-of-the-envelope engineering

System design is estimation. "Latency numbers every programmer should know" (an L1 cache hit is about a nanosecond, a main-memory reference about 100 ns, a same-datacentre round trip about half a millisecond, a disk seek about 10 ms) let you estimate before you build: will this fit in memory, is the bottleneck network or disk, can one machine handle the load? An estimate that is right to within a factor of 2 will usually tell you which design to pursue.

Estimation trainer

The app shows a quick calculation (\(387 \times 52\), \(0.023 \times 3800\), \(7.9 \text{ GB} / 41 \text{ s}\)) for three seconds, then asks for an estimate. Score by how close the estimate is on a logarithmic scale, and track your typical error factor over time.

1.10.6. Exercises

  1. Round \(6.0451\) to (a) 2 d.p., (b) 1 d.p., (c) 3 s.f., (d) the nearest whole number.

  2. Estimate \(48.7 \times 21.3\), then compute it exactly. What was your relative error?

  3. A service handles 1,200 requests per second, each producing a 3 KB log line. Roughly how much log data is produced per day?

Answers
  1. (a) \(6.05\) (decider 5, round up). (b) \(6.0\) (decider 4). (c) \(6.05\). (d) \(6\).

  2. \(50 \times 20 = 1000\). Exactly: \(48.7 \times 21.3 = 1037.31\). Relative error \((1037.31 - 1000)/1037.31 \approx 0.036\), about 3.6%. (Rounding 48.7 up and 21.3 down partly cancelled.)

  3. \(1200 \times 3 \text{ KB} = 3600 \text{ KB/s} \approx 3.6 \text{ MB/s}\). A day is \(86\,400 \approx 10^5\) seconds. \(3.6 \text{ MB} \times 10^5 \approx 3.6 \times 10^5 \text{ MB} \approx 360 \text{ GB}\) per day. (Exactly, with 86,400 s: about 311 GB.)

US curriculum

Rounding to a place value is a grade 3–5 topic (Common Core 3.NBT.1, 5.NBT.4). Estimation recurs throughout middle school. Significant figures are usually taught in high-school chemistry and physics rather than in mathematics courses.

1.11. Interactive tools

Browser tools on the companion website that go with this chapter. Each example link in the chapter opens one of them with that example already set up.

1.12. Mastery check

  1. Classify each number as natural, integer, rational, or irrational (give the smallest set it belongs to): \(-4\), \(0.75\), \(\sqrt{9}\), \(\sqrt{10}\), \(0.\overline{6}\).

  2. Convert \(1101\,0110_2\) to hex and to decimal. Convert 300 to binary.

  3. Compute \(49 \times 51\) mentally and name every arithmetic law you used.

  4. Prove that \((-a)(-b) = ab\) starting from \((-1)(-1) = 1\) and the laws of arithmetic.

  5. Evaluate \(12 - 2 \times (1 - 4)^2 \div 6\). Then state what Python prints for -4 ** 0.5 + 10 // -3.

  6. Find the prime factorisation of 2024 and explain why trial division can stop where it does.

  7. What is the 8-bit two’s-complement pattern of \(-37\)? What happens in 8-bit signed arithmetic if you compute \(127 + 1\)?

  8. Estimate the number of seconds in a year to one significant figure, then to three.

Decision rule: All correct without hesitation → move on to Chapter 2. Stuck on 1–2 → reread the matching section (Section 1.1, Section 1.3, Section 1.4, Section 1.5, Section 1.6, Section 1.8, Section 1.9, Section 1.10). Stuck on more → work the section exercises first.

Mastery check answers
  1. \(-4\): integer. \(0.75 = \tfrac{3}{4}\): rational. \(\sqrt{9} = 3\): natural. \(\sqrt{10}\): irrational (10 is not a perfect square; the argument for \(\sqrt{2}\) adapts). \(0.\overline{6} = \tfrac{2}{3}\): rational.

  2. Group bits: \(1101 = \text{D}\), \(0110 = 6\), so \(\text{D6}_{16}\). Decimal: \(13 \times 16 + 6 = 214\). For 300: \(256\) fits (44 left), 128 no, 64 no, 32 fits (12 left), 16 no, 8 fits (4 left), 4 fits (0 left), 2 no, 1 no: \(1\,0010\,1100_2\). Check: \(256 + 32 + 8 + 4 = 300\). ✓

  3. \(49 \times 51 = 49 \times (50 + 1) = 49 \times 50 + 49\) (distributive) \(= 2450 + 49 = 2499\). Alternatively \((50 - 1)(50 + 1) = 2500 - 1 = 2499\) (distributive twice, commutative, and inverse to cancel \(-50 + 50\)).

  4. \((-a)(-b) = ((-1)a)((-1)b)\) (since \(-x = (-1)x\)) \(= (-1)(-1)\,ab\) (commutative and associative laws to regroup) \(= 1 \cdot ab = ab\) (identity).

  5. Brackets: \(1 - 4 = -3\); exponent: \((-3)^2 = 9\); then \(2 \times 9 = 18\), \(18 \div 6 = 3\); finally \(12 - 3 = 9\). Python: -4 ** 0.5 is \(-(4^{0.5}) = -2.0\); 10 // -3 floors \(-3.33\ldots\) to \(-4\); the sum is -6.0.

  6. \(2024 = 2 \cdot 1012 = 2^2 \cdot 506 = 2^3 \cdot 253\); 253 is not divisible by 3, 5, or 7; \(253 = 11 \times 23\). So \(2024 = 2^3 \cdot 11 \cdot 23\). After dividing out 11 the remainder is 23, and the next trial divisor 12 has \(12^2 = 144 > 23\), so 23 must be prime: a composite number always has a factor no larger than its square root.

  7. \(37 = 0010\,0101\); invert: \(1101\,1010\); add 1: \(1101\,1011\) (\(= \text{DB}_{16} = 219 = 256 - 37\)). \(127 + 1\) overflows: the pattern \(1000\,0000\) is read as \(-128\).

  8. \(365 \times 24 \times 3600\). Roughly \(400 \times 25 \times 4000 = 4 \times 10^7\) is a little high (all three rounded up); more carefully \(365 \times 86\,400 = 31\,536\,000 \approx 3 \times 10^7\) (1 s.f.) or \(3.15 \times 10^7\) (3 s.f.). A handy fact: a year is about \(\pi \times 10^7\) seconds.