Search code examples
javamathpi

Leibniz Formula using Java


The Leibniz formula for pi is: pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9... I am trying to write this in Java but am running into a problem where the output is always 4 (which is not the value of pi). I put my code in a java visualizer and it seems that the problem is that when the code falls into the else statement, it is not subtracting (1-denominator) from pi and that is making the prevPi value and the pi value the same which is causing the do/while loop to end. Does anyone know how I can fix this?

My code:

public static float piCalculatorLeibniz() {
        float pi = 0;
        int denominator = 1;
        float prevPi = 0;
        boolean keepGoing = true;
        int i = 0;
        while (keepGoing == true) {
            prevPi = pi;
            if (i % 2 == 0) {
                pi += (1/denominator);
            } else {
                pi -= (1/denominator);
            }
            i++;
            denominator += 2;
            if (pi == prevPi) {
                keepGoing = false;
            }
        }
        pi *= 4;
        return pi;
    }

Solution

  • You're right. 4 is in fact not the value of Pi.

    The problem is that the denominator variable is an int so 1/denomenator is int/int so the result is 0. That makes you exit the loop after just one iteration since pi == prevPi

    Just change the denominator type to a double (or float) and you'll get the right answer.

    Also, you don't need to write while(keepGoing == true). The variable keepGoing is already a boolean, you can write simply while(keepGoing)

    Edit:

    I enjoyed playing with this code, so here's a slightly shorter version that's more accurate due to the use of double. It also seems to converge quite a lot faster:

    double pi = 0, denominator = 1, prevPi = 1;
    while (pi != prevPi) {
        prevPi = pi;
        pi += (1 / denominator) - (1 / (denominator + 2));
        denominator += 4;
    }
    return pi * 4;