필터 지우기
필터 지우기

How to make a function that calculate appoximate value of pi

조회 수: 5 (최근 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
Muhammad Usman Saleem
Muhammad Usman Saleem 2015년 5월 29일
formaula is given in the image attached in the the post
James Tursa
James Tursa 2015년 5월 29일
Please post what you have done so far so we can comment on it and make suggestions.

댓글을 달려면 로그인하십시오.

채택된 답변

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.
Muhammad Usman Saleem
Muhammad Usman Saleem 2016년 1월 22일
Thanks, its lengthy approach but will be fine.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Number Theory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by