Open In App

fabs() method of Python’s math Library

Last Updated : 23 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate 
# the working of fabs()
  
# for fabs()
import math
  
# initializing integer 
x = -2
  
# initializing float
y = -2.00
  
# printing magnitude and type of output
# type conversion to float
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")
  
# printing magnitude and type of output
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()




# Python3 code to demonstrate 
# the exception of fabs()
  
# for fabs()
import math
  
# initializing string
c = "gfg"
  
# initializing complex number
d = 4 + 2j
  
# checking for exceptions
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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads