Python fabs() function
Description
The fabs() method returns the absolute value of a number as a float; for example, math.fabs(-10) returns 10.0.
Syntax
The syntax of the fabs() method is as follows:
import math
math.fabs( x )
**Note:** fabs() cannot be accessed directly; you need to import the math module and call the method through the static object.
Parameters
- x -- a numeric expression.
Return Value
Returns the absolute value of a number as a float.
Example
The following shows examples of using the fabs() method:
Example 1
#!/usr/bin/python
-- coding: UTF-8 --
import
math
x
= -
1.5
y
=
math
.
fabs
(
x
)
(
y
)
Outputs 1.5
x
=
10
y
=
math
.
fabs
(
x
)
(
y
)
Outputs 10.0
In the example above, fabs(-1.5) returns the absolute value of -1.5, which is 1.5, and fabs(10) returns the absolute value of 10, which is 10.0. Note that the return value is always a float, even if the argument is an integer.
Running the example above produces:
1.5
10.0
Example
#!/usr/bin/python
-- coding: UTF-8 --
import
math
Import the math module
"
math.fabs(-45.17) :
"
,
math
.
fabs
(
45.17
)
"
math.fabs(100.12) :
"
,
math
.
fabs
(
100.12
)
"
math.fabs(100.72) :
"
,
math
.
fabs
(
100.72
)
"
math.fabs(119L) :
"
,
math
.
fabs
(
119L
)
"
math.fabs(math.pi) :
"
,
math
.
fabs
(
math
.
pi
)
Running the example above produces:
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.14159265359
Python Numbers