lecture20

# lecture20 - LECTURE 20 Recursion Recursion vs Iteration E7...

This preview shows pages 1–5. Sign up to view the full content.

1 LECTURE 20 Recursion Recursion vs Iteration E7, Fall 2008, M. Frenklach 1 RECURSION: x n = x n -1 * x function y = powerfun(x,n) % recursion: x^n = x^(n-1)*x if n == 1 y = x; else y = powerfun(x,n-1) * x; end 2 RECURSION: Fibonacci numbers 1 1 2 3 5 8 13 21 34 55 89 144 … F = F = 1 F 1 F 2 1 F n = F n-2 + F n-1 3

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 function F = fib(n) % RECURSIVE version if < 3 F 1 = F 2 = 1; F n = F n-2 + F n-1 if n < 3 F = 1; else F = fib(n-2) + fib(n-1); end 4 F 1 = F 2 = 1; F n = F n-2 + F n-1 fib(5) =5 fib(3) =2 fib(4) =3 fib(1) =1 fib(2) =1 fib(2) =1 fib(3) =2 fib(1) =1 fib(2) =1 5 ITERATION – Repeated execution of a part of a code for. ..end while. ..end 6
3 function F = fib_iter(n) % ITERATIVE version F = zeros(1,n); F 1 = F 2 = 1; F n = F n-2 + F n-1 F(1) = 1; F(2) = 1; for i = 3:n F(i) = F(i-2) + F(i-1); end 7 >> tic, fib(20); toc >> tic TIMING >> for i = 1:100 fib_iter(1000) >> end >> t = toc; t/100 8 % fib_ratio.m % ratio of fibonacci numbers n = 20; RATIO F(i+1)/F(i) f = fib_iter(n); r = f(2:n)./f(1:n-1); plot(r, '-o' ) 9

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4 RATIO F(i+1)/F(i) >> r' ans = 1 2 1.5 1.6667 1.6 1.625 1.6154 1 619 1.619 1.6176 1.6182 1.618 1.6181 1.618 1.618 1.618 1.618 1.618 1.618 1.618 10 ab a bb b bb ϕ ϕϕ + == + = GOLDEN RATIO = 2 1 10 15 1.6180339887 2 + = −−= + =≈ Leonardo Da Vinci's illustration from the Divina Proportione , Luca Pacioli 1509, Venice, depicting the golden proportion as it applies to the human face.
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 6

lecture20 - LECTURE 20 Recursion Recursion vs Iteration E7...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online