Effacer les filtres
Effacer les filtres

tail recursive function and wrapper function

4 vues (au cours des 30 derniers jours)
Samantha Steele
Samantha Steele le 20 Sep 2011
Ok so it program a tail-recursive function to calculate A. and i need to add a wrapper function..
A=1-(1/2)+(1/3)-(1/4)+(1/5)-(1/6).... A is calculated when the last item is smaller than 10^-3

Réponses (2)

Walter Roberson
Walter Roberson le 21 Sep 2011
MATLAB has no special support for tail recursion, just for recursion.

Ramon Villamangca
Ramon Villamangca le 20 Juin 2021
Modifié(e) : Ramon Villamangca le 20 Juin 2021
The question is not about whether Matlab supports tail recursion. The question is to make a tail recursive function and wrapper function that presumably would enable to tail recursion support. Can we do that?
Lets see the tail recursive function first:
function a = asum(lim)
a = arec(lim-1,0,1);
end
function a = arec(lim,acc,cur)
if cur > lim
a = acc;
elseif mod(cur,2)
a = arec(lim,acc+1/cur,cur+1);
else
a = arec(lim,acc-1/cur,cur+1);
end
end
Now, the limit given (1/10^3) is so small that the above function will work without any wrapper function:
>> asum(10^3)
ans =
0.6936
But if we increase the limit to say, 1/10^6, we will run to "out of memory" error:
>> asum(1000000)
Out of memory. The likely cause is an infinite recursion within the program.
Error in asum>arec (line 9)
a = arec(lim,acc+1/cur,cur+1);
For this we need a wrapper function. One way is to use a "trampoline" wrapper. We need to modify the recursive function as follows:
function a = asum(lim)
a = trampoline(arec(lim-1,0,1));
end
function a = arec(lim,acc,cur)
if cur > lim
a = acc;
elseif mod(cur,2)
a = @() arec(lim,acc+1/cur,cur+1);
else
a = @() arec(lim,acc-1/cur,cur+1);
end
end
With this one we will not run out of memory:
>> asum(1000000)
ans =
0.6931
The trampoline wrapper function looks like this:
function t = trampoline(f)
%TRAMPOLINE wrapper function to convert tail-recursive functions to loops
% Usage: trampoline(f), where f is a tail-recursive function
while isa(f,'function_handle')
f = f();
end
t = f;
end

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by