Skip to main content
 首页 » 编程设计

python之在 float 中找到小数点后的数字总和,直到任意精度

2024年10月25日16bhlsheji

我正在尝试计算由分数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 

上面的数字基本上对应于 c 在你上面的代码中的值,在第 310 次迭代结束时,假设 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