Python fabs() Function
Description
The fabs() method returns the absolute value of a number as a floating-point number, e.g., math.fabs(-10) returns 10.0.
Syntax
The following is the syntax of the fabs() method:
import math math.fabs( x )
Note:fabs() is not accessible directly; you need to import the math module and invoke this method through a static object.
Parameters
- x -- A numeric expression.
Return Value
Returns the absolute value of the number as a floating-point number.Examples
The following demonstrates an example of using the fabs() method:
Example 1
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
x = -1.5
y = math.fabs(x)
print(y) # Output 1.5
x = 10
y = math.fabs(x)
print(y) # Output 10.0
In the above examples,fabs(-1.5)returned 1.5, the absolute value of -1.5,fabs(10)returned 10.0, the absolute value of 10. Note that the return value is always a floating-point number, even if the passed argument is an integer.
After running the above examples, the output result is:
1.5 10.0
Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math # Import the math module
print "math.fabs(-45.17) : ", math.fabs(-45.17)
print "math.fabs(100.12) : ", math.fabs(100.12)
print "math.fabs(100.72) : ", math.fabs(100.72)
print "math.fabs(119L) : ", math.fabs(119L)
print "math.fabs(math.pi) : ", math.fabs(math.pi)
After running the above example, the output result is:
math.fabs(-45.17) : 45.17 math.fabs(100.12) : 100.12 math.fabs(100.72) : 100.72 math.fabs(119L) : 119.0 math.fabs(math.pi) : 3.14159265359Other Extensions
Python Numbers