Negative numbers and distance from zero
The number line, sign rules, abs(), and what // and % do below zero.
Why it matters
Below-zero numbers are everywhere in data. A refund is a negative sale, a winter temperature can be −9, a profit can turn into a loss, and a model's scores and weights are negative as often as positive. Python handles negatives exactly, but two of its operators surprise people with them, and those surprises cause real bugs. This lesson builds the number line in your head and shows where the traps are.
What you'll be able to do
- Place numbers below zero on a number line and compare them
- Apply the sign rules for adding, subtracting, multiplying and dividing
- Measure how far off a number is with abs()
- Predict what // and % do with negative numbers, and use % to wrap around a clock
What it covers
- The number line
- The sign rules
- A cold day's swing
- Distance from zero: abs()
- How far off was the forecast?
- // and % with negative numbers
- When did the flight leave?
- Negative numbers in AI
// divides and keeps a whole number. What does this print?print(-7 // 2)
Show the answer
-4
−7 ÷ 2 is −3.5, and // always rounds down, toward the left of the number line. Below −3.5 is −4, not −3. This lesson shows why, and where it matters.
The number line
Picture a ruler that carries on to the left of zero. Numbers to the right are bigger; numbers to the left are smaller. So −1 is bigger than −3, because it sits further right, closer to zero. A temperature of −1 is warmer than −3, and a bank balance of −$1 is better than −$3.
Adding moves you right and subtracting moves you left, so subtracting more than you have takes you below zero:
print(-3 < -1) # True: -3 is further left print(3 - 10) # 7 steps left of zero print(-5 + 8) # start at -5, move 8 right
A minus sign in front of a number, like -5, just says which side of zero it's on. It's easy to confuse with subtraction, because it's the same symbol: -5 is a number, while 3 - 5 is a calculation that happens to give a negative number. Zero itself is neither positive nor negative; it's the point where the two sides meet.
Negatives show up wherever something can go either way: profit and loss, a balance that's overdrawn, a change that's a fall rather than a rise, a position below sea level, a score below average.
Try both numbers negative, then one of each. Watch the sign of each result.
The sign rules
Four rules cover almost everything:
- Adding a negative is the same as subtracting: 10 + (−4) = 6.
- Subtracting a negative is the same as adding: 10 − (−4) = 14.
- Multiply or divide two numbers with the same sign, and the result is positive: −3 × −4 = 12.
- Multiply or divide numbers with different signs, and the result is negative: −3 × 4 = −12.
Brackets help when a negative number follows an operator, both on paper and for readers of your code: 10 − (−4) is easier to read than 10 − −4, though Python accepts both.
The second rule sounds odd until you think of money. A negative number is a debt. Taking away a debt of $4 leaves you $4 better off, which is exactly what adding $4 does.
For multiplying, a pattern shows why two negatives make a positive. Multiply −3 by 2, 1, 0 and −1 in turn: −6, −3, 0, then 3. Each step down in the second number adds 3 to the result, so the pattern carries straight on past zero into the positives.
print(10 + -4, 10 - -4) print(-3 * -4, -3 * 4, -12 / -3)
balance = 50 refund = -20 print(balance - refund)
Show the answer
70
Subtracting a negative adds: 50 − (−20) = 50 + 20 = 70. Taking away a debt leaves you better off.
A cold day's swing
On a winter day the high was −2 degrees and the low was −9. Set swing to how many degrees the temperature rose from the low to the high, and middle to the average of the high and the low.
high = -2 low = -9 swing = 0 # how far the temperature rose, low to high middle = 0 # the average of high and low print(swing, middle)
Distance from zero: abs()
Sometimes the sign doesn't matter, only the size. A forecast that's 3 degrees too high and one that's 3 degrees too low are both 3 degrees off. The absolute value of a number is its distance from zero, always zero or more. Python's abs() gives it:
print(abs(-7), abs(7), abs(0)) predicted = 120 actual = 104 error = actual - predicted print(error, abs(error))
Pick one order for subtracting and stick to it; this course uses actual minus predicted. The error is −16: the prediction was 16 too high. Its absolute value, 16, is how far off it was. You'll meet this again as the mean absolute error, one of the most common ways to score a model: the average of the absolute errors, so misses in both directions count instead of canceling out.
abs() also measures the gap between any two numbers, whichever is bigger: abs(a - b) is the distance between them on the number line. The gap between −2 and 5 is 7, and so is the gap between 5 and −2. That's how you'd check whether two readings are "within 3 degrees of each other" without caring which one is higher.
miss = 47 - 52 print(miss, abs(miss))
Show the answer
-5 5
47 − 52 is −5: the prediction was 5 too high. abs() drops the sign and keeps the size, 5.
How far off was the forecast?
A forecast said 120 tents would sell; 104 did. Set error (actual minus forecast), size (how far off, ignoring direction) and percent_off (the size as a percentage of the actual sales, rounded to 1 decimal place).
forecast = 120 actual = 104 error = 0 size = 0 percent_off = 0 print(error, size, percent_off)
// and % with negative numbers
With positive numbers, // and % behave as you'd expect. With negatives, Python follows one rule that keeps them consistent: // always rounds down, toward the left of the number line, and % gives whatever is left over so that the two fit back together.
print(-7 // 2, -7 % 2) # -4 and 1, because -4 * 2 + 1 == -7 print((-7 // 2) * 2 + (-7 % 2)) # always gets back to -7
That rule makes % perfect for anything that wraps around, like a clock. Five hours before 2 a.m. is (2 − 5) % 24, which is 21: nine in the evening the day before. Days of the week, months and angles wrap the same way. (Many other languages round toward zero instead, so this is a classic surprise when moving code between them.)
Rounding toward zero does exist in Python, just not in //. int() chops off the decimals, which moves a negative number up toward zero: int(-3.5) is −3, while -7 // 2 is −4. When you need a whole number from a negative value, decide which one you mean, and pick the tool that does it.
print((2 - 5) % 24)
Show the answer
21
2 − 5 is −3, and % 24 wraps it around the clock: 3 hours before midnight is 21:00, nine in the evening.
When did the flight leave?
A flight landed at hour 3 (3 a.m.) after 7 hours in the air. Set departure_hour to the hour it left, on a 24-hour clock from 0 to 23. Use % so it works for any landing time.
landing_hour = 3 flight_hours = 7 departure_hour = 0 print("Left at hour", departure_hour)
Negative numbers in AI
You'll see negatives all through the course. A model's raw scores, called logits, are often negative. A model's weights can be negative, which means the feature pushes the prediction down. During training, the direction to nudge each weight comes out as a positive or negative number, and the sign is the whole message: up or down. And the logarithm of a probability is always negative, which you'll meet when models are scored.
Reading the sign first is a habit worth building: before asking "how big?", ask "which way?" And when you compare negative numbers, remember the number line: a loss of −40 is worse than a loss of −10, even though 40 is the bigger number. Sorting a list of profits puts the biggest losses first, which is exactly what you want when you're looking for the products that are hurting most.
Show the answer
More days since the last order push the score down
A negative weight means that as the feature grows, its contribution to the score shrinks. The sign says which way; the size, 0.4, says how strongly.
old_rate = 8 new_rate = 6 print(new_rate - old_rate)
Show the answer
-2
New minus old is −2: a fall of 2 percentage points. The minus sign carries the direction, so you don't need a separate word for "down".
Practice what you just read
- 4 code examples you can edit and run
- a practice exercise that checks your code
- a 6-question quiz
- 5 review cards for spaced repetition
Try a quiz question
Which of these is positive?