So I wrote a program using Delphi to approximate Pi using the formula (Pi^2)/12 = 1 - 1/4 + 1/9 - 1/16 + 1/25 - ... but the answer it gives me isn't right. No matter how many terms I add it gives me 3.00000000000. Here's the code:
Code:
program Pi_Estimator;
{Program for estimating Pi. Written by Daniel Young.}
{$APPTYPE CONSOLE}
uses
SysUtils;
var
Pi: real;
n: longint;
b: longint;
i: longint;
a: longint;
begin
writeln('Welcome to the Pi approximator!');
write('Enter how many terms you would like to use ');
write('to estimate Pi:');
readln(n);
writeln;
writeln;
writeln('Now enter how many decimal places you would ');
write('like to output Pi to:');
readln(b);
i := 2;
Pi := 0;
a := 4;
while (i <> n) do
begin
if (i mod 2 = 0) then
begin
a := abs(a);
a := a+2*i + 1
end
else
a := -1*(2*i + 1)-a;
Pi := Pi + (1 div a);
i := i + 1;
end;
Pi := sqrt(12*(Pi + 0.75));
writeln;
writeln;
writeln(Pi:0:b);
readln;
end.
So if this looks confusing I'll try to explain how I wrote it (I only took one semester of programming, so it might not be the most efficient code). First the program gets the number of terms to use from the user, as well as how many decimal places to print Pi to. Set i to 2 and a to 4 so that the numbers come out right on the denominator of the terms and it goes through the loop adding terms 1/9 - 1/16 + 1/25... so on using the if then statement to see if the term should be positive or negative. After i gets to n it stops. Since Pi still needs the 1 and - 1/4 terms (the first two terms of the series), I add those (which equals .75), solved for Pi in the formula, and printed to b decimal places.
If you don't understand part of the code I wrote just let me know and I'll explain it. I'm not very good at writing clear precise code yet, so bear with me. Hope you guys can shed some light on the problem. Thanks!