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.
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);
Best Answer