Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I saw that in python there are two similar-looking functions for calculating the absolute value of a number:

#First

abs(-5)

#Second

import math

math.fabs(-5)

How do these functions vary?

1 Answer

0 votes
by (108k points)

Please be informed that math.fabs() change its parameter to float data if it can (if it can't, it throws an exception). It then takes the absolute value and returns the result as float data.

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

Want to be a Python expert? Join this Python Training course by Intellipaat to learn more.

 

Related questions

0 votes
1 answer
asked Feb 25, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
0 answers
asked Feb 25, 2021 in Python by ashely (50.2k points)

Browse Categories

...