-5

I am starting with learning Python. I currently have the following small piece of code:

a = float(input())
b = float(3)
while a < b:
    print(a + 0.0001)
    a+=0.0001

This counts, but there appear decimals in the end of the float. Why do they come there and what are they?

Output:

enter image description here

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Gerrit
  • 1
  • 1

1 Answers1

1

This is because the numbers in the question are not exactly represented by binary floating point. Start with 0.0001. The closest double precision value is in fact:

0.00010000000000000000479217360238592959831294137984514236450195312 5

So when you write 0.0001 what you actually get is the number above. That is then added to whatever value you input, and then the result is the closest representable value to that.

If this comes as a shock to you, then I suggest that you read David Goldberg's timeless article What Every Computer Scientist Should Know About Floating-Point Arithmetic.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490