Python 2.7 >= operator

Just started using Python and can't for the life of me understand why this loop is only running twice and not three times

x = 0.03

while(x - 0.01 >= 0):

    x = x - 0.01

6 comments · 100% upvoted · other discussions

comments

BTOdell

Floating point errors.

0.03 - 0.01 = 0.019999999999999997

0.019999999999999997 - 0.01 = 0.009999999999999997

0.009999999999999997 - 0.01 = -3.469446951953614e-18

-3.469446951953614e-18 is not >= 0, so it stops after the second iteration.

theodb [OP]

Ah ok, thanks. I'll just convert everything to ints then.

[deleted]

Wait, why does this happen?

BTOdell

Because Python uses double precision floating point numbers to represent it's decimal values. A double precision floating point number only has 64 bits to represent its value, so some mathematical expressions cannot be computed exactly.

[deleted]

TIL

Isvara

Represented, not computed.

It's nothing to do with it "only" having 64 bits (except for the fact that 64 < ∞), but the fact that some fractions can't be represented exactly in a binary representation, just like you can't, for example, represent ⅓ exactly in a decimal representation.