The math.isclose()
function is used to determine whether two numerical values are close enough to be considered equal given a certain level of precision.
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Parameters
a |
The first value to be compared, it should be a real number. |
b |
The second value to be compare, it should also be a real number |
rel_tol |
An optional parameter that specifies the relative tolerance for the comparison. It defaults to 1e-09 |
abs_tol |
An optional parameter that specifies the absolute tolerance for the comparison, it defaults to 0.0 |
Return Value
This function returns True
if the two values passed in are considered close enough within the given tolerances, and False
otherwise.
import math
print(math.isclose(10.123456789, 10.123456788))
print(math.isclose(10, 11))
Let’s take a look at an example of using custom tolerance levels.
import math
print(math.isclose(10.123456788, 10.123456789, rel_tol=1e-4, abs_tol=1e-3))
print(math.isclose(10, 9.9, rel_tol = 0.5))
This function can be useful if precision is necessary when working with a large collection values.
import math
check_value = 15.0
list_of_floats = [12.98, 14.99, 15.00, 20.02, 10.04, 15.06, 15.08, 15.10, 15.125, 15.14, 24.16, 5.18, 15.20, 7.22, 15.24, 11.26, 15.28, 15.30, 15.32, 15.34, 14.48, 12.54, 15.56, 15.58, 15.60, 15.62, 15.64, 8.76, 17.18, 15.96, 10.32]
print(list(filter(lambda x: math.isclose(x, check_value, rel_tol=0.1), list_of_floats)))