The Python Oracle

testing for numeric equality when variable is modified inside loop

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island

--

Chapters
00:00 Testing For Numeric Equality When Variable Is Modified Inside Loop
00:56 Accepted Answer Score 7
02:13 Answer 2 Score 4
02:59 Thank you

--

Full question
https://stackoverflow.com/questions/3834...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #floatingpoint

#avk47



ACCEPTED ANSWER

Score 7


The problem is that binary floating point arithmetic is not precise so you will get small errors in the calculations. In particular the number 0.1 has no exact binary representation. When you calculate using floating point numbers the very small errors cause the result to be slightly incorrect from what you might expect and that makes the equality test fail.

This small error might not be visible when printing the float with the default string representation. Try using repr instead, as this gives a slightly more accurate representation of the number (but still not 100% accurate):

>>> print(repr(t))
4.999999999999998
>>> print(t == 5.)
False

To get an accurate string representation of a float you can use the format method:

>>> print '{0:.60f}'.format(t)
4.999999999999998223643160599749535322189331054687500000000000
>>> print '{0:.60f}'.format(0.1)
0.100000000000000005551115123125782702118158340454101562500000

A general rule with floating point arithmetic is to never make equality comparisons.

The reason why it works when you used 0.5 is because 0.5 does have an exact representation as a binary floating point number so you don't see any problem in that case. Similarly it would work for 0.25 or 0.125.

If you need precise calculations you can use a decimal type instead.

from decimal import Decimal    
step = Decimal('0.1')

t = Decimal(0)
while t < Decimal(5):  
    t += step 

print(t)
print(t == Decimal(5))

Result:

5.0
True



ANSWER 2

Score 4


NEVER try to test floats for equality.

Floats are often not exactly what you inputted them to be.

In [43]: .1
Out[43]: 0.10000000000000001

So it's much safer to only test floats with inequalities. If you need to test if two floats are nearly equal, use a utility function like near:

def near(a,b,rtol=1e-5,atol=1e-8):
    try:
        return abs(a-b)<(atol+rtol*abs(b))
    except TypeError:
        return False

The rtol parameter allows you to specify relative tolerance. (abs(a-b)/abs(b)) < rtol

The atol parameter allows you to specify absolute tolerance. abs(a-b) < atol

So for example, you could write

t = 0.  
while t<4.9:  
    t = t + 0.1  
    if near(t,1.):
        print('Hiya')