Python - fabs() vs abs()

PythonServer Side ProgrammingProgramming

Both abs() and fabs() represent the mathematical functions which give us the absolute value of numbers. But there is a subtle difference between both of them which we can explore in the exmaples below.

Example

The abs() functions returns the absolute value as an integer or floating point value depending on what value was supplied dot it. But the fabs) function will always return the value as floating point irrespective of whether an integer or a floating point was supplied to it as a parameter.

 Live Demo

import math

n = -23
print(abs(n))
print(math.fabs(n))

n = 21.4
print(abs(n))
print(math.fabs(n))

n = complex(10,12)
print(abs(n))
#print(math.fabs(n)) – Causes error

Output

Running the above code gives us the following result −

23
23.0
21.4
21.4
15.620499351813308
raja
Published on 22-Jul-2020 08:32:11

Advertisements