Python Python abs(): Return Absolute Value — Syntax, Complex Numbers, Errors,…
page info

본문

Python abs(): Absolute Value Function Explained
The built-in abs()
function returns the absolute value of a number. It supports integers, floats, and complex numbers, and works with custom numeric types that implement __abs__()
. This guide covers syntax, examples, performance notes, error handling, and real-world use cases to help you apply abs()
effectively.
Syntax
abs(x)
Parameter: A numeric value such as int
, float
, complex
, or an object implementing __abs__()
.
Returns: The absolute value of x
. For integers and floats, returns the same type; for complex numbers, returns a float
magnitude.
Quick examples
print(abs(-10)) # 10
print(abs(3.14)) # 3.14
print(abs(0)) # 0
print(abs(-0.0)) # 0.0
Complex numbers
For complex inputs, abs()
returns the modulus, computed as sqrt(real**2 + imag**2)
.
z = 3 + 4j
print(abs(z)) # 5.0
Custom numeric types
Implement __abs__()
to define absolute value behavior for your class.
class Distance:
def __init__(self, x):
self.x = x
def __abs__(self):
return self.x if self.x >= 0 else -self.x
d = Distance(-7)
print(abs(d)) # 7
Practical use cases
- Error and deviation: Measure differences without sign.
- Sorting by magnitude: Use as a key for consistent ordering.
- Numerical stability: Compare magnitudes in algorithms.
nums = [-3, -1, 2, 5]
print(sorted(nums, key=abs)) # [-1, 2, -3, 5]
Common errors and caveats
- Non-numeric types: Passing a string or list raises
TypeError
. - Large integers: Python integers are arbitrary precision; no overflow occurs.
- Floating point: Beware of rounding errors; extremely small values may approach zero.
try:
print(abs("10"))
except TypeError as e:
print(e) # bad operand type for abs(): 'str'
Performance and alternatives
- Single values: Built-in
abs()
is implemented in C and is very fast. - Arrays: Use
numpy.abs
for vectorized numerical data. - Conditional equivalence:
x if x >= 0 else -x
is equivalent but less clear; preferabs()
.
FAQ
- Does
abs()
handle negative zero? - Yes.
abs(-0.0)
returns0.0
. - What does
abs()
return for complex numbers? - A
float
representing the magnitude of the complex number. - Can I use
abs()
with custom objects? - Yes, if the object implements
__abs__()
.
Related keywords
Python abs, absolute value, complex modulus, TypeError, numerical stability, numpy.abs, sorting key, floating point
comment list
There are no registered comments.