溢出错误:(34,'数值结果超出范围')

时间:2021-01-20 20:24:27

标签: python while-loop sum overflow series

我正在尝试为 n 的一个值和下一个值之间的部分和的差异创建一个检测程序,但我收到了 OverflowError 的错误:(34,'数值结果超出范围')。就存储的数字类型而言,我有什么不对的地方吗?这是我的代码:

def compute_sum(a, b, tolerance=1e-5):
    """Compute the sum $\sum^\infty_{n=1} a^n / b^{n-1} until the partial sums are less than *tolerance*.
    
    Returns the computed sum and raises a *ValueError* if the sum appears to be diverging.
    """

    import numpy
    n = 1;
    R = 100;
    Rold = 101;
    while (R > tolerance):
        while (n == 1):
            num = a**n
            den = b**(n-1)
            n += 1
            PS = num/den
            PSnew = PS
            S = PS
        else:
            while (Rold > R):
                num = a**n
                den = b**(n-1)
                n += 1
                PSold = PSnew
                PSnew = num/den
                Rold = R
                R = abs(PSnew - PSold)
                S = S + PSnew
            
    computed_sum = S;
            
    return computed_sum

1 个答案:

答案 0 :(得分:0)

如果你设置了一个 < b 那么我没有看到问题(尝试了一些数字并得到了一些结果),也许你可以说你有堆栈溢出的值(对不起,我还不能评论)。

另一方面,如果 a > b 则脚本在第一个循环中获得堆栈,这是因为 Rol 立即变得小于 R 但 R 仍然大于容差。

在不同的实例中打印通常有助于检测错误在哪里,但解决这个问题的方法可能是添加一个“and”语句,说最后一个循环继续,除了 R > Rol 和 R < Tolerance(另一件事是不是必需的,但最好使用“if n == 1”而不是“while n==1”,因为无论如何循环都会运行1次)。