0 votes
1 view
in Python by (8.3k points)

I have this tail-recursive function here:

def fib(n, sum):

    if n < 1:

        return sum

    else:

        return fib(n-1, sum+n)

c = 998

print(fib(c, 0))

It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" RuntimeError. Is this just a stack overflow? Is there a way to get around it?

2 Answers

0 votes
by (16.8k points)

It is a guard against a stack overflow, yes. Python (or rather, the CPython implementation) doesn't optimize tail recursion, and unbridled recursion causes stack overflows. You can change the recursion limit with sys.setrecursionlimit, but doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.

Python isn't a functional language and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea.

0 votes
ago by (20.3k points)

It seems like you just need to set a higher recursion depth like this:

sys.setrecursionlimit(1500)

...