Question

I am making a program to prove Leibnitz method for computing PI.

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

I took a very interesting approach to this and I am just wondering if there is a much easier way to do this.

What I did was I made the variable j the denominator. and the main idea was to have a counter start at -3 then go to Absolute value of -5 then -7 then absolute values of -9...so on. Do you think there is any way to make it smaller? Thanks :)

(To end the loop the teacher said to find the absolute difference and have that be < 1e-6)

public class Leibnitz
{
    public static void main(String argv[])
    {
        double answer = (Math.PI) / 4; //answer
        double numTheory = 1; //answer
        double j = -3; //counts the Denominator
        double piFrac; //extra variable for calc
        int i = 0; //counts loop

        System.out.print("How many iterations does it take to compute pi this series: ");

        while (Math.abs(answer - numTheory) > 1e-6)
        {
            if (j % 4 == -1) //checks if number should be negative (5,9,... needs to be positive so -5 % 4 = -1, -9 % 4 = -1)
                j = Math.abs(j);

            piFrac = (1 / j); //fraction of pie
            numTheory = numTheory + piFrac; //answer

            if (j > 0) //makes counter a negative
                j = -j;

            j -= 2; //goes down by 2

            i++; //counts how many times it goes thru the loop
        }

        System.out.println(i);

    }
}
Was it helpful?

Solution

If you are just looking for optimizations. This should work, it's much shorter and not too much less readable.

while (Math.abs(answer + numTheory) > 1e-6)
{
    j += 2;
    numTheory += 1 / (++i % 2 == 0 ? -j : j);
}

Explanation, the code (++i % 2 == 0 ? -j : j) gets evaluated as follows

(expression) ? (if branch) : (else branch)

so in english. if (++i mod 2 equals 0) then do (-j) else do (j)

Full code:

public class Leibnitz
{
    public static void main(String argv[])
    {
        double answer = Math.PI / 4; //answer
        double numTheory = 1; //answer
        double j = -3; //counts the Denominator
        int i = 0; //counts loop

        System.out.print("How many iterations does it take to compute pi this series: ");
        while (Math.abs(answer + numTheory) > 1e-6)
        {
            j += 2;
            numTheory += 1 / (++i % 2 == 0 ? -j : j);
        }
        System.out.println(i);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top