This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Linear Recurrences - 1 10 - Recursion and Linear Recurrences Motivation Now that youve seen recursion in action, it is time to move on to some more interesting examples of it. These examples typically have more than one recursive call in the function. To understand such programs, we often use recursion trees to visualize whats going on. A More Complicated Recurrence The Fibonacci numbers are an important sequence of numbers that have a recursive definition with two terms: F(n) = F(n1) + F(n2) and base case F(1) = F(2) = 1 The sequence is: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 You can see that it increases rather sharply. In fact, as we will see later, it increases at an exponential rate. For now, lets write a MATLAB program to compute Fibonacci numbers. The process is very similar to the recursive code we wrote before, %fibonacci.m %calculates a fibonnacci sequence of length n %E77 reader %07-01 D# function sum = fibonacci(n) if (n < 3) sum = 1; else sum = fibonacci(n-2) + fibonacci(n-1); end If you write this program and test it, youll find that it does indeed do the right thing. As for understanding the program, its a lot more complicated than a recursive program with one call. We couldnt draw the kind of figure we did in the first recursion lecture to explain whats going on. Instead, we use recursion trees to explain it. Each node in a recursion tree represents one call to the function. The root of the tree is the first call. The children of the root are the recursive calls that the root makes. Their children represent Linear Recurrences - 2 the recursive calls that they make, etc. In each node, we write the argument n for its call....
View Full Document
This note was uploaded on 02/12/2011 for the course E 7 taught by Professor Patzek during the Spring '08 term at University of California, Berkeley.
- Spring '08