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
• 14,970 points
40 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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
• 56,120 points

Related Questions In Python

0 votes
1 answer

Difference between append vs. extend list methods in Python

append: Appends object at end. x = [1, ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,320 points
106 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
• 14,970 points
53 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
350 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
• 56,120 points
264 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
25 views
+4 votes
6 answers
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
• 56,120 points
18 views
+1 vote
2 answers

Python string formatting: % vs. .format

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

answered Apr 11 in Python by Dasa Ravi
31 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.