For an int or float, abs(x) simply strips the sign, so the absolute value of -7 and 7 are both 7. For a complex number, it instead returns the magnitude — the distance from the origin in the complex plane, computed as the square root of the sum of the squares of the real and imaginary parts — rather than a sign-stripped complex number, since 'negative' isn't meaningful for complex values.
1Understanding abs()
For an int or float, abs(x) simply strips the sign, so the absolute value of -7 and 7 are both 7. For a complex number, it instead returns the magnitude — the distance from the origin in the complex plane, computed as the square root of the sum of the squares of the real and imaginary parts — rather than a sign-stripped complex number, since 'negative' isn't meaningful for complex values.
Subtracting two numbers and taking abs() of the result is the idiomatic way to get the distance between them regardless of which one is larger.
print(abs(-15))
print(abs(15))
print(abs(-3.7))2Practical Example
Here is a real-world application of abs() showing how it is used in production Python code.
target = 100
actual = 87
if abs(target - actual) > 5:
print("Reading is out of tolerance")
else:
print("Reading is within tolerance")3Best Practices
Follow these guidelines when working with abs():
1. Use abs(a - b) to measure distance/difference between two values instead of an if/else that picks the larger minus the smaller
2. Define __abs__() on a custom numeric class if you want it to support abs()
3. Combine abs() with a tolerance and comparison, or math.isclose, rather than == when checking if a float is 'close enough' to a target
Tip: Subtracting two numbers and taking abs() of the result is the idiomatic way to get the distance between them regardless of which one is larger.
print(abs(-15))
print(abs(15))
print(abs(-3.7))