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
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
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] 1 points · Jan 2018
Ah ok, thanks. I'll just convert everything to ints then.
[deleted] 1 points · Jan 2018
Wait, why does this happen?
BTOdell 2 points · Jan 2018
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] 1 points · Jan 2018
TIL
Isvara 1 points · Jan 2018
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.