Search code examples
javaloopsiterationpi

Java: coding the Wallis product to find pi


I am trying to write a code to output pi using the Wallis product formula: https://en.wikipedia.org/wiki/Wallis_product

This is my code:

public class PI {
    public static void main(String[] args) {
      pI();
    }

    public static void pI () {

    double pi = 0;
    int a = 0;
    int b = 1;
    double denom = 0;
    double num = 0;
    int temp = 0;
    int count = 0;
    double halfpi = 1;


        while(true) {
          temp = b;
          b = temp + 2;
          denom = temp*b;

          a += 2;
          num = a*a; 

          halfpi *= (num/denom);
          count++;

          System.out.println(halfpi*2);                    
        }    
    }
}

I have found that the code works just fine until the loop exceeds around 33000 iterations. After this point it just prints: "-0.0":

-0.0
-0.0
-0.0
-0.0
-0.0
...

----jGRASP: process ended by user.

What could be causing this?


Solution

  • The issue is because you are mixing INT's and Doubles. Your code will not produce any errors because this type of multiplication is fine however when you are assigning ints and then trying to assign them back to doubles you are losing everything except for the integer value before the decimal.

    double pi = 0;
    double a = 0;
    double b = 1;
    double denom = 0;
    double num = 0;
    double temp = 0;
    double count = 0;
    double halfpi = 1;