Python - abs vs fabs

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

First

abs(-5) 

Second

 import math math.fabs(-5) 

How do these methods differ?

+93
python
May 27 '12 at 7:16
source share
4 answers

math.fabs() converts its argument to float if it can (if it cannot, it throws an exception). Then it takes an 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 [7]: type(abs(-2)) Out[7]: int In [8]: type(abs(-2.0)) Out[8]: float In [9]: type(abs(3+4j)) Out[9]: float In [10]: type(math.fabs(-2)) Out[10]: float In [11]: type(math.fabs(-2.0)) Out[11]: float In [12]: 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 
+116
May 27 '12 at 7:21
source share

Edit: as @aix suggested, a better (fairer) way to compare speed differences:

 In [1]: %timeit abs(5) 10000000 loops, best of 3: 86.5 ns per loop In [2]: from math import fabs In [3]: %timeit fabs(5) 10000000 loops, best of 3: 115 ns per loop In [4]: %timeit abs(-5) 10000000 loops, best of 3: 88.3 ns per loop In [5]: %timeit fabs(-5) 10000000 loops, best of 3: 114 ns per loop In [6]: %timeit abs(5.0) 10000000 loops, best of 3: 92.5 ns per loop In [7]: %timeit fabs(5.0) 10000000 loops, best of 3: 93.2 ns per loop In [8]: %timeit abs(-5.0) 10000000 loops, best of 3: 91.8 ns per loop In [9]: %timeit fabs(-5.0) 10000000 loops, best of 3: 91 ns per loop 

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




In addition to what @aix said, another thing to keep in mind is the speed difference:

 In [1]: %timeit abs(-5) 10000000 loops, best of 3: 102 ns per loop In [2]: import math In [3]: %timeit math.fabs(-5) 10000000 loops, best of 3: 194 ns per loop 

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

+8
May 27 '12 at 7:22
source share

math.fabs() always returns a float, and abs() can return an integer.

+3
May 27 '12 at 7:22
source share

abs() : returns the absolute value according to the argument, i.e. if the argument is int, then it returns int; if the argument is float, it returns float. It also works with a complex variable, i.e. abs(a+bj) also works and returns an absolute value, i.e. math.sqrt(((a)**2)+((b)**2)

math.fabs() : only works with integer values โ€‹โ€‹or floating point values. Always returns an absolute floating-point value, regardless of the type of argument (except for complex numbers).

0
Feb 05 '18 at 13:46
source share



All Articles