Get Absolute Values in Python: abs(), math.fabs()

Modified: | Tags: Python, Numeric

In Python, you can get the absolute value of a number using either the built-in abs() function or the math module's fabs() function.

Get Absolute Values of Integers with abs()

Passing an integer (int) to abs() returns its absolute value as an int.

print(abs(100))
# 100

print(abs(-100))
# 100

print(type(abs(100)))
# <class 'int'>
source: abs_usage.py

Get Absolute Values of Floating-Point Numbers with abs()

Passing a floating-point number (float) to abs() returns its absolute value as a float.

print(abs(1.23))
# 1.23

print(abs(-1.23))
# 1.23

print(type(abs(1.23)))
# <class 'float'>
source: abs_usage.py

Get Absolute Values of Complex Numbers with abs()

In Python, you can represent complex numbers using j as the imaginary unit.

Passing a complex number (complex) to abs() returns its absolute value (also known as its modulus or magnitude) as a float.

print(abs(1 + 1j))
# 1.4142135623730951

print(abs(3 + 4j))
# 5.0

print(type(abs(3 + 4j)))
# <class 'float'>
source: abs_usage.py

The __abs__() Special Method

When abs() is called, it internally invokes the object's special method __abs__(). In other words, abs(x) is equivalent to x.__abs__().

print((-100).__abs__())
# 100

print((-1.23).__abs__())
# 1.23

print((3 + 4j).__abs__())
# 5.0
source: abs_usage.py

If you try to use abs() with an object that doesn't implement __abs__(), such as a list, you'll get a TypeError.

l = [-2, -1, 0, 1, 2]

print(hasattr(l, '__abs__'))
# False

# print(abs(l))
# TypeError: bad operand type for abs(): 'list'
source: abs_usage.py

You can use the built-in hasattr() function to check if an object has a specific attribute or method.

You can also implement __abs__() in your custom classes to define how abs() should work with them. Here's a simple example where abs() always returns 100:

class MyClass:
    def __abs__(self):
        return 100

mc = MyClass()

print(abs(mc))
# 100
source: abs_usage.py

Convert List Elements to Absolute Values

To convert all elements in a list to their absolute values, you can use a list comprehension with abs().

l = [-2, -1, 0, 1, 2]

print([abs(i) for i in l])
# [2, 1, 0, 1, 2]
source: abs_usage.py

Alternatively, NumPy's np.abs() can convert list elements to their absolute values.

Difference Between math.fabs() and abs()

math.fabs() also returns the absolute value, but unlike abs(), it always returns a floating-point number (float). Even when given an int, math.fabs() returns a float.

import math

print(math.fabs(-100))
# 100.0

print(type(math.fabs(-100)))
# <class 'float'>

print(math.fabs(-1.23))
# 1.23

print(type(math.fabs(-1.23)))
# <class 'float'>
source: math_fabs.py

math.fabs() only supports real numbers. Attempting to use it with a complex number (complex) will raise a TypeError.

# print(math.fabs(3 + 4j))
# TypeError: must be real number, not complex
source: math_fabs.py

Since math.fabs() does not rely on __abs__(), it won't work with custom classes that implement it.

class MyClass:
    def __abs__(self):
        return 100

mc = MyClass()

# math.fabs(mc)
# TypeError: must be real number, not MyClass
source: math_fabs.py

Related Categories

Related Articles