abs() vs fabs() function in Python
This tutorial will teach you about the working of abs() and fabs() method in Python and their differences. The primary purpose of both of these functions is to find the absolute value of a given positive or negative number. But these are a little different in their functioning. Let’s see more about abs() and fabs() functions further in this tutorial.
abs() vs fabs() method in Python
We will discuss these two functions separately in this tutorial.
Python abs() method is a built-in method and does not require importing any Python module. It has the following syntax.
In the above syntax, the number can be integer or float. The return type is the same as the input number. This method accepts a number as input and returns its absolute value. See the below implementation of the abs() method in Python.
number = 5.7 print(abs(number)) number = -18.9 print(abs(number)) number = 5 print(abs(number)) number = -4 print(abs(number))
5.7 18.9 5 4
Now let’s see how fabs() method behaves.
This function has the following syntax.
This method is defined in the math module of Python. Which is why we need to import the math module before using the fabs() method. To know about more methods in the math module, refer here: Math module of Python
Like the abs() method, this function also converts a given input number, which can be integer or float, into its absolute value. The only difference is that its return type is float. Therefore, irrespective of the given input number, the function returns a float value. Please have a look at the below python program to understand the concept. Here it is.
import math number = 5.7 print(math.fabs(number)) number = -18.9 print(math.fabs(number)) number = 5 print(math.fabs(number)) number = -4 print(math.fabs(number))
And the output is:
5.7 18.9 5.0 4.0
As you can see, we have imported the math module to use fabs() method in our program. And this function has returned the absolute value in float for the given inputs.
Thank you and keep coding.