Question
Asked By – Mateusz Jagiełło
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?
Now we will see solution for issue: Python – abs vs fabs
Answer
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 [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/npe/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))
TypeError: can't convert complex to float
This question is answered By – NPE
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0