在浮点数学中将一个数字除以它的除数时,如果结果不是整数浮点数

When dividing a number by its divisor in floating point math, when if ever is the result not an integral float

当我运行这段代码在python

def is_cool(n):
    if (n/7).is_integer():
        return True
    else:
        return False

for i in range(0,1000000,7):
    if not is_cool(i):
        print(i, " is where the error is")

它不打印任何东西。我知道有些地方浮点数学总是正确的。这是其中之一吗?

(n/7).is_integer() returns True 只有当 n%7===0

现在你 运行 你的循环从 0 开始,步长为 7

您的 i 将是 0, 7, 14, 21, ...

is_cool(i) 将始终 return True 对于 i 的每个值,如上所述,但在您的 if 条件下,您已声明 if not is_cool(i) 将永远是 False 因此代码不会打印任何东西

IEEE-754 数字除以它的一个除数 returns 一个精确的结果。

IEEE 754-2008 4.3 说:

… Except where stated otherwise, every operation shall be performed as if it first produced an intermediate result correct to infinite precision and with unbounded range, and then rounded that result according to one of the attributes in this clause.

当中间结果可表示时,所有舍入属性都将其舍入到自身;舍入仅在无法表示时更改值。 5.4中给出了除法规则,并没有说明上述情况的例外情况。

可表示数除以可表示除数所得的商必须是可表示的,因为它的有效位不能超过分子。因此,将一个数除以它的一个除数 returns 是一个精确的结果。

请注意,此规则适用于作为除法实际操作数的数字。当您在源代码中有一些数字时,例如 1234567890123456890 / 7,这些数字首先被转换为数字格式。如果它们不能以那种格式表示,则必须产生某种近似值。这与该部门的运作方式不同。