fabs() method of Python’s math Library
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)
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
The magnitude of integer is : 2.0 The type of output is : The magnitude of float is : 2.0 The type of output is :
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()
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