提问者:小点点

int太大,无法转换为浮点


我正在用python研究基本微积分和阶乘。试图从牛顿级数生成PI,但我不能超过171次迭代,因为这个错误:overflowerrror:int太大,无法转换为float。代码如下:

我导入了这个:从数学导入阶乘,gamma/从数学导入sqrt

def calculus(ran):

    x = 1/2

    exp = 0
    p = 0

    terminos = []
    length = len(terminos)

    for i in range(ran):
        k = i
        n = 1/2

        tzero = 1

        exp += 2

        num = gamma(n)

        if k != 0:
           
            den1 = factorial(k)
            den2 = n-k
            den3 = gamma(den2)
            den = den1 * den3
            f1 = num/den

           
            f2 = 1/(exp+1)
            f3 = x**(exp+1)

            terminos.append(f1*f2*f3)
        else:
            f1 = x
            f2 = 1
            f3 = 1
            terminos.append(f1*f2*f3)

    p = 0

    terminos.append(-sqrt(3)/8)

    serie = sum(terminos)

    pi = serie * 12

    print(pi)

calculus(172)

共1个答案

匿名用户

根据Python教程,在精度很重要的情况下,最好使用十进制分数模块。

例如,你应该写f2=1/(exp 1),而不是写f2=1/(exp 1)

from fractions import Fraction
f2 = Fraction(1, exp+1)

阅读本文以获得更好的理解。

请注意,在Python中不建议进行如此繁重的计算,即使是使用内置库,如分数。您应该使用像NumPy这样的库来获得更好的性能和更高的精度。