Float,How Do You Compare Two Floats In Python

strange phenomenon

i was talking to a colleague the other day, inside the computer float comparison is a dirty business. for example, ,0.1+0.2 i'm not going to get 0. 3?

>>> 0.1+0.2 0.30000000000000004 why such a silly result ?

this article in a nutshell, the numbers in a computer are stored in binary , some numbers in the computer cannot be saved accurately, so the nearest number is saved 。

there is also a problem in the decimal system where numbers do not accurately represent images 1/3 that's the number, so you have to round it 0.33 something like that - you can't count on zero. 33 + 0.33 + 0.33 it adds up to 1.

so we're comparing two floats to see if they're equal , you can't just rely on == but when the difference between them is less than a small value that we can tolerate , you can think of them as equal.

Python how to solve the problem ?

there's a similar process in all languages, python and that's how it's handled ?StackOverFlow there are similar problems : what-is-the-best-way-to-compare-floats-for-almost-equality-in-python

a rough and easy way to judge

return abs(f1 - f2) <= allowed_error

python3.5 after that, PEP485 a solution is given in the proposal. the use of math. isclose method, pass in the two numbers to be compared and the acceptable precision difference 。

PEP 485: A function for testing approximate equality

PEP 485 adds the math.isclose() and cmath.isclose() functions which tell whether two values are approximately equal or “close” to each other. Whether or not two values are considered close is determined according to given absolute and relative tolerances. Relative tolerance is the maximum allowed difference between isclose arguments, relative to the larger absolute value:

math.isclose method of use

>>> import math >>> a = 5.0 >>> b = 4.99998 >>> math.isclose(a, b, rel_tol=1e-5) True >>> math.isclose(a, b, rel_tol=1e-6) False It is also possible to compare two values using absolute tolerance, which must be a non-negative value: >>> import math >>> a = 5.0 >>> b = 4.99998 >>> math.isclose(a, b, abs_tol=0.00003) True >>> math.isclose(a, b, abs_tol=0.00001) False

Tag » Approximate Equal Python