Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 fabs() Function

Python3 fabs() Function

Python3 Numbers Python3 Numbers


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:


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


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

)

print

(

y

)

Outputs 1.5

x

=

10

y

=

math

.

fabs

(

x

)

print

(

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

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(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 Python3 Numbers