FileDocCategorySizeDatePackage
CalculatePI.javaAPI DocExample2032Wed Nov 21 21:08:26 GMT 2001None

CalculatePI.java

//7. Use any loops you may need to calculate the value of pi, 
//which is given by 4 -4/3 + 4/5 -4/7 +4/9 -4/11 and so on. 
//How many terms do you need to get within 0.0000001 of Math.PI?

import java.io.*;

class CalculatePI {
  
  public static void main (String[] args) {
    //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);
  
  }// end main
} // end class CalculatePI