Absolute Value
The absolute value of a number is its distance from zero, ignoring direction. Both 6 and −6 are 6 steps from zero, so both have absolute value 6. It is a small idea with a big job: whenever a program asks "how far?" or "how big is the error?" rather than "which way?", absolute value is involved.
Definition
The absolute value of is written (vertical bars on both sides):
The second line looks odd at first: how can be positive? Because when is negative, is its opposite, which is positive. For : .
| 9 | 0 | −2.5 | −100 | ||
|---|---|---|---|---|---|
| 9 | 0 | 2.5 | 100 |
Absolute value is never negative, and it is 0 only for 0 itself.
In Python it is the built-in function abs, which works for ints, floats and fractions:
from fractions import Fraction
for x in [9, 0, -2.5, -100, Fraction(-3, 4)]:
print(f"abs({x}) = {abs(x)}")
def my_abs(x): # the definition, written out
return x if x >= 0 else -x
print(my_abs(-6), my_abs(6))abs(9) = 9
abs(0) = 0
abs(-2.5) = 2.5
abs(-100) = 100
abs(-3/4) = 3/4
6 6
Distance between two numbers
The distance between and on the number line is . It doesn't matter which you subtract from which, because .
This is the most common use of absolute value in practice. "Is within 0.5 of 10?" becomes , which is the same as .
Rules worth knowing
| Rule | Example |
|---|---|
| (triangle inequality) |
Watch out: absolute value does not split over addition. , but . The two are equal only when and have the same sign (or one is zero). The triangle inequality says the sum's size can never be more than the sizes added: going 5 steps right and 3 steps left can't take you further than 8 steps from where you started.
import random
rng = random.Random(3)
always_ok = True
for _ in range(1000):
a, b = rng.randint(-50, 50), rng.randint(-50, 50)
if abs(a * b) != abs(a) * abs(b) or abs(a + b) > abs(a) + abs(b):
always_ok = False
print("rules held in 1000 random tests:", always_ok)
print(abs(5 + -3), abs(5) + abs(-3))rules held in 1000 random tests: True
2 8
Solving number
has two solutions, and , the two points at distance 4 from zero. has one solution (0), and has none, because a distance can't be negative. Similarly means " is 3 away from 10": or .
In software
- Comparing floats: because floats carry tiny rounding errors, code checks
abs(a - b) < toleranceinstead ofa == b. Python'smath.isclosedoes this for you. - Errors in machine learning: the mean absolute error averages over many examples; it tells you how far off a model is, typically.
- Grid distance: on a city-block or tile map, the number of moves from to without diagonals is , the Manhattan distance, used by path-finding in games.
- Dead zones: a game ignores joystick input when so a slightly worn stick doesn't make the character drift.
import math
print(0.1 + 0.2 == 0.3, abs((0.1 + 0.2) - 0.3) < 1e-9, math.isclose(0.1 + 0.2, 0.3))
predictions = [12, 15, 9, 20]
truth = [10, 15, 11, 25]
errors = [abs(p - t) for p, t in zip(predictions, truth)]
print("errors:", errors, " mean absolute error:", sum(errors) / len(errors))
player, goal = (2, 7), (6, 4)
print("tile moves:", abs(player[0] - goal[0]) + abs(player[1] - goal[1]))False True True
errors: [2, 0, 2, 5] mean absolute error: 2.25
tile moves: 7
Exercises
Exercise 1: Evaluate
Compute (a) (b) (c) (d)
Answer
(a) 15 (b) 12 (c) −3 (d) 20
Solution
Exercise 2: Solve
Find every with (a) (b) (c)
Answer
(a) 9 or −9 (b) 7 or −3 (c) no solution
Solution
(a) the two points 9 steps from 0. (b) " is 5 away from 2": or . (c) an absolute value can never be negative.
print([x for x in range(-20, 21) if abs(x - 2) == 5])[-3, 7]
Exercise 3: Within tolerance
A bolt should be 40 mm long, with a tolerance of 0.2 mm. Which of these lengths pass: 39.85, 40.25, 40.2, 39.7? Write the test as one absolute-value inequality.
Answer
. 39.85 and 40.2 pass; 40.25 and 39.7 fail.
Solution
✓, ✗, ✓ (equal is allowed), ✗. In code, add a tiny allowance so the float rounding of doesn't wrongly fail the edge case:
for length in [39.85, 40.25, 40.2, 39.7]:
print(length, abs(length - 40) <= 0.2 + 1e-9)39.85 True
40.25 False
40.2 True
39.7 False
Exercise 4: Closest to target
Write code that finds which number in [17, -4, 31, 22, 9] is closest to 20.
Answer
22 (distance 2)
Solution
"Closest" means smallest . Python's min accepts a key that says what to compare:
nums = [17, -4, 31, 22, 9]
print([abs(x - 20) for x in nums])
print(min(nums, key=lambda x: abs(x - 20)))[3, 24, 11, 2, 11]
22
Test yourself
What is ?
- −8
- 8
- 14
- −14
How many solutions does have?
- None
- One
- Two
- Infinitely many
Which is always true for any numbers and ?