MATLAB: How to make a function that calculate appoximate value of pi

homeworkpiseriessum

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

Best Answer

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