我正在尝试求由分数 a/b
创建的数字的 2000 位十进制数字之和。我得到了很多数字,直到我遇到 NaN
(不是数字)。当循环运行大约 310 次时,我遇到了 NaN。如何获取其余数字?
这是我正在使用的代码:
import math
a = 3.00
b = 857.00
c = a/b
result = 0.0
s = 0.0
for x in range(0, 2000 , 1):
s= c % 10
result += int(s)
c *= 10
print result
最佳答案
您使用了错误的方法。使用直接 float 除法会限制您计算小数的能力,因为整数可以根据底层库转换为 float ,如 mentioned in documentation ,并且默认情况下 float 不会将数字保存为任意精度(在您的情况下为 2000):
When passing in a string, values for NaN and Infinity may be returned, depending on the underlying C library. Float accepts the strings nan, inf and -inf for NaN and positive or negative infinity. The case and a leading + are ignored as well as a leading - is ignored for NaN. Float always represents NaN and infinity as nan, inf or -inf.
就您的情况(以及我的情况)而言,该限制恰好是2**1024
。转到 python 提示符,然后尝试运行以下命令:
>>> float(2**1024)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to float
>>> float(2**1023)
8.98846567431158e+307
上面的数字基本上对应于上面代码中在第 310 次迭代结束时 c
的值,并且考虑到 c 被定义为 float,它会抛出错误.
基本上,这意味着任何等于或大于 2 **1024
的 float
数字都将是转换为 nan
或 inf
,因此您现有的代码将无法运行。
另外,请注意 floating point calculations have limitations anyway ,所以对于如此高的精度,你的答案是不正确的。
因此,我建议您计算每轮除以分母 b 的余数,如下所示:
a = 3
b = 857
result = 0
if a:
for x in range(0, 2000 , 1):
a = a*10
result += a / b
a = a%b
>>> print result
9056
关于python - 查找 float 中小数点后的数字总和,直到任意精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29279722/