为什么Python 3.4给出大数除法的错误答案,我该如何测试可分性? [英] Why does Python 3.4 give the wrong answer for division of large numbers, and how can I test for divisibility?
问题描述
print(int(724815896270884803/61))
给出11882227807719424。
print(724815896270884803 // 61 )
给出正确的结果11882227807719423。
<为什么浮点结果是错误的,我怎样才能测试大数是否可以被61整除?我真的需要做整数除法,然后乘以它,看看它是否相等吗?
浮点结果是因为用 /
来划分两个整数会产生一个浮点数,而且除法的精确结果不能完全表示为 float
。确切的结果11882227807719423必须四舍五入到最接近的可表示的数字:
$ p $ In [1]:float(11882227807719423)
Out [1]:1.1882227807719424e + 16
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?
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
这篇关于为什么Python 3.4给出大数除法的错误答案,我该如何测试可分性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!