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

Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers

B1·09

Negative Numbers

Around chapter 9: how negative numbers connect subtraction, the laws of arithmetic, remainders and machine integers; three other ways to see them; what the chapter simplifies (negative zero, unsigned types, mixing signed and unsigned); how Python's decimal module divides with the sign handled separately, and why its remainder disagrees with int's; four debugging drills; and interview questions.

6 topics · ~13 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Opposite −a: a+(−a)=0, unique, −(−a)=a → the integers → the number line extended left → order and absolute value |a|, distance |a−b|.
  • Subtraction = adding the opposite (chapter 3's subtraction, now always possible).
  • Distributivity (chapter 1) forces 0×b=0, (−a)b=−(ab), (−a)(−b)=ab → division's sign rules → a(b−c)=ab−ac → inequalities flip under negative multipliers (chapter 6's companion, drill D2).
  • Remainders with negatives: floored, truncated, Euclidean (chapter 4) → clocks, weekdays, ring buffers, hash buckets want r≥0.
  • Machine integers: remainders modulo 2n (chapter 5) read as signed → two's complement, flip and add 1, sign extension, overflow, the number with no opposite.
  • Next: powers of negatives and −22 (chapter 10), signed errors and rounding of negatives (chapter 11), the real line (chapter 12).

Explain it differently

Negatives are bookkeeping that cancels. A credit and a debit of the same size cancel; that's all a+(−a)=0 says. Removing a debit from the books (subtracting a negative) is as good as adding a credit. Multiplying a debit by a count gives a bigger debit; reversing a debit, "taking away" debits several times, gives credit, which is (−)(−)=+.

Direction and turning round. Think of a number as a walk along a line: the size is how far, the sign is which way you face. Multiplying by −1 means turning round. Turning round twice faces you the way you started, so (−1)(−1)=1, and multiplying both sides of an inequality by −1 turns the whole line round, so the order reverses.

Two's complement is an odometer. A car's 5-digit odometer at 00002, wound back 5 km, shows 99997. If you agree that readings above 50000 mean "below zero", then 99997 means −3, and the odometer adds correctly in both directions without knowing anything about signs. A byte is an 8-bit odometer with 128 as the dividing line.

Gaps and misconceptions

What the chapter oversimplifies

1. "Zero has no sign", which is false for floating-point numbers. The integers have one zero. Floating point keeps a sign bit even for zero, so there are two:

Python
import math
z = -0.0
print(z == 0.0, z, math.copysign(1, z), 0.0 * -1, round(-0.4), round(-0.4, 1))
print(math.atan2(0.0, -1.0), math.atan2(-0.0, -1.0))
Text
True -0.0 -1.0 -0.0 0 -0.4
3.141592653589793 -3.141592653589793

−0.0 equals 0.0, but its sign can be detected (copysign), and functions that depend on direction give different answers: atan2 gives π or −π. Rounding −0.4 to one place keeps it, and 0.0×−1 produces −0.0. JavaScript shows the same and hides it when printing:

JavaScript
console.log(Math.round(-0.4), Object.is(Math.round(-0.4), -0), 1 / Math.round(-0.4), String(-0), JSON.stringify(-0));
Text
-0 true -Infinity 0 0

Math.round(-0.4) is −0, which prints as "0" and serialises to JSON as 0, but 1/−0 is −∞. Harmless in most code; visible in angles, divisions and any test that compares results with Object.is.

2. "Every integer has an opposite", which unsigned types don't allow. The chapter's integers include negatives. Unsigned machine types (sizes, counts, size_t in C) are remainders modulo 2n read without a sign, so subtracting past zero and negating both wrap:

Python
import numpy as np, warnings
warnings.simplefilter("ignore")
print("uint16: 3 - 5 =", np.uint16(3) - np.uint16(5), "| uint8: -(5) =", -np.uint8(5), "| 200 + 100 =", np.uint8(200) + np.uint8(100))
Text
uint16: 3 - 5 = 65534 | uint8: -(5) = 251 | 200 + 100 = 44

3−5 in 16 unsigned bits is 65,534, the opposite of 5 in 8 bits is 251, and 200+100 is 44. Each is the right answer modulo 2n and the wrong answer for a count. Code that subtracts unsigned values ("items left = stock − ordered") needs a check first.

3. "Signed and unsigned are two readings of the same bits", which breaks when they're mixed. Combining a signed and an unsigned value forces a choice of type, and languages choose differently:

Python
import numpy as np
x = np.uint64(10) - np.int64(3)
big = np.uint64(2**63 + 1) - np.int64(0)
print(x, type(x).__name__, "|", big, "=", int(big), "not", 2**63 + 1)
Text
7.0 float64 | 9.223372036854776e+18 = 9223372036854775808 not 9223372036854775809

NumPy can't fit every uint64 and every int64 in either type, so it converts both to float64, which has only 53 bits of precision: 263+1 silently becomes 263. JavaScript's >>> 0 reinterprets −1 as the unsigned 4,294,967,295, after which it's bigger than 1:

JavaScript
console.log(-1 >>> 0, (-1 >>> 0) > 1, (-5 >>> 0).toString(2).length);
Text
4294967295 true 32

(C has the classic version: -1 < 1u is false, because −1 is converted to the largest unsigned value.) Keep signed and unsigned values apart, or convert explicitly and check the range.

Common misconceptions

Misconception What's actually true Where it's shown
"There's only one zero." Floats have +0.0 and −0.0: equal, but distinguishable. What the chapter oversimplifies, point 1
"Subtracting a bigger number from a smaller gives a negative result." Not in unsigned types: it wraps to a large positive number. What the chapter oversimplifies, point 2
"Mixing signed and unsigned is harmless." It can convert to float (losing precision) or reinterpret −1 as a huge number. What the chapter oversimplifies, point 3
"Every decimal library rounds division the same way as integers." Python's Decimal truncates, so Decimal(-17) % 5 is −2 while -17 % 5 is 3. Code walkthrough
"A remainder is a valid array index." A truncated remainder can be negative; JavaScript returns undefined for it. Drill D1
"Math.abs makes a hash code safe to use as a bucket." Math.abs(Integer.MIN_VALUE) is still negative. Drill D2
"sort() sorts numbers." JavaScript's default sort compares text, so −1 comes before −10 and 10 before 2. Drill D3
"Integer division of a timestamp by 86,400 gives the day." For times before 1970, truncation gives the next day; floor. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Why the laws are worth keeping. The chapter's argument, "this rule is forced if distributivity is to hold", is the permanence principle that guided the extension of numbers from whole numbers to integers, fractions, reals and complex numbers (George Peacock, 1830): keep the laws, and let them decide the new cases. Complex numbers (i2=−1) are the next place it's applied, beyond this book.
  • Ordered rings. The integers aren't just a ring (the exercises' "What the chapter leaves out") but an ordered one: positives are closed under + and ×, and every number is positive, negative or zero. Remainders modulo m form a ring but can't be ordered compatibly (m−1 plus 1 is 0), which is why comparisons break at the wrap in machine integers.
  • Modular arithmetic underneath two's complement. n-bit two's complement is the ring of remainders modulo 2n with representatives chosen from −2n−1 to 2n−1−1. Addition, subtraction and multiplication are exact modulo 2n; only comparison and division depend on the chosen representatives.

Applying it

Code walkthrough

Python's int divides with floored rounding; its decimal module, following the General Decimal Arithmetic specification, truncates, and handles the sign separately from the digits. Excerpt from Lib/_pydecimal.py in Python 3.13, the method behind //, % and divmod for Decimal (on your computer: python3 -c "import _pydecimal; print(_pydecimal.__file__)"):

Python
    def _divide(self, other, context):
        """Return (self // other, self % other), to context.prec precision.

        Assumes that neither self nor other is a NaN, that self is not
        infinite and that other is nonzero.
        """
        sign = self._sign ^ other._sign
        ...
        if expdiff <= context.prec:
            op1 = _WorkRep(self)
            op2 = _WorkRep(other)
            if op1.exp >= op2.exp:
                op1.int *= 10**(op1.exp - op2.exp)
            else:
                op2.int *= 10**(op2.exp - op1.exp)
            q, r = divmod(op1.int, op2.int)
            if q < 10**context.prec:
                return (_dec_from_triple(sign, str(q), 0),
                        _dec_from_triple(self._sign, str(r), ideal_exp))

A Decimal stores a sign bit (0 for positive, 1 for negative) separately from its digits, like sign-and-magnitude. sign = self._sign ^ other._sign is the chapter's sign rule as one operation: exclusive or of the two sign bits is 0 (positive) when they're the same and 1 (negative) when they differ. _WorkRep holds the digits as a non-negative integer, so divmod(op1.int, op2.int) divides the sizes, both positive. Then the quotient gets the combined sign and the remainder gets the dividend's sign (self._sign): that's truncated division, built from magnitudes. Measured against int:

Python
from decimal import Decimal as D
for a, b in ((17, 5), (-17, 5), (17, -5), (-17, -5)):
    print(f"{a:>3} {b:>3}   int: {a // b:>3} {a % b:>3}   Decimal: {D(a) // D(b):>3} {D(a) % D(b):>3}   remainder_near: {D(a).remainder_near(D(b)):>3}")
print(D(-7) // D(2), D("-7.5") % D(2), D(0) * D(-1), -0.0)
Text
 17   5   int:   3   2   Decimal:   3   2   remainder_near:   2
-17   5   int:  -4   3   Decimal:  -3  -2   remainder_near:  -2
 17  -5   int:  -4  -3   Decimal:  -3   2   remainder_near:   2
-17  -5   int:   3  -2   Decimal:   3  -2   remainder_near:  -2
-3 -1.5 -0 -0.0

For −17 by 5, int gives −4 remainder 3 (floored) and Decimal gives −3 remainder −2 (truncated): the same rows as the chapter's Experiment 1, inside one language. remainder_near is a third choice, the remainder nearest zero (from −b2 to b2, the "least absolute remainder" of chapter 4's Deeper page). And because the sign is stored separately, Decimal(0) * Decimal(-1) is a negative zero, -0, as with floats.

Read it yourself

Using the code above, predict divmod(Decimal(17), Decimal(-5)) and Decimal("-7.5") % Decimal(2), and explain why a sign-and-magnitude representation makes truncation the natural choice.

Debugging drills

D1. A ring buffer that returns undefined

A JavaScript dashboard keeps the last five readings in a ring buffer and shows "the reading k steps back". For some steps it shows nothing:

JavaScript
// A ring buffer of the last 5 readings; "previous" steps back from the newest.
const ring = ["r0", "r1", "r2", "r3", "r4"], newest = 1;
for (const back of [0, 1, 2, 3, 6]) {
  const i = (newest - back) % ring.length;
  console.log(`back ${back}: index ${i} -> ${ring[i]}`);
}
Text
back 0: index 1 -> r1
back 1: index 0 -> r0
back 2: index -1 -> undefined
back 3: index -2 -> undefined
back 6: index 0 -> r0

Explain, and fix.

D2. A hash bucket of −8

A Java cache picks a bucket with Math.abs(key.hashCode()) % buckets. In production, one key throws ArrayIndexOutOfBoundsException:

Java
public class HashBucket {
    public static void main(String[] args) {
        String[] keys = {"apple", "kayavak", "polygenelubricants"};
        int buckets = 10;
        for (String k : keys) {
            int h = k.hashCode();
            System.out.printf("%-20s hash %12d  Math.abs %12d  bucket %4d  floorMod %3d%n",
                              k, h, Math.abs(h), Math.abs(h) % buckets, Math.floorMod(h, buckets));
        }
    }
}
Text
apple                hash     93029210  Math.abs     93029210  bucket    0  floorMod   0
kayavak              hash   -929574014  Math.abs    929574014  bucket    4  floorMod   6
polygenelubricants   hash  -2147483648  Math.abs  -2147483648  bucket   -8  floorMod   2

Explain, and fix.

D3. The coldest temperature is −1

A weather widget sorts the day's readings to show the coldest and warmest:

JavaScript
const temps = [-1, -10, 2, 10, -2, 0, -15];
const sorted = temps.slice().sort();
console.log(sorted.join(", "), "| coldest:", sorted[0], "| warmest:", sorted[sorted.length - 1]);
Text
-1, -10, -15, -2, 0, 10, 2 | coldest: -1 | warmest: 2

Explain, and fix.

D4. A birthday one day late

A service stores birth times as Unix timestamps (seconds since 1 January 1970, UTC) and computes the day number with integer division by 86,400, as in C or Java. People born before 1970 see the wrong date:

Python
import datetime as dt
DAY = 86_400
for label, ts in (("1 Jan 1970 06:00", 6 * 3600), ("31 Dec 1969 18:00", -6 * 3600), ("15 Aug 1947 09:00", -706_287_600)):
    truncated = int(ts / DAY)                    # what C, Java and JavaScript integer division do
    floored = ts // DAY                          # Python's //
    epoch = dt.date(1970, 1, 1)
    print(f"{label:<18} ts {ts:>12}  truncated -> {epoch + dt.timedelta(days=truncated)}  floored -> {epoch + dt.timedelta(days=floored)}")
Text
1 Jan 1970 06:00   ts        21600  truncated -> 1970-01-01  floored -> 1970-01-01
31 Dec 1969 18:00  ts       -21600  truncated -> 1970-01-01  floored -> 1969-12-31
15 Aug 1947 09:00  ts   -706287600  truncated -> 1947-08-16  floored -> 1947-08-15

Explain, and fix.

Career-oriented

Interview prep

Mid level

Q1. Implement mod(a, n) that always returns a value from 0 to n−1 in a language whose % truncates, and explain where you'd use it.

How to get there. What truncation returns for negatives, and the correction.

Q2. Explain two's complement to a junior engineer, and why −x is "flip the bits and add one".

How to get there. Remainders modulo 2n, and the all-ones sum.

Senior level

Q1. A code review finds int remaining = stock - ordered; where both are unsigned in one service and signed in another. What can go wrong, and what do you require?

How to get there. Unsigned subtraction, mixing types, and what the value means.

Q2. Your team's API returns money as signed integers of paise. A partner's client reads them into an unsigned 32-bit field. What breaks, and how do you prevent it?

How to get there. Signed values read as unsigned, and range.

Staff level

Q1. Set the organisation's rules for integer types in services that handle money, counts and identifiers.

How to get there. Range, signedness, division, overflow, and boundaries.

Q2. A legacy system stores temperatures in sign-and-magnitude bytes; the new one uses two's complement. Plan the migration.

How to get there. Which values differ, and how to prove the conversion.