-3

I try this code with python 2.7.9:

a=8.52
for i in range(1,3):
    a *= 10.0
    print int (a)

It should display

85
852

But it displays

85
851

Do you have any idea why? Is it a known bug?

Zach
  • 600
  • 5
  • 16
  • 1
    `a*10` is `85.19999999999999` . – Anand S Kumar Oct 09 '15 at 15:33
  • @Zach, it's worth nothing you'll almost guaranteed never find a bug in the language if you're just starting out. The language is very mature in that sense. – TankorSmash Oct 09 '15 at 15:39
  • 2
    I understand the closing of this often asked question, but I think the downvotes are harsh. OP thought the problem was with `int` and was thus poorly prepared to Google for the correct terms that would lead to an answer. – Steven Rumbalski Oct 09 '15 at 15:40
  • @StevenRumbalski perspective was the reason I answered: first, giving OP the chance to google himself, and secondly, providing the typical debugging steps – Marcus Müller Oct 09 '15 at 15:48

1 Answers1

4

Do you have any idea why? Is it a known bug?

The obvious print debugging approach yields:

a=8.52
for i in range(1,3):
    a *= 10.0
    print int (a)
print a

which prints:

85
851
851.99999...

So, what's happening here is floating point math. It's not exact, because there's no exact way to represent 8.51 with binary floating point. Instead, a value very very close (yet smaller) to 8.51 is first stored in a.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94