Using the math.isclose function with values ​​close to 0

As you know, due to the binary representation of numbers, this expression evaluates to False(at least in Python):

0.2 + 0.4 == 0.6

To be able to verify equality in numerical errors, the module mathoffers isclose:

import math
math.isclose(0.2 + 0.4 , 0.6)

This last expression gives Trueas expected.

Now why again the following expression False?

math.isclose(0.2 + 0.4 - 0.6 , 0.0)

It seems like everything is compared to 0.0equalFalse

math.isclose(1.0e-100 , 0.0)
+4
source share
1 answer

The answer can be worked out by reading the documentation .

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

True, a b , False - .

.

rel_tol - - a b a b. , 5%, rel_tol = 0,05. - 1-09, , . rel_tol .

abs_tol - - . abs_tol .

, :

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

, , . , false.

:

math.isclose(1.0e-100 , 0.0)

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

, , , , .

, , .

, .

+8

Source: https://habr.com/ru/post/1628198/


All Articles