如何解决int太长而无法转换为float错误?

时间:2017-01-14 00:40:08

标签: python python-2.7

我正在尝试确定e的连续数字中的前10位素数,因此想要将e计算为任意数量的小数点。这是我的代码,但是当我输入1000例如,它不能将factorial转换为float,因为它太大了:

import math

def calculate_e(n):
    e_real=0.0
    e_test=0.0
    accurate=False
    term=1 
    while accurate==False:
        e_real=sum(1 / float(math.factorial(i)) for i in range(term))
        if (e_real-e_test)<n:
            accurate=True
        else:
            accurate=False
        term+=1
        e_test=e_real
    return e_real

a=input("Enter accuracy: ")+1
b=10**(-a)
e=round(calculate_e(b),a)
print e

此外,我遇到的其他问题是打印该位数而不进行舍入。假设我想看到e的前三位数,我希望它输出271而不是272.我能想出的最好的就是让它更准确地将1位小数再精确到四位小数。 / p>

1 个答案:

答案 0 :(得分:2)

因子变得太大并不重要。前面有一个更重要的问题:

>>> import math
>>> for term in range(30):
        e_real = sum(1 / float(math.factorial(i)) for i in range(term))
        print '%2d %.60f' % (term, e_real)

 0 0.000000000000000000000000000000000000000000000000000000000000
 1 1.000000000000000000000000000000000000000000000000000000000000
 2 2.000000000000000000000000000000000000000000000000000000000000
 3 2.500000000000000000000000000000000000000000000000000000000000
 4 2.666666666666666518636930049979127943515777587890625000000000
 5 2.708333333333333037273860099958255887031555175781250000000000
 6 2.716666666666666341001246109954081475734710693359375000000000
 7 2.718055555555555447000415369984693825244903564453125000000000
 8 2.718253968253968366752815200015902519226074218750000000000000
 9 2.718278769841270037233016410027630627155303955078125000000000
10 2.718281525573192247691167722223326563835144042968750000000000
11 2.718281801146384513145903838449157774448394775390625000000000
12 2.718281826198492900914516212651506066322326660156250000000000
13 2.718281828286168710917536373017355799674987792968750000000000
14 2.718281828446759362805096316151320934295654296875000000000000
15 2.718281828458230187095523433526977896690368652343750000000000
16 2.718281828458994908714885241352021694183349609375000000000000
17 2.718281828459042870349549048114567995071411132812500000000000
18 2.718281828459045534884808148490265011787414550781250000000000
19 2.718281828459045534884808148490265011787414550781250000000000
20 2.718281828459045534884808148490265011787414550781250000000000
21 2.718281828459045534884808148490265011787414550781250000000000
22 2.718281828459045534884808148490265011787414550781250000000000
23 2.718281828459045534884808148490265011787414550781250000000000
24 2.718281828459045534884808148490265011787414550781250000000000
25 2.718281828459045534884808148490265011787414550781250000000000
26 2.718281828459045534884808148490265011787414550781250000000000
27 2.718281828459045534884808148490265011787414550781250000000000
28 2.718281828459045534884808148490265011787414550781250000000000
29 2.718281828459045534884808148490265011787414550781250000000000

这些是e_real中计算的确切值。您可以看到,当term变为18或更大时,您的e_real不再发生变化。浮动只是没有能力存储近1000位有效数字。

正如SethMMorton所说,请查看decimal模块。这可以解决你的两个问题。