🕯️ Magic Note
The abs() function returns the absolute value (non negative) of a number. For example, abs(5 – 3) and abs(3 – 5) both return 2. It removes the sign, leaving only the distance. Comparing this distance to a threshold with < turns a vague idea of “close enough” into a concrete boolean condition. The result is True when the difference becomes irrelevant.
- abs() works on integers, floats, and complex numbers
- The threshold value can be any non negative number
- Common use cases: comparing floating point numbers, checking if a value is within a tolerance
- Use <= instead of < if equality should also count as close enough
| gifts | love | abs(gifts - love) | value | Result |
|---|---|---|---|---|
| 10 | 10 | 0 | 1 | True (0 < 1) |
| 8 | 10 | 2 | 1 | False (2 < 1 is false) |
| 9.5 | 10 | 0.5 | 0.5 | False (0.5 < 0.5 is false, use <= for inclusive) |
| 9.5 | 10 | 0.5 | 0.6 | True |
| 15 | 5 | 10 | 2 | False |
Python
# Checking if two values are close enough
gifts = 9.7
love = 10.0
threshold = 0.5
is_christmas = abs(gifts – love) < threshold
print(is_christmas)
# Output: True (0.3 < 0.5)
Python
# Floating point comparison without tolerance (dangerous)
a = 0.1 + 0.2
b = 0.3
print(a == b)
# Output: False (due to floating point precision)
# Safe comparison with tolerance
tolerance = 1e-10
print(abs(a – b) < tolerance)
# Output: True
Python
# Using a threshold to check if a number is approximately zero
values = [0.0001, 0.001, 0.01, 0.1]
threshold = 0.005
for v in values:
if abs(v) < threshold:
print(f”{v} is practically zero”)
else:
print(f”{v} is significant”)
# Output: 0.0001 is practically zero
# Output: 0.001 is practically zero
# Output: 0.01 is significant
# Output: 0.1 is significant
- Using == for floating point numbers that result from calculations, leading to unexpected False even for mathematically equal values
- Choosing a threshold that is too strict (like 1e-30) on normal scale data, causing the condition to never be true
- Forgetting that abs() on large numbers might still be large; use relative tolerance when comparing numbers of different magnitudes
⚡ Whisper
Gifts and love do not need to be the same. They need to be close enough. Close enough to matter. The distance is measured not in numbers but in meaning. When the gap shrinks below a silent threshold, you open your heart. Christmas is not about perfection. It is about what you choose to celebrate.