Using math.isclose function with values close to 0 Using math.isclose function with values close to 0 python-3.x python-3.x

Using math.isclose function with values close to 0


The answer can be worked out by reading the documentation.

math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)

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

Whether or not two values are considered close is determined according to given absolute and relative tolerances.

rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that 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.

If no errors occur, the result will be:

abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

You use default tolerances which means that a relative tolerance check is used. And the equation above makes it clear why your expressions evaluates false.

Consider the final expression in the question:

math.isclose(1.0e-100 , 0.0)

Plug these values into the expression from the documentation and we have

1.0e-100 <= max(1.0e-9 * 1.0e-100, 0.0)

I think it should be obvious that when performing a relative tolerance comparison, using default tolerances, no non-zero value is deemed close to zero.

For very small values you should perhaps use an absolute tolerance.

Or you should re-write the test to avoid comparing against zero.