我试图用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显然不平衡。在
任何帮助都将不胜感激。在
为什么不使用模运算符来检查一个数是否可以被等分呢?在
n%x==0
真除法隐式地将输入转换为float,它不提供精确地存储
a
值的精度。E、 在我的机器上所以你失去了精确性。类似的情况发生在你的大数字上(比较
^{pr2}$int(float(a))-a
)。现在,如果你检查你的除法,你会看到结果“is”实际上是一个整数
这也是事先没有预料到的。在
在数学.trunc函数执行类似的操作(来自docs): 返回截断为整数(通常是长整数)的实值x。
python的duck类型特性允许比较长整数和float,请参阅 Checking if float is equivalent to an integer value in python和 Comparing a float and an int in Python。在
这是个疯狂的方法。只需使用余数运算符。在
相关问题 更多 >
编程相关推荐