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,350 points
66 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
• 56,920 points

Related Questions In Python

+1 vote
2 answers

Difference between append vs. extend list methods in Python

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

answered Aug 21 in Python by germyrinn
• 180 points
254 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,350 points
143 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
487 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,920 points
784 views
+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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 343 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,920 points
33 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
77 views