开发者

Why is there an error when dividing 2/5.0 in Python? [duplicate]

开发者 https://www.devze.com 2022-12-20 03:30 出处:网络
This question already has answers here: 开发者_开发知识库 Closed 12 years ago. Possible Duplicate:
This question already has answers here: 开发者_开发知识库 Closed 12 years ago.

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.


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


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消