Python math.isclose() Method
Python math.isclose() The method checks whether two values are close to each other, returning True if they are close and False otherwise.
math.isclose() Determines whether two values are considered close based on given absolute and relative tolerances.
Python version: 3.5
The formula is:
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
Syntax
The syntax of the math.isclose() method is as follows:
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Parameter Description:
- a -- required, a number. If x is not a number, a TypeError is returned. If the value is 0 or negative, a ValueError is returned.
- b -- required, a number. If x is not a number, a TypeError is returned. If the value is 0 or negative, a ValueError is returned.
- rel_tol -- is the relative tolerance, the maximum allowed difference between a and b relative to the larger absolute value of a or b. For example, to set a 5% tolerance, pass rel_tol=0.05. The default tolerance is 1e-09, ensuring the two values are the same within about 9 decimal digits. rel_tol must be greater than zero.
- abs_tol -- is the minimum absolute tolerance, useful for comparisons near zero. abs_tol must be at least zero.
Return Value
Returns a Boolean checking whether two values are close to each other; True if they are close, otherwise False.
Example
The following example checks whether two values are close to each other:
Example
Import the math package
import
math
Output whether the two values are close
(
math
.
isclose
(
8.005
,
8.450
,
abs_tol
=
0.4
)
)
(
math
.
isclose
(
8.005
,
8.450
,
abs_tol
=
0.5
)
)
Output result:
False
True
The following example checks whether two floating-point numbers are close:
Example
Import the math package
import
math
Can be used for floating-point comparisons
This outputs false, because 0.1+0.2 does not equal 0.3
(
0.1
0.2
==
0.3
)
(
0.1
0.2
)
This outputs true
(
math
.
isclose
(
0.1
0.2
,
0.3
)
)
Output result:
False
0.30000000000000004
True
Python math Module