Matlab Programming
Matlab Programming
Your Task
- fibonacci_tail_recursive(1) = 1
- fibonacci_tail_recursive(2) = 1
- fibonacci_tail_recursive(3) = 2
- fibonacci_tail_recursive(4) = 3
- Etc.
- There is no need for input error checking on this exercise.
Visual Tests
Matlab Programming
Your Task
- fibonacci_tail_recursive(1) = 1
- fibonacci_tail_recursive(2) = 1
- fibonacci_tail_recursive(3) = 2
- fibonacci_tail_recursive(4) = 3
- Etc.
- There is no need for input error checking on this exercise.
Visual Tests
Solution
The solution code for a tail recursive Fibonacci function is as follows:
function f = fibonacci_tail_recursive(n)
    f = fibonacci(1, 0, n); %invoking the tail recursive fibonacci with right parameters
 end
function y = fibonacci(a, b, c)
    if(n==1)
        y = a+b;
    else
 y = fibonacci(b, a+b, c-1);
    end
 end
A function call is tail recursive when the recursive call is the last thing executed by the current fuction. So the function shouldn\'t perform computation on a value, which it is waiting for, to be returned by the next function call. Where the normal fibonacci recursive function can be written in plain terms as:
fib(n) = fib(n-1)+fib(n-2)
Here the function call has to perform an addition on the two values it is waiting for, i.e. fib(n-1) and fib(n-2). To make the function tail recursive, we need to make only one recursive call which should be the last computation in the respective function which is why we take three values as parameters in the function call:
fib(a,b,c) : Here c represents the number of which fibonacci is to be calculated whereas a and b represents the last two numbers in the fiboacci series, that is the c-1th and c-2th numbers in the fibonacci series. Since we maintain the tally of last two numbers in each function call, the last computation that remains in each recursive call is to pass the updated value of these three parameters. This results in efficiency as the function call which is invoking a recursive call doesn\'t can get rid of stack required to store values.
At last the initial parameters were chosen as (1,0,n) to fit the description of question where for n=1, the answer is 1 and also for n=2 also the answer is 1. So for n=1 where we answer the current sum of a and b which is 1, for n=2, we just flip the numbers a and b, essentially keeping their sum same that is 1.This flip is only possible because when executed for first time the sum of a=1, b=0 yields 1 for the next value of b which is the value of a.


