Skip to main content
Engineering LibreTexts

6.7: One more example

  • Page ID
    41455
  • After factorial, the most common example of a recursively defined mathematical function is fibonacci, which has the following definition (see http://en.Wikipedia.org/wiki/Fibonacci_number):

    \[ \mathit{fibonacci}(0) = 0 \nonumber \]

    \[ \mathit{fibonacci}(1) = 1 \nonumber \]

    \[ \mathit{fibonacci}(n) = \mathit{fibonacci}(n-1) + \mathit{fibonacci}(n-2) \nonumber \]

    Translated into Python, it looks like this:

    def fibonacci(n):
        if n == 0:
            return 0
        elif  n == 1:
            return 1
        else:
            return fibonacci(n-1) + fibonacci(n-2)
    

    If you try to follow the flow of execution here, even for fairly small values of \( n \), your head explodes. But according to the leap of faith, if you assume that the two recursive calls work correctly, then it is clear that you get the right result by adding them together.

    • Was this article helpful?