Java Arithmetic Operator calculate/approximate PI

Question

Pi can be computed using the following formula:

pi = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...)

We would like to write a program that displays the result of

4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11)

and

4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13)


public class Main{
  public static void main(String[] args) {
    System.out.println(4 * (1.0 - (1 / 3) + (1 / 5) -
              (1 / 7) + (1 / 9) - (1 / 11)));
    System.out.println(4 * (1.0 - (1 / 3) + (1 / 5) - (1 / 7)
               + (1 / 9) - (1 / 11) + (1 / 13)));
  }
}

Note

We can also use loop:

public class Main {
  public static void main(String[] args) {
    System.out.println(approximatePi(11));
    System.out.println(approximatePi(13));
  }//ww w  .ja  v  a  2s  .  co  m

  private static double approximatePi(int index) {
    boolean positive = true;
    double sum = 0.0;
    for (int i = 1; i <= index; i += 2) {
      if (positive) {
        sum += (1.0 / i);
        positive = false;
      } else {
        sum -= (1.0 / i);
        positive = true;
      }
    }

    return 4.0 * sum;
  }
}



PreviousNext

Related