Python Glossary Русский

all Python 3mathterm

math.fabs

absolute value

Returns the absolute value of a number as a float. Unlike abs(), it always returns a float, never an int.

Syntax

math.fabs(x)

In everyday code abs() is the right call: it keeps the type (int, Decimal, Fraction) and handles complex numbers, whereas fabs() coerces everything to float and raises TypeError on a complex argument. That coercion costs precision — a large int keeps only 53 bits of mantissa, and a huge one raises OverflowError outright. Reach for fabs() only when a float is what you want anyway, such as comparing against a tolerance.

Examples

import math
print(math.fabs(-5.0))  # → 5.0
print(math.fabs(3.14))  # → 3.14
print(math.fabs(-0.0))  # → 0.0
print(type(math.fabs(-3)))  # → <class 'float'> (abs(-3) вернул бы int)
print(math.fabs(-1e100))  # → 1e+100
print(math.fabs(0))  # → 0.0

See also

Open in the full glossarydocs.python.orgReport an inaccuracy