math.fabs(x) returns the absolute value (distance from zero) of a real number x, always as a float.
Unlike Python's built-in abs(), which preserves int types and accepts complex numbers, math.fabs() rejects complex values with TypeError and converts integers such as -7 to 7.0.
math.fabs() is a function in Python's standard math module: import it with import math and call math.fabs(...), or import the name directly with from math import fabs.
Syntax
Import math and pass any real number.
python
import math
mag = math.fabs(x)
Call
What it does
math.fabs(-7)
Returns 7.0 (float, unlike abs(-7)).
math.fabs(-3.5)
Returns 3.5.
math.fabs(-0.0)
Returns 0.0 (sign bit cleared).
math.fabs(float("-inf"))
Returns inf.
For general Python code, built-in abs() is preferred because it works on ints, floats, complex numbers, Decimal, and custom objects.
NaN remains NaN. Checking with math.isnan() confirms NaN stays NaN.
Frequently Asked Questions
abs() is built in, keeps ints as ints, works on complex numbers, and delegates to __abs__. math.fabs() always returns a float and only accepts real numbers.
5.0 (a float).
No, passing a complex number raises TypeError. Use built-in abs() instead.
Positive 0.0 with its sign bit cleared.
If given a huge Python integer larger than the maximum 64-bit float (~1.8e308). Built-in abs() never overflows on ints.