Python | fabs () vs abs ()

fabs | Python Methods and Functions

Syntax abs ()

 abs (number) 

Syntax fabs ()

 math.fabs (number) 

Both will return the absolute value of the number.

The difference is that math.fabs (number) will always return a floating point number, even if the argument is an integer a number, whereas abs () will return a floating point or an integer depending on the argument.

In case the argument is a complex number, abs () will return a part of the value, where like fabs () will return an error .

To use the fabs () function, we need to import the math library.

# Python code to demonstrate how it works
# fabs () and abs ()

import math

 
################################
# When the argument is an integer #
######################### ########

number = - 10

  
# abs () will return an integer as
# the argument is an integer

print ( abs (number))

 
# fabs () will return a float

print (math.fabs (number))

 
################################## ########
# When input is floating point #
################### ########################

number = - 12.08

 
# abs () will return a floating point number
# a number is used as an argument floating point

print ( abs (number))

 
# fabs () will return a floating point number

print (math.fabs (number))

 
############### ######################
# When the input is a complex number #
#################### ################

number = complex ( 3 , 4 )

  
# abs () will return the value

print ( abs (number))

  
# fabs () will return an error
# print (math.fabs (number))

Output:

 10 10.0 12.08 12.08 5.0 




Python | fabs () vs abs (): StackOverflow Questions

Python - abs vs fabs

I noticed that in python there are two similar looking methods for finding the absolute value of a number:

First

abs(-5)

Second

import math
math.fabs(-5)

How do these methods differ?

Tutorials