问题
In my program, I'm using division to test if the result is an integer, I'm testing divisibility. However, I'm getting wrong answers. Here is an example:
print(int(724815896270884803/61))
gives 11882227807719424.
print(724815896270884803//61)
gives the correct result of 11882227807719423.
Why is the floating point result wrong, and how can I test whether the large number is divisible by 61? Do I really need to do integer division and then multiply it back and see if it's equal?
回答1:
The floating-point result is wrong because dividing two ints with /
produces a float, and the exact result of your division cannot be represented exactly as a float
. The exact result 11882227807719423 must be rounded to the nearest representable number:
In [1]: float(11882227807719423)
Out[1]: 1.1882227807719424e+16
回答2:
Instead of dividing, you should compute the modulus (%
):
print(724815896270884803 % 61)
This is similar to doing an integer division and returning the remainder (think back to elementary school long division). A remainder of 0
means it is divisible.
来源:https://stackoverflow.com/questions/23899258/why-does-python-3-4-give-the-wrong-answer-for-division-of-large-numbers-and-how