question:
calculating pi:
pi/4= 1-(1/3)+(1/5)-(1/7)+(1/9)-... (a)
which comes from
arctanx= x-(x^3/3)+(x^5/5)-(x^7/7)+(x^9/9)-... (b)
write a function to cumpute pi using question a. you should find that this series converges slowly. Determine how many terms are required to calculate pi to a relative accuracy of 10^-5.
My function:
function pi= calculating_pi
pi1=0
prompt='calculate pi';
n=input(100);
x=1
for i=1:n
if mod(i,2)==1
pi1=pi1+(1/x);
else pi1=pi1-(1/x);
end
x=x+2
pi1 = 4 * pi1;
error = abs(pi - pi1);
fprintf('Calculated value of pi : %f\n', pi1);
fprintf('Actual value of pi : %f\n', pi);
fprintf('Error : %f\n', error);
end
end
i keep getting error using input. I have no idea what I am doing wrong.

1 comentario

Walter Roberson
Walter Roberson el 3 de Oct. de 2019
What are you expecting input(100) to do for you?

Iniciar sesión para comentar.

 Respuesta aceptada

John D'Errico
John D'Errico el 3 de Oct. de 2019
Editada: John D'Errico el 3 de Oct. de 2019

0 votos

Easy. Type pi at the command line. Works like a charm.
Harder, since you did make a very credible effort at a solution, first, you need to recognize that you are using a pretty slowly convergent series.
Here is the sequence of estimates you should expect to see, for the first 50 terms.
n = 0:49;
cumsum(1./(2*n+1).*(-1).^n)*4
ans =
Columns 1 through 11
4 2.6667 3.4667 2.8952 3.3397 2.976 3.2837 3.0171 3.2524 3.0418 3.2323
Columns 12 through 22
3.0584 3.2184 3.0703 3.2082 3.0792 3.2004 3.0861 3.1942 3.0916 3.1892 3.0962
Columns 23 through 33
3.1851 3.0999 3.1816 3.1031 3.1786 3.1059 3.1761 3.1083 3.1738 3.1104 3.1719
Columns 34 through 44
3.1122 3.1702 3.1138 3.1686 3.1153 3.1672 3.1166 3.166 3.1178 3.1648 3.1189
Columns 45 through 50
3.1638 3.1199 3.1629 3.1208 3.162 3.1216
So, as I said, a slowly convergent series.
A very big part of the problem is in EVERY iteration of the loop, you multiply by 4.
pi1 = 4 * pi1;
That line is INSIDE your loop. So if I change your logic just slightly, multiplying by 4 only at the very end, it works nicely enough.
pi1 = 0;
x=1;
for i=1:n
if mod(i,2)==1
pi1=pi1+(1/x);
else pi1=pi1-(1/x);
end
x=x+2;
end
pi1 = 4 * pi1;
error = abs(pi - pi1);
fprintf('Calculated value of pi : %f\n', pi1);
fprintf('Actual value of pi : %f\n', pi);
fprintf('Error : %f\n', error);

1 comentario

Britnie Casillas
Britnie Casillas el 3 de Oct. de 2019
Thank you very much! I think I got it now!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Graphics Performance en Centro de ayuda y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by