Python3 fabs() Function
Description
The fabs() method returns the absolute value of a number as a float; for example math.fabs(-10) returns 10.0.
The fabs() function is similar to abs(), but there are two differences:
-
abs() is a built-in function. fabs() is defined in the math module.
-
fabs() only works with float and integer values. abs() can also be applied to complex numbers.
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, which can be an integer, float, etc. The function returns the absolute value of x, i.e. a nonnegative number..
Return Value
Returns the absolute value of a number.
Example
The following shows examples of using the fabs() method:
Example 1
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 2
#!/usr/bin/python3
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(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(math.pi) : 3.141592653589793
Python3 Numbers