Borrar filtros
Borrar filtros

How to make a function that calculate appoximate value of pi

11 visualizaciones (últimos 30 días)
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 comentarios
Muhammad Usman Saleem
Muhammad Usman Saleem el 29 de Mayo de 2015
formaula is given in the image attached in the the post
James Tursa
James Tursa el 29 de Mayo de 2015
Please post what you have done so far so we can comment on it and make suggestions.

Iniciar sesión para comentar.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 29 de Mayo de 2015
Editada: Andrei Bobrov el 29 de Mayo de 2015
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 comentarios
Cedric
Cedric el 18 de En. de 2016
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 el 22 de En. de 2016
Thanks, its lengthy approach but will be fine.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by