tags:

views:

153

answers:

5

I wrote this small snippet to calculate Fibonacci numbers. It works well for numbers up to 996 and from 997 a trace back is being printed. I can't figure out what the problem is. Does it has something to do with maximum_recursion_count?

def fib(n):
 if n==0:
  return 0
 elif n==1:
  return 1
 else:
  return fib(n-1)+n
+3  A: 

There is a wonderful Fibonnaci function implementation here that doesn't use recursion.

huntaub
Personal Note: I have run this function in the interpreter up to 10^600 and gotten all the numbers in less than 5 seconds.
huntaub
+3  A: 

Your code may come up against stack call limits.

mcandre
+5  A: 

Probably. Take a look at sys.getrecursionlimit(). The default value is 1000, which sounds like it just might be causing the problem you're seeing: once there are 1000 frames on the stack (i.e. slightly less than 1000 recursive function calls), you'll get an error on the next function call.

You can set the recursion limit to a larger value using sys.setrecursionlimit, but there is a maximum value which is platform-dependent (which means you might have to figure out what it is by trial and error).

David Zaslavsky
+2  A: 

You have reached the maxmimum recursion depth limit. As far as I know its default value is about 1000. You can change it sys.setrecursionlimit() and see it using sys.getrecursionlimit()

fishcrimson
+3  A: 

You say "It works well for numbers up to 996" ... No, it doesn't, it generates the wrong results. The last line should be:

return fib(n - 1) + fib(n - 2)
John Machin
The problem is, this is a TERRIBLE way to compute the fibonacci numbers. It will cost O(2^n) recursive calls to compute the nth fibonacci number. So for n even as small as 50, do you really want to do that much work?
woodchips
@woodchips: On the other hand, it's at least a correct way. If my answers don't have to be correct, I can produce them extremely fast. This is an improvement over the original for calculating Fibonacci numbers.
David Thornley
@woodchips: yeah yeah yeah, recursion is usually inefficient. The first priority is to get it CORRECT. How can the OP get a non-recursive function working properly when he doesn't have the relationship `f(n) = f(n-1) + f(n-2)` correct in his head? Once he has got that and verified a recursive function against manual calcs for (say) n <= 10, THEN he's in a position to start writing a non-recursive function.
John Machin
@woodchips .. yeah i understand how terrible the problem is and i was trying to implement dynamic programming technique with it .so as to improve the running tym and during the testing the performance of theimproved version vs this one i got this error .
Bunny Rabbit