我在做大数的除法

2024-09-21 03:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python2.7编写一个程序,首先检查一个数是否与另一个数等分,以及是否得到除法的结果。在

然而,当我使用大量的数字时,我得到了一些有趣的结果。在

目前我正在使用:

from __future__ import division
import math
a=82348972389472433334783
b=2
if a/b==math.trunc(a/b):
    answer=a/b
    print 'True' #to quickly see if the if loop was invoked

当我运行这个程序时,我得到:

^{pr2}$

但82348972389472433334783显然不平衡。在

任何帮助都将不胜感激。在


Tags: toanswerfromimport程序trueiffuture
3条回答

为什么不使用模运算符来检查一个数是否可以被等分呢?在

n%x==0

真除法隐式地将输入转换为float,它不提供精确地存储a值的精度。E、 在我的机器上

>>> int(1E15+1)
1000000000000001
>>> int(1E16+1)
10000000000000000

所以你失去了精确性。类似的情况发生在你的大数字上(比较int(float(a))-a)。
现在,如果你检查你的除法,你会看到结果“is”实际上是一个整数

^{pr2}$

这也是事先没有预料到的。在

在数学.trunc函数执行类似的操作(来自docs): 返回截断为整数(通常是长整数)的实值x。

python的duck类型特性允许比较长整数和float,请参阅 Checking if float is equivalent to an integer value in pythonComparing a float and an int in Python。在

这是个疯狂的方法。只需使用余数运算符。在

if a % b == 0:
    # then b divides a evenly
    quotient = a // b

相关问题 更多 >

    热门问题