Python | fabs() vs abs()

Both the abs() and the fabs() function is used to find the absolute value of a number.

Syntax of abs()

abs(number)

Syntax of fabs()



math.fabs(number)

Both will return the absolute value of number.

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

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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate working
# of 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 floating point number
print(math.fabs(number))
  
###########################################
# When the input is a floating point number#
########################################### 
number = -12.08
  
# abs() will return an floating point number
# as the argument is a floating point number
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 magnitude
print(abs(number))
  
# fabs() will return an error
# print(math.fabs(number))

chevron_right


Output:

10
10.0
12.08
12.08
5.0


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nidhi_biet