0

So I created a while x <= 10 add 0.01 but it outputs numbers to 4dp and so on and lowers the endings too.

x = 0
c = 0 #count of numbers
while x <= 10:
    x += 0.01
    c += 1
    print (x)
print(c)

Expected results to be 0.01, 0.02, 0.03 Results seem to become changed at 0.06

0.01 0.02 0.03 0.04 0.05 0.060000000000000005 0.07 0.08 0.09 0.09999999999999999 MIDDLE STUFF 9.959999999999832 9.969999999999832 9.979999999999832 9.989999999999831 9.999999999999831 10.009999999999831

Sam
  • 25
  • 7

1 Answers1

1

I would guess this is because of floating-point rounding behavior. Interestingly enough, you can iterate by decimal values in, say, a for loop, but the unreliable behavior of floating point addition (from what I've been told) makes this less than desirable.

Alex Leibowitz
  • 1,364
  • 1
  • 8
  • 12