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..

采纳的回答

Andrei Bobrov
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
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 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by