Python Tutorial Python Advanced Python References Python Libraries

Python math - isclose() Function



The Python math.isclose() function returns True if the values a and b are close to each other and False otherwise. The two values are considered close using absolute and relative tolerances.

rel_tol is the relative tolerance and it is maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example - to set tolerance of 1%, rel_tol = 0.01 can be used. The default value of rel_tol is 1e-09. rel_tol must be greater than zero.

abs_tol is the minimum absolute tolerance. It is used to compare values near 0. The value must be at least 0. The default value of abs_tol is 0.0.

The result is compared using following formula: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).

NaN, inf, and -inf is handled according to IEEE rules. NaN is not considered close to any other value, including NaN. inf and -inf are considered close to each other.

Syntax

#New in version 3.5
math.isclose(a, b, rel_tol, abs_tol)   

Parameters

a Required. Specify the first value to check value for closeness.
b Required. Specify the second value to check value for closeness.
rel_tol Optional. Specify the relative tolerance. It is maximum allowed difference between a and b. Default value: 1e-09.
abs_tol Optional. Specify the absolute tolerance. It is used to compare values near 0. The value must be at least 0. Default value: 0.0.

Return Value

Returns True if the values a and b are close to each other, and False otherwise.

Example:

The example below shows the usage of isclose() function.

import math

print(math.isclose(100, 104))
print(math.isclose(100, 104, rel_tol = 0.05))
print(math.isclose(100, 100.0000000001))
print(math.isclose(100, 101, abs_tol = 2))

The output of the above code will be:

False
True
True
True

❮ Python Math Module