Why does Python 3.4 give the wrong answer for division of large numbers, and how can I test for divisibility? [duplicate]

廉价感情. 提交于 2019-12-10 17:22:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!