How to make a function that calculate appoximate value of pi
11 次查看(过去 30 天)
显示 更早的评论
Hi every one; I am going to make a function called a_pi that uses the following approximations of pi
but that function should have following specifications Instead of going to infinity, the function stops at the smallest k for which the approximation differs from pi (i.e., the value returned MATLAB’s built-‐in function) by no more than the positive scalar, delta, which is the only input argument. The first output of the function is the approximate value of π, while the second is k. (Note: if your program or the grader takes a long time, you may have created an infinite loop and need to hit Ctrl-‐C on your keyboard.) How to deal with that question.Thanks in advance for assistance..
2 个评论
James Tursa
2015-5-29
Please post what you have done so far so we can comment on it and make suggestions.
采纳的回答
Andrei Bobrov
2015-5-29
编辑:Andrei Bobrov
2015-5-29
function [pi_here,k1] = a_pi(delta)
f = @(k)sqrt(12)* 1./( (2*k+1).*(-3).^k ) ;
k1 = ceil(fzero(@(k)abs(f(k)) - delta,1));
pi_here = sum(f(0:k1));
end
or
function [pi_here,k1] = a_pi(delta)
f = @(k)sqrt(12)* sum(1./( (2*k+1).*(-3).^k )) ;
k1 = ceil(fzero(@(k)abs(f(0:k) - pi) - delta,1));
pi_here = f(0:k1);
end
or
function [pi_here,k1] = a_pi(delta)
k = 0;
pi_here = 0;
while abs(pi_here - pi) > delta
pi_here = pi_here + sqrt(12)./( (2*k+1).*(-3).^k );
k = k + 1;
end
k1= k - 1;
end
3 个评论
Cedric
2016-1-18
function main
tol = 1e-15 ;
n = 1e3 ;
tic ;
for k = 1 : n
a_pi1( tol ) ;
end
toc
tic ;
for k = 1 : n
a_pi2( tol ) ;
end
toc
tic ;
for k = 1 : n
a_pi3( tol ) ;
end
toc
end
function [pi_here,k1] = a_pi1(delta)
f = @(k)sqrt(12)* 1./( (2*k+1).*(-3).^k ) ;
k1 = ceil(fzero(@(k)abs(f(k)) - delta,1));
pi_here = sum(f(0:k1));
end
function [pi_here,k1] = a_pi2(delta)
f = @(k)sqrt(12)* sum(1./( (2*k+1).*(-3).^k )) ;
k1 = ceil(fzero(@(k)abs(f(0:k) - pi) - delta,1));
pi_here = f(0:k1);
end
function [pi_here,k1] = a_pi3(delta)
k = 0;
pi_here = 0;
while abs(pi_here - pi) > delta
pi_here = pi_here + sqrt(12)./( (2*k+1).*(-3).^k );
k = k + 1;
end
k1= k - 1;
end
Gives
>> main
Elapsed time is 0.731927 seconds.
Elapsed time is 2.314194 seconds.
Elapsed time is 0.007396 seconds.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!