tail recursive function and wrapper function

4 Ansichten (letzte 30 Tage)
Samantha Steele
Samantha Steele am 20 Sep. 2011
Bearbeitet: Ramon Villamangca am 20 Jun. 2021
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

Antworten (2)

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

Ramon Villamangca
Ramon Villamangca am 20 Jun. 2021
Bearbeitet: Ramon Villamangca am 20 Jun. 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by