Python weird addition bug [duplicate]

好久不见. 提交于 2019-11-29 08:49:28

From the Python docs

Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either (emphasis mine). You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic (although some languages may not display the difference by default, or in all output modes)

You should probably use the decimal module.

You are using floating point numbers and have experienced a representation error. In particular, 0.01 has no exact representation as a binary floating point number. Instead a number very close to, but not exactly equal to 0.01 will be stored. This is not a bug. This is just the way floating point arithmetic works.

You can solve your problem in a few ways.

  • Accept that the results are not completely accurate or
  • Multiply everything by 100 and working with integers or
  • Use the Decimal type.

Example:

from decimal import Decimal
percentage = Decimal('0.1')
step = Decimal('0.01')
percentage += step

Floats do not have infinite precision, and so you get weird behaviour like this.

A better solution would be to store your percentage as an integer, representing tenths of a percent and increment by one.

e.g.:

percent_as_integer += 1

instead of

percent_as_float += 0.01

When you want to display the percentage, simply do:

print "%d.%02d" % divmod(percent_as_integer, 100)

EDIT: Actually, using the decimal module instead as was suggested in another answer is probably a better, more pythonic solution.

As described in other answers, this is a limitation of native floating point numbers in all current microprocessors.

If you need exact representation of decimal numbers (ex. for accounting and business application) you should use decimal type, not floating point. You may also use cdecimal module, which is a high-performance implementation of the decimal type.

Update: Starting with Python v3.3, the builtin decimal module is implemented in C.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!