Python 3 – Number fabs() Method
In Python, there is a built-in method named fabs() which is used to get the absolute value of a number. The number can be an integer, a float or even a complex number. The fabs() method is available in the math module in Python.
Syntax of fabs() method:
math.fabs(x)
The fabs() method takes only one argument. It returns the absolute value of the given number. If the number is positive, the same number will be returned. If the number is negative, the absolute value of that number will be returned.
Example 1: Finding Absolute Value of a Number
import math
# Taking integer input from user
number = int(input("Enter an integer: "))
# Calling fabs() method to get absolute value
absolute_value = math.fabs(number)
# Displaying the result
print("The absolute value of {} is {}".format(number, absolute_value))
Output:
Enter an integer: -10
The absolute value of -10 is 10.0
Example 2: Finding Absolute Value of a Float Number
import math
# Taking float input from user
number = float(input("Enter a float number: "))
# Calling fabs() method to get absolute value
absolute_value = math.fabs(number)
# Displaying the result
print("The absolute value of {} is {}".format(number, absolute_value))
Output:
Enter a float number: -7.5
The absolute value of -7.5 is 7.5
Example 3: Finding Absolute Value of a Complex Number
import math
# Taking complex number from user
number = complex(input("Enter a complex number: "))
# Calling fabs() method to get absolute value
absolute_value = math.fabs(number)
# Displaying the result
print("The absolute value of {} is {}".format(number, absolute_value))
Output:
Enter a complex number: -8+6j
The absolute value of (-8+6j) is 10.0
In the above examples, we have used the fabs() method to get the absolute value of a number. The method works fine for all types of numbers, including integers, floats, and complex numbers.
Conclusion
The fabs() method is a built-in method in Python which returns the absolute value of a number. It is useful when you want to find the distance between two values or get the magnitude of a complex number. The method is available in the math module and is easy to use.