views:

241

answers:

5

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?

+20  A: 

Welcome to IEEE754, enjoy your stay.

Use decimal instead.

Ignacio Vazquez-Abrams
+1 (A link to) the explanation of the unfortunate truth. And a useful solution. Succinctly put.
MattH
This section of the tutorial http://docs.python.org/tutorial/floatingpoint.html explains the issue, python way
nosklo
Using `decimal` instead is horrid advice. Decimal numbers have the **same problem** (for example if you were trying to represent 2/3 instead of 2/5), but `decimal.Decimal` is incompatible with many packages, slow, and syntactically more trouble to deal with.
Mike Graham
+1  A: 

See this question for the explanation. The right way would be to either

  1. Use integers until the "final" calculation
  2. Live with rounding errors.
Kimvais
+3  A: 

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.

Hans W
+2  A: 

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?

Charles Merriam
Using `decimal` does **not** get around this. Decimal numbers are no more able to represent all rationals than binary floating point numbers. Simply change the example from 2/5 and replace it by 2/3.
Mike Graham
+1  A: 

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").

Greg Hewgill