为什么Python 3.4给出大数除法的错误答案,我该如何测试可分性? [英] Why does Python 3.4 give the wrong answer for division of large numbers, and how can I test for divisibility?

查看:145
本文介绍了为什么Python 3.4给出大数除法的错误答案,我该如何测试可分性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我使用除法来测试结果是一个整数,我测试可分性。但是,我得到错误的答案。这里是一个例子:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆