为什么 1 // 0.1 == 9.0?

Why does 1 // 0.1 == 9.0?

在Python2.73.x中,为什么整数除法除以数字0 < x < 1时给出的数字不正确?

负数 -1 < x < 0 甚至可以正常工作:

>>> 1//.1
9.0
>>> 1//-.1
-10.0

我知道负数(或正数)的整数除法向负无穷大舍入,但是我认为 1//.1 应该导致 10.0 因为 1 可以除by .1 没有余数。

您在这里看到的基本上是使用 / 的“正常”划分与使用 // 的地板划分之间的差异的影响。

同样重要的是要记住 general issue with floating point arithmetic which is a certain imprecision just because of how they work. In those situations, it’s always good to use the decimal 模块来检查实际发生的事情。那么让我们看看你在这里做什么:

首先,.1已经不准确了:

>>> Decimal(.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

那么,让我们看看实际的划分结果:

>>> Decimal(1) / Decimal(.1)
Decimal('9.999999999999999444888487687')
>>> 1 / .1
10.0

如您所见,使用 / 的正常除法并不能准确地为您提供 10 浮点运算。但它真的很接近。这就是为什么当你使用普通浮点数时,你实际上得到了 10(因为除法不精确会立即丢失在数字类型的不精确中)。

当使用底除法时,结果在之前被底除,不精确被纠正,所以这就是为什么你得到 9:

>>> Decimal(1) // Decimal(.1)
Decimal('9')
>>> 1 / .1
10.0

对于负数,地板效应是相反的方向,如所解释的in that other question:

>>> Decimal(1) / Decimal(-.1)
Decimal('-9.999999999999999444888487687')
>>> 1 / -.1
-10.0
>>> Decimal(1) // Decimal(-.1)
Decimal('-9')
>>> 1 // -.1
-10.0