# Python - abs vs fabs

### Question

I noticed that in python there are two similar looking methods for finding the absolute value of a number:

First

``````abs(-5)
``````

Second

``````import math
math.fabs(-5)
``````

How do these methods differ?

1
101
2/22/2014 4:46:24 PM

`math.fabs()` converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.

In addition to floats, `abs()` also works with integers and complex numbers. Its return type depends on the type of its argument.

``````In : type(abs(-2))
Out: int

In : type(abs(-2.0))
Out: float

In : type(abs(3+4j))
Out: float

In : type(math.fabs(-2))
Out: float

In : type(math.fabs(-2.0))
Out: float

In : type(math.fabs(3+4j))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/alexei/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))

TypeError: can't convert complex to float
``````
122
9/19/2015 5:47:26 PM

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

``````In : %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In : from math import fabs

In : %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In : %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In : %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In : %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In : %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In : %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In : %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop
``````

So it seems `abs()` only has slight speed advantage over `fabs()` for integers. For floats, `abs()` and `fabs()` demonstrate similar speed.

In addition to what @aix has said, one more thing to consider is the speed difference:

``````In : %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In : import math

In : %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop
``````

So `abs()` is faster than `math.fabs()`.