Search code examples
javaloopspi

java compute pi to 6 significant figurs


I'm having trouble with this program, we are supposed to compute pi to six significant figures, WITHOUT ROUNDING and WITHOUT using math library constant, the program should also show the number of iterations it took to reach 6 sig fig accuracy as well as the math constant in the output, so far I'm just trying to get my head around computing pi, I'm completely lost on how to get six 6 figs with or without rounding, not to mention how to iterate how many iterations it took to reach 6 sig figs pls help.

"Write an algorithm and program to compute π, using the formula described in the text PI/4 =1-(1/3)+(1/5)-(1/7)+(1/9)...." Output will include your computed value for π, the math library constant expected value for π and the number of iterations it took to reach six-significant digit accuracy. The number of iterations could exceed 250,000. Make your output clean and easy to read for comparing results.

This is the code I have so far to compute pi but even this I'm not sure is right.

public static void main(String[] args) throws Exception {      
    Double pi=1.0;
    int s=1;
    for (double j=3.0; j<100.0; j=j+2)
    {
        if (s % 2 == 0)
            pi = pi + (1/j);
        else
            pi = pi - (1/j);
        s = s + 1;
    }
    System.out.println(4*pi);

Solution

  • consider

            String piStr = "3.14159";
            Double pi=1.0;
            int s=1;
            double j=3.0; 
            String lcl = "";
            String upToNCharacters = "";
            while (true)
            {
                if (s % 2 == 0)
                    pi = pi + (1/j);
                else
                    pi = pi - (1/j);
    
                s = s + 1;
                j=j+2;
                
                lcl = "" + 4 * pi;
                upToNCharacters = lcl.substring(0, Math.min(lcl.length(), 7));
                if (upToNCharacters.equals(piStr)) {
                    break;
                }
            }
            System.out.println(upToNCharacters);
            System.out.println("after " + s);
    

    output

    3.14159

    after 136121