I have the following Python (3.12) code for finding Fibonacci numbers recursively, and keeping track of how many times the function is called.
fibcalls = 0
def fib(n):
global fibcalls
fibcalls += 1
if n < 2: return n
return fib(n-1)+fib(n-2)
I can run this for fib(40). It takes a while (but gets there before I give up). If I then check the value of fibcalls, which counts how many times the function has been called, I get a value of $331160281$.
My question is: Why isn't recursion depth exceeded so as to give me an error message?
A little more background: I am a math professor teaching a discrete math class to computer science majors. I would like to explain why our recursive factorial function can't even get to $1100$ calls (for calculating factorial($1100$)), but our recursive Fibonacci function can make over $300$ million calls without an error. I do have a theory: Namely: Calls to a given value only appear on the stack once, even though they are needed many times in the recursion. But that's just a guess.
Any further information would be welcome.