Shelves / Arithmetic and Numbers
AN·09
Negative Numbers
Numbers below zero: what a negative number is (an opposite, a direction, a debt), the number line and absolute value, why subtracting a negative adds, why a negative times a negative is positive (proved, not memorised), the distributive law with subtraction, why inequalities flip, the three ways programming languages divide negative numbers, and how computers store negatives in two's complement, where 251 and −5 are the same byte.
Start here
What this chapter answers
What does mean, and is bigger or smaller than ? Why is ? Why is and not , and is that a convention someone chose or something that couldn't be otherwise? Why does multiplying both sides of an inequality by turn it round? Why does Python say while JavaScript says ? And how can the same byte mean both 251 and ?
Negative numbers in one picture
Extend chapter 1's number line to the left of zero: , each as far from zero as its positive partner but on the other side. A number now has a size (its distance from zero) and a direction (which side). Adding a positive number moves right; adding a negative moves left. Everything in this chapter is that picture, plus the insistence that the laws of chapter 1 keep working on the new numbers.
What a negative number is
Opposites
For every number , its opposite is the number that adds to it to make zero:
So is "the number that undoes 5": a debt of ₹5 cancels a credit of ₹5; 5 floors down cancels 5 floors up; 5 °C below zero is as far from zero as 5 °C above it. The whole numbers together with their opposites are the integers: . The opposite of an opposite is the number itself, , because is what adds to to make zero. And each number has only one opposite: if and both add to to make zero, then .
Order and absolute value
On the number line, numbers increase to the right, so : a temperature of °C is colder than °C, and a debt of ₹10 leaves you worse off than a debt of ₹2. The absolute value is a number's distance from zero, its size without its direction: . The distance between two numbers on the line is : from to 4 is steps.
Adding and subtracting
Adding: moves on the line
Start at the first number and move: right for a positive amount, left for a negative one. : start at 3, move 5 left, land on . . In words: same signs, add the sizes and keep the sign; different signs, subtract the smaller size from the larger and keep the sign of the larger. The laws of chapter 1 still hold: addition of integers is commutative and associative, and 0 is still the identity.
Subtracting: add the opposite
Chapter 3 defined as the number you add to to get . With negatives that number always exists, and it's , because . So:
Subtracting a negative adds. On the line: asks "how far from to 5?", which is 8 steps to the right. And for money: cancelling a ₹3 debt (subtracting ) leaves you ₹3 better off. Subtraction is now always possible, which is why the integers were invented, and it's never commutative: and are opposites.
Multiplying and dividing
Positive times negative
is three lots of : . Three debts of ₹4 are a debt of ₹12. By commutativity, too. In general, : a negative times a positive is negative.
Negative times negative
What should be? "Minus three lots of minus four" has no direct picture, so ask what the laws of arithmetic allow. Chapter 1's distributive law forces the answer.
So a negative times a negative must be positive, if distributivity is to keep working for the new numbers; any other choice would break the arithmetic of the whole numbers we already trust. That's the honest answer to "why": not a rule handed down, but the only rule consistent with the ones before it. A pattern shows the same thing without algebra: , , , ; each step down adds 4, so the next, , is 4.
Dividing
Division undoes multiplication, so the signs follow: because , and because . Same signs give a positive result, different signs a negative one, for both multiplication and division. Fractions take signs the same way: , which is why fraction types keep the sign on the top (chapter 6's companion, drill D2).
Distributivity with subtraction
With subtraction written as adding the opposite, distributivity covers it at once:
So , a mental-arithmetic trick that chapter 1 could only state for positive differences. The same algebra gives the familiar : .
Why inequalities flip
If , then adding the same number to both keeps the order. Multiplying by a positive number keeps it; multiplying by a negative number reverses it: , but . The reason: means is positive; multiplying by gives , which is negative, so . This is the bug in chapter 6's companion, drill D2: cross-multiplying to compare fractions multiplies by both denominators, which flips the comparison if one of them is negative.
Division with remainder, for negatives
Chapter 4's division algorithm, with , was for whole numbers. With negatives, there's a choice to make about , and programming languages chose differently:
| Aspect | Floored (Python's //, %) |
Truncated (C, Java, JavaScript) | Euclidean |
|---|---|---|---|
| Quotient | Rounded down | Rounded towards zero | Chosen so |
| by 5 | , | , | , |
| by | , | , | , |
| Sign of | Same as the divisor | Same as the dividend | Never negative |
All three satisfy with ; they differ only in which of the two possible remainders they pick. For clocks, calendars, array indexes and hash buckets you want a remainder in to even for negative inputs: Python's % with a positive divisor gives that; in C, Java and JavaScript, -17 % 5 is -2, and an index of is a bug. The lab measures all three.
Negative numbers in computers
The problem
A byte has 8 bits and can hold 256 patterns. For whole numbers they mean 0 to 255 (chapter 2). To store negatives, some patterns must be given negative meanings. Three schemes have been used:
- Sign and magnitude: the first bit is the sign, the other seven the size. is
00000101, is10000101. Simple, but there are two zeros (00000000and10000000) and addition needs special cases. - Ones' complement: is with every bit flipped. is
11111010. Still two zeros. - Two's complement: is stored as . is ,
11111011. One zero, and addition needs no special cases at all.
Two's complement
In two's complement with bits, a number from to is stored as the remainder of on division by (chapter 4, floored): positives as themselves, negatives as . For 8 bits that's to 127, and the first bit happens to be 1 exactly for the negatives.
The reason every computer uses it is chapter 5's "remainders add and multiply". The hardware adds bit patterns as unsigned numbers and keeps the last 8 bits, which is arithmetic modulo 256; and and 251 are the same number modulo 256 (they differ by 256). So adding 251 is the same, modulo 256, as adding : , and keeping 8 bits gives 7, which is . The same circuit adds signed and unsigned numbers; only the reading of the result differs.
So = 00000101, flipped 11111010, plus 1 = 11111011 = 251, the code for .
Overflow, and the number with no opposite
Fixed width means a fixed range. In 8 bits, wraps to (the pattern 10000000): the true answer, 128, isn't representable, and the remainder modulo 256 reads as . The range is lopsided: exists but doesn't, so has no opposite in 8 bits, and negating it gives again. In 32 bits the same happens to : abs of it is itself, a famous source of bugs in code that assumes absolute values are never negative.
Lab: negative numbers in code
Experiment 1: three remainders
import math
print(" a b | a // b a % b | trunc rem (C, Java, JS) | Euclidean q r")
for a, b in ((17, 5), (-17, 5), (17, -5), (-17, -5)):
tq = int(a / b) # truncate towards zero
tr = a - b * tq
eq = (a - a % abs(b)) // b # Euclidean: remainder always 0 <= r < |b|
er = a - b * eq
print(f"{a:>3} {b:>3} | {a // b:>6} {a % b:>5} | {tq:>5} {tr:>4} | {eq:>11} {er:>2}")
print("math.fmod(-17, 5) =", math.fmod(-17, 5), "| divmod(-17, 5) =", divmod(-17, 5))
a b | a // b a % b | trunc rem (C, Java, JS) | Euclidean q r
17 5 | 3 2 | 3 2 | 3 2
-17 5 | -4 3 | -3 -2 | -4 3
17 -5 | -4 -3 | -3 2 | -3 2
-17 -5 | 3 -2 | 3 -2 | 4 3
math.fmod(-17, 5) = -2.0 | divmod(-17, 5) = (-4, 3)
All three conventions agree for positive numbers and disagree as soon as a sign is negative. Python's // and % are floored, so -17 % 5 is 3; truncation (what C, Java and JavaScript do, and Python's math.fmod) gives ; the Euclidean remainder is never negative, even for a negative divisor. Each row satisfies : check .
Experiment 2: one byte, two readings
for n in (5, -5, 127, -128, -1):
b = n.to_bytes(1, "big", signed=True)
print(f"{n:>5} -> byte {b[0]:08b} = {b[0]:>3} read unsigned")
print(int.from_bytes(bytes([251]), "big", signed=True), int.from_bytes(bytes([251]), "big", signed=False))
print("-5 in 16 bits:", f"{(-5) & 0xFFFF:016b}", "| 2**8 - 5 =", 2 ** 8 - 5)
5 -> byte 00000101 = 5 read unsigned
-5 -> byte 11111011 = 251 read unsigned
127 -> byte 01111111 = 127 read unsigned
-128 -> byte 10000000 = 128 read unsigned
-1 -> byte 11111111 = 255 read unsigned
-5 251
-5 in 16 bits: 1111111111111011 | 2**8 - 5 = 251
The byte 11111011 is 251 read as unsigned and read as signed: the same bits, . is all ones (255), and is 10000000 (128). In 16 bits, is twelve 1s and then 1011: two's complement sign-extends, filling the new high bits with copies of the sign bit, which keeps the value the same at any width.
Experiment 3: overflow in JavaScript
const a = new Int8Array([127, -128, 100]);
a[0] += 1; a[1] -= 1; a[2] *= 2;
console.log(Array.from(a));
console.log((2147483647 + 1) | 0, Math.abs(-2147483648 | 0) | 0, (-7 >> 1), (-7 / 2) | 0, Math.floor(-7 / 2));
const i = new Int32Array([-2147483648]); i[0] = -i[0]; console.log(i[0]);
[ -128, 127, -56 ]
-2147483648 -2147483648 -4 -3 -4
-2147483648
An Int8Array stores 8-bit two's complement: 127 + 1 wraps to , wraps to 127, and becomes . JavaScript's | 0 converts to a 32-bit integer, so wraps to , and Math.abs of , forced back to 32 bits, is still negative; negating it in an Int32Array gives itself. Shifting right by one (-7 >> 1) floors (), while (-7 / 2) | 0 truncates (): two "halvings" that disagree for negatives, like Experiment 1's remainders.
Experiment 4: sorting signed bytes
nums = [3, -1, 0, -128, 127, -20, 5]
as_bytes = {n: n.to_bytes(1, "big", signed=True)[0] for n in nums}
print("by value: ", sorted(nums))
print("by stored byte: ", sorted(nums, key=lambda n: as_bytes[n]))
print("byte, sign flipped:", sorted(nums, key=lambda n: as_bytes[n] ^ 0x80))
print("as text: ", sorted(str(n) for n in nums))
by value: [-128, -20, -1, 0, 3, 5, 127]
by stored byte: [0, 3, 5, 127, -128, -20, -1]
byte, sign flipped: [-128, -20, -1, 0, 3, 5, 127]
as text: ['-1', '-128', '-20', '0', '127', '3', '5']
Sorting the stored bytes as unsigned numbers puts every negative after every positive, because negatives have the top bit set. Flipping the sign bit (XOR with 0x80) maps onto in order, so byte order then matches numeric order; databases and sort routines use exactly this trick to compare signed keys as raw bytes. Sorting the numbers as text is wrong in yet another way ( before , 127 before 3), chapter 1's point that numerals aren't numbers.
Worked examples
Arithmetic with signs
Temperatures, balances and distances
Bytes and remainders
Exercises
Practice
- Put in order, smallest first: , 2, , 0, , .
- Calculate: (a) ; (b) ; (c) ; (d) .
- Calculate: (a) ; (b) ; (c) and ; (d) .
- Use distributivity with subtraction to compute mentally: (a) ; (b) ; (c) .
- The temperature on a mountain is °C and in the valley 9 °C. What's the difference? If it drops 6 degrees everywhere, what is each?
- Write in 8-bit two's complement: (a) ; (b) ; (c) 100. What number is
10110000? - Find and for divided by 6 under the floored, truncated and Euclidean conventions.
Answers
- .
- (a) ; (b) ; (c) ; (d) .
- (a) ; (b) 8; (c) 1 and ; (d) .
- (a) ; (b) ; (c) .
- degrees. After the drop: °C and 3 °C; the difference is still 23.
- (a)
11111111; (b) =10011100; (c)01100100.10110000= 176 unsigned, . - Floored: , (). Truncated: , . Euclidean (divisor positive): same as floored, , .
Harder
- Prove that and that .
- Show that if and , then . Use it to explain why means .
- Explain why, in -bit two's complement, adding a number to its own code with the bits flipped always gives all 1s, and why that means flipped-plus-one negates.
- A program stores temperatures in tenths of a degree as signed 16-bit integers. What range can it store? What happens if it computes the average of two readings as when both are near the top of the range, and how should it be computed instead?
- Why is for every , and what does that tell you about solving ?
Answers
- , so is the opposite of (opposites are unique). Then .
- means . With , (a positive times a negative), so , . For : multiply both sides by , which is negative, so the inequality flips: . Check : ✓; : ✗.
- In each position, a bit and its flip are one 0 and one 1, so they add to 1 with no carries: the sum is ones, . So flipped , and flipped plus one is , the code of .
- to tenths: to degrees, far more than needed. But can overflow if both are large (two readings of 2000.0 degrees, 20,000 each, sum to 40,000, which wraps negative). Compute (safe when the difference fits), or widen to 32 bits before adding. A real thermometer won't reach those values, but the same bug in binary search over large arrays was found in widely used libraries in 2006.
- , by the sign rule. So squaring loses the sign: both 5 and square to 25, and has two solutions, and . (Chapter 10's square roots pick the positive one by convention.)
Challenge
- Suppose someone proposes the rule instead. Using only the distributive law and , derive a contradiction, so that the proposal can't be adopted without giving up distributivity.
Discussion
Distributivity gives . The left side is (zero times anything is zero, which itself follows from distributivity). The right side, under the proposal, is . So , a contradiction. Keeping would mean giving up distributivity, and with it long multiplication, the area model and most of algebra. So isn't a convention in the way that "1 isn't prime" is; it's forced.
In real life
Misconceptions and limits
The model to keep
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| " is bigger than because 10 is bigger than 2." | Order runs left to right on the line: . Size is . | Order and absolute value |
| " is always negative." | is the opposite of ; if , then . | Opposites |
| "Two negatives make a positive" (for addition too). | Only for multiplication and division; . | Adding: moves on the line |
| "Negative times negative is positive by convention." | It's forced by the distributive law. | Negative times negative |
| "." | ; . | Worked examples |
| "Multiplying both sides of an inequality by a number keeps it true." | A negative multiplier reverses it. | Why inequalities flip |
"% always gives a remainder from 0 to ." |
In C, Java and JavaScript, -17 % 5 is . |
Division with remainder, for negatives |
| "The absolute value of a number is never negative." | In fixed-width types, abs of the most negative value overflows and stays negative. |
Overflow, and the number with no opposite |
Limits and trade-offs
- Integers are a model of opposites, not of everything with a minus sign. A temperature of °C isn't "minus ten units of something"; it's a position on a scale with an arbitrary zero. Twice °C isn't "twice as cold".
- Fixed-width integers aren't the integers. They're remainders modulo read in a particular way; they obey the laws of arithmetic only modulo , and comparisons break at the wrap.
- Negative remainders are a convention. Choose the one your problem needs (usually a remainder from 0 to ), and don't assume your language chose it.
- Some quantities can't be negative. Counts, lengths and prices: a negative result there signals an error, not a debt. Validate.
Revision sheet
Key ideas
- Opposite: ; unique; . Integers: whole numbers and their opposites.
- Order: left to right on the line; . Absolute value : distance from 0. Distance between and : .
- Add: move right for positive, left for negative. Subtract = add the opposite: .
- Signs: ; ; , forced by distributivity. Same for division.
- Distributivity with subtraction: ; .
- Inequalities: multiplying or dividing by a negative reverses them.
- Remainders with negatives: floored (Python), truncated (C, Java, JS), Euclidean (); all satisfy .
- Two's complement ( bits): stored as ; as = flip the bits and add 1. Range to .
- Overflow wraps; has no opposite in bits.
Glossary
- Opposite (additive inverse): the number that adds to a given number to make zero; .
- Integer: a whole number or the opposite of one:
- Absolute value: a number's distance from zero, .
- Signed number: a number with a direction (positive or negative) as well as a size.
- Sign rule: same signs multiply or divide to a positive result, different signs to a negative one.
- Floored division: division whose quotient is rounded down, so the remainder has the divisor's sign.
- Truncated division: division whose quotient is rounded towards zero, so the remainder has the dividend's sign.
- Euclidean division: division whose remainder is never negative.
- Sign and magnitude: storing a sign bit and the size separately.
- Ones' complement: storing as with every bit flipped.
- Two's complement: storing in bits as ; flip the bits and add 1.
- Sign extension: widening a two's complement number by copying its sign bit into the new high bits.
- Integer overflow: a result outside a fixed-width type's range, which wraps around.