When dividing a float by 100 in Python 2.7 I get the following "rounding behaviour":

>>> 3.7e-03/100
3.7000000000000005e-05

I would expect the following:

>>> 3.7e-03/100
3.7e-05

Note that:

>>> 3.7e-03/100 == 3.7e-05
False
>>> 3.7000000000000005e-05 == 3.7e-05
False

While probably of not practical difference in most applications I find this behaviour somewhat disconcerting.

Why does this happen and how can I avoid it?

I am using Python: '2.7.5 |Anaconda 1.7.0 (32-bit)| (default, Jul 1 2013, 12:41:55) [MSC v.1500 32 bit (Intel)]'

有帮助吗?

解决方案

This is a well-known deficiency of floating-point numbers.

You can think of binary floating-point as fractions with power-of-two denominators. Even a simple number such as 0.1 cannot be accurately represented as binary floating-point, and every division by a power of ten is by nature inaccurate.

If you need accurate division with arbitrary denominators in Python, use Decimal (which simulates pencil-and-paper decimals) or Fraction (which simulates pencil-and-paper fractions).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top