Home »
Python
Difference between abs() and fabs() methods in Python
Python abs() vs fabs() methods: Here, we are going to learn what is the difference between abs() and fabs() methods in Python?
Submitted by IncludeHelp, on April 17, 2019
In python, abs() method and fabs() method both are used to find the absolute value of a number. They are used for the same purpose but they have a difference, which we are going to discuss in this tutorial.
Python abs() method
abs() method is a built-in method in python – it accepts a number and returns the absolute value of the given number.
abs() method can accept positive or negative integer value, positive or negative float value and returns an absolute value based on the given number type. If the number is an integer it returns an integer value, if the number is a float it returns a float value.
Syntax:
abs(n)
Python code to demonstrate example of abs() method
# Python code to demonstrate example of
# abs() method
a = 10 # +ve integer
b = -10 # -ve integer
c = 10.23 # +ve float
d = -10.23 # -ve float
# printing absolute values using abs() method
print("abs(a): ", abs(a))
print("abs(b): ", abs(b))
print("abs(c): ", abs(c))
print("abs(d): ", abs(d))
Output
abs(a): 10
abs(b): 10
abs(c): 10.23
abs(d): 10.23
See the output – Values of a and b are integers, thus, their absolute values are also integers. Values of c and d are floats, thus, their absolute values are also float values.
Python fabs() method
fabs() method is also a built-in function but it is defined in math module, so to use fabs() method, we need to import math module first.
The fabs() method is also used to find the absolute value of a given number, it also accepts a number and returns the absolute value of the given number.
fabs() method can accept positive or negative integer value, positive or negative float value and returns the absolute value of float type.
Syntax:
math.fabs(n)
Python code to demonstrate example of fabs() method
# Python code to demonstrate example of
# fabs() method
# importing math module
import math
a = 10 # +ve integer
b = -10 # -ve integer
c = 10.23 # +ve float
d = -10.23 # -ve float
# printing absolute values using abs() method
print("fabs(a): ", math.fabs(a))
print("fabs(b): ", math.fabs(b))
print("fabs(c): ", math.fabs(c))
print("fabs(d): ", math.fabs(d))
Output
fabs(a): 10.0
fabs(b): 10.0
fabs(c): 10.23
fabs(d): 10.23
Difference between abs() and fabs() methods
There are mainly two differences between abs() and fabs() methods,
- abs() method is a standard built-in method, for this, there is no need to import a module. But, the fabs() method is defined in the math module, for this we need to import the math module first.
- abs() method returns either an integer value or a float value based on given number type. But, fabs() method returns only float value, no matter given number is an integer type or a float type.