When I run this code in 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-2008 4.3 says:
… 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.
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. 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
Now you run your loop starting from 0
with a step size of 7
Your i
will be 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.