Wednesday, 7 August 2013

Python int(90.0) = 89 error

Python int(90.0) = 89 error

This is a glitch in a larger program I wrote that I can't figure out. I'm
using Python 2.7.
n = 0.5
while n < 2:
print(int(n * 100))
n += 0.1
The output for 90, 100, and 110 are off by 1. Truncated output: 50, 60,
70, 80, 89, 99, 109, 120, 130, 140, ...
This doesn't happen when I a) start with n = 0.8, b) print the floating
point numbers directly, or c) don't increment n using a loop as with:
n = 0.9
print(int(n * 100))
I know there are many work arounds to this, but I'm still curious as to
why this might be occurring. It was part of a file naming function for
ordering output files of raw data. Thanks in advance!

No comments:

Post a Comment