0

I'm trying to create a detection program for the difference in partial sums between one value of n and the next but I get the error of OverflowError: (34, 'Numerical result out of range'). Is there something I'm not doing right in terms of the type of number stored? This is my code:

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
Brad Figueroa
  • 869
  • 6
  • 15
  • Please post your whole stack trace and tell us what values you feed the function with. – Ruli Jan 20 '21 at 21:17

1 Answers1

0

If you set a < b then i didn't see a problem (tried with some numbers and got some result), maybe you can say with wich values you had the stack overflow (sorry i can't coment yet).

On the other hand, if a > b then the script gets stack on the first loop, this is because Rol becames smaller than R inmediatly but R is still greater than the tolerance.

Printing in the different instances normally helps in detecting where bugs are, but the way to solve this could be to add a "and" statement saying that the last loop continues except that R > Rol and R < Tolerance (Another thing that is not necesarry but it is better maybe is using "if n == 1" rather than "while n==1" because the loop is going to run 1 time no matter what).