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
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개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Number Theory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!