为什么 5 能被 0.5 整除,但不能被 0.1 整除?

Why is 5 divisible by 0.5 but not by 0.1?

我不明白为什么 % 是这样的:

>>> 5 % 0.5 == 0
True
>>> 5 % 0.25 == 0
True
>>> 5 % 0.2 == 0
False
>>> 5 % 0.1 == 0
False

谁能给我解释一下? 我需要检查用户输入是否划分了一系列数字。只有当所有数字都可以被用户输入整除时,程序才接受输入,否则它会要求用户输入另一个数字。

浮点运算中的舍入错误。

>>>5 % 0.5
0.0
>>>5 % 0.25
0.0
>>>5 % 0.2
0.19999999999999973
>>>5 % 0.1
0.09999999999999973

注意:

  • 0.52**-1
  • 0.252**-2
  • 0.6252**-1 + 2**-3 等等。

所以,只要你有一个完美表示的浮点数,division/modulo操作很可能会顺利进行。

但是,当您尝试除以(或取模)0.1 或 0.2 时,其浮点表示总是存在舍入误差,这意味着除法将不完整,因此结果将不是没错。

您可以使用 Decimal module for more correct operations. Also, go through the regular pitfalls of floating point number.


>>> 1000 % 0.25 == 0
True
>>> 1000 % 0.625 == 0
True