Possible Duplicate:
Python float - str - float weirdness
In python, 2/5.0
or 2/float(5)
returns 0.40000000000000002
Why do I get that error at the end and how can I get the right value to use in additional calculations?
Possible Duplicate:
Python float - str - float weirdness
In python, 2/5.0
or 2/float(5)
returns 0.40000000000000002
Why do I get that error at the end and how can I get the right value to use in additional calculations?
Welcome to IEEE754, enjoy your stay.
Use decimal
instead.
See this question for the explanation. The right way would be to either
Because floating point arithmetic is not exact. You should use this value in your additional calculations, and round off the result when you're finished. If you need it to be exact, use another data type.
Ignacio above has the right answer.
There is are IEEE standards for efficiently storing floating point numbers into binary computers. These go in excruciating detail about exactly how numbers are stored and these rules are followed on almost every computer.
They are also wrong. Binary numbers cannot handle most normal numbers, just powers of two. Instead of doing something tricky requiring recomputation of the bottom bits to round-off or other tricks, the standards choose efficiency.
That way, you can curse at your system that runs slightly faster. There are occasional debates about changing Python in some way to work around these problems, but the answers are not trivial without a huge loss in efficiency.
Getting around this:
One option is digging into the "decimal" package of the standard library. If you stick to the examples and ignore the long page, it will get you what you want. No bets on efficiency.
Second is to do a manual rounding and string truncate yourself in one output function. Who cares if the number is off a bit if you never print those bits?
Note that Python 3.1 has a new floating point formatting function that avoids this sort of appearance. See What's new in Python 3.1 for more details (search for "floating point").