简体   繁体   English

在浮点数学中将数字除以其除数时,如果结果不是整数浮点数

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

When I run this code in python当我在 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")

It doesn't print anything.它不打印任何东西。 I know there are some places where floating point math will always be correct.我知道有些地方浮点数学总是正确的。 Is this one of them?这是其中之一吗?

IEEE-754 division of a number by one of its divisors returns an exact result. IEEE-754 将一个数除以它的一个除数会返回一个精确的结果。

IEEE 754-2008 4.3 says: 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. ...除非另有说明,每个操作都应该像首先产生一个精确到无限精度和无限范围的中间结果一样执行,然后根据本节中的一个属性对该结果进行四舍五入。

When an intermediate result is representable, all of the rounding attributes round it to itself;当中间结果可表示时,所有舍入属性将其舍入到自身; rounding changes a value only when it is not representable.舍入仅在值不可表示时更改值。 Rules for division are given in 5.4, and they do not state exceptions for the above.除法规则在 5.4 中给出,它们没有说明上述例外情况。

The quotient resulting from dividing a representable number by a representable divisor must be representable, as it can have no more significant bits than the numerator.将可表示数除以可表示除数所得的商必须是可表示的,因为它的有效位不能超过分子。 Therefore, dividing a number by one of its divisors returns an exact result.因此,将一个数除以它的一个除数会返回一个精确的结果。

Note that this rule applies to the numbers that are the actual operands of the division.请注意,此规则适用于作为除法实际操作数的数字。 When you have some numerals in source code, such as 1234567890123456890 / 7 , those numerals are first converted to the numeric format.当源代码中有一些数字时,例如1234567890123456890 / 7 ,这些数字首先转换为数字格式。 If they are not representable in that format, some approximation must be produced.如果它们不能以该格式表示,则必须产生一些近似值。 That is a separate issue from how the division operates.这是一个独立于部门运作方式的问题。

(n/7).is_integer() returns True only when n%7===0 (n/7).is_integer()仅在n%7===0时返回True

Now you run your loop starting from 0 with a step size of 7现在您从0开始运行循环,步长为7

Your i will be 0, 7, 14, 21, ...你的i将是0, 7, 14, 21, ...

is_cool(i) will always return True for every value of i as stated above but in your if condition you have stated if not is_cool(i) will always be False hence code will not print anything is_cool(i)将始终为上述i每个值返回True但在您的if条件中, if not is_cool(i)将始终为False因此代码不会打印任何内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM