//set up i/o objects inside main routine
PrintWriter screen = new PrintWriter(System.out,true);
double piValue = 0; // to accumulate the value of pi
int denominator = 1; // to increase as 1, 3, 5 etc as we go
final int numerator = 4; // this will be constant
final int gapSize = 2; // steps the denominator goes up in
final double accuracy = 0.0000001; // to measure how close we get
int numberOfLoops =0; // how many times do we go round loop?
boolean positive = true; // to tell us whether we add or subtract
//a term in loop
// now begin the loop to calculate pi.
while (Math.abs(Math.PI - piValue) > accuracy) {
// loop round until we get as close as accuracy to pi
// We take abs because the difference could be positive or negative
if(positive == true) {
piValue = piValue + (numerator*1.0/denominator);
// use the 1.0 to force a real conversion
}
else { // it's a negative term
piValue = piValue - (numerator*1.0 / denominator);
}
// diagnostic print follows
screen.println(piValue);
//and now we must remember the loop housekeeping
denominator = denominator + gapSize; // increase the bottom line
numberOfLoops++; // another term has been added
//and flip the boolean sign flag to get + and - alternating
if (positive == true) {
positive = false;
}
else {
positive = true;
}
} // end while
// after loop, the output
screen.print("The value of pi after " + numberOfLoops);
screen.println("attempts is " + piValue);