Python - abs vs fabs

0 votes

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?

Sep 19, 2018 in Python by bug_seeker
• 15,510 points
704 views

1 answer to this question.

0 votes

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/alexei/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))

TypeError: can't convert complex to float
answered Sep 19, 2018 by Priyaj
• 58,020 points

Related Questions In Python

+1 vote
3 answers

Difference between append vs. extend list methods in Python

Python append() method adds an element to ...READ MORE

answered Aug 21, 2019 in Python by germyrinn
• 240 points
96,920 views
0 votes
1 answer

Difference between append vs. extend list methods in Python

append: Appends object at the end. x = ...READ MORE

answered Aug 8, 2018 in Python by bug_seeker
• 15,510 points
2,275 views
+7 votes
8 answers

Difference for string comparison in Python: 'is' vs. ==

If we use "==" means both variables ...READ MORE

answered Sep 3, 2018 in Python by Parul Raheja
2,527 views
0 votes
1 answer

Python vs Cpython

So what is CPython? CPython is the original ...READ MORE

answered Aug 29, 2018 in Python by Priyaj
• 58,020 points
11,997 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,468 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,128 views
0 votes
1 answer

Python string formatting: % vs. .format

To answer your first question... .format just ...READ MORE

answered Aug 17, 2018 in Python by Priyaj
• 58,020 points
1,041 views
+1 vote
2 answers

Python string formatting: % vs. .format

Using Python format() function is what the ...READ MORE

answered Apr 11, 2019 in Python by Dasa Ravi
1,466 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP