fabs() is a method specified in math library in Python 2 and Python 3.
Sometimes while computing the difference between 2 numbers to compute the closeness of a number with the other number, we require to find the magnitude of certain number, fabs() can come handy in the cases where we are dealing with ints and want the result in float number to perform floating point comparisons further as fabs() converts its every magnitude to floating point value.
Syntax : fabs(x)
Parameters :
x : Number whose magnitude has to be computed.
Returns : Returns the magnitude of the element passed in the function. Always returns a floating point number, irrespective of the data type of the argument number.
Code #1 : Code to demonstrate fabs() working
import math
x = -2
y = -2.00
print("The magnitude of integer is : ", end ="")
print(math.fabs(x))
print("The type of output is : ", end ="")
print(type(math.fabs(x)))
print("\r")
print("The magnitude of float is : ", end ="")
print(math.fabs(y))
print("The type of output is : ", end ="")
print(type(math.fabs(y)))
|
Output :
The magnitude of integer is : 2.0
The type of output is :
The magnitude of float is : 2.0
The type of output is :
Exception :
There are many exceptions associated with this method, since it always returns a floating point number, this function throws an exception when python cannot convert the argument to floating point number. For eg. in case of string and complex numbers.
Code #2 : Code to demonstrate exceptions of fabs()
import math
c = "gfg"
d = 4 + 2j
try :
print("The absolute value of string is :")
print(math.fabs(c))
except Exception as e:
print("Error !! The error on passing string is :")
print(str(e))
print("\r")
try :
print("The absolute value of complex is :")
print(math.fabs(d))
except Exception as e:
print("Error !! The error on passing complex is :")
print(str(e))
|
Output :
The absolute value of string is :
Error !! The error on passing string is :
a float is required
The absolute value of complex is :
Error !! The error on passing complex is :
can't convert complex to float
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
23 Oct, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...