tail recursive function and wrapper function
조회 수: 3 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (2개)
Walter Roberson
2011년 9월 21일
MATLAB has no special support for tail recursion, just for recursion.
댓글 수: 0
Ramon Villamangca
2021년 6월 20일
편집: Ramon Villamangca
2021년 6월 20일
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Fixed-Point Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!