user11699723
user11699723

Reputation:

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;
    }

Upvotes: 1

Views: 605

Answers (3)

Malt
Malt

Reputation: 30295

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;

Upvotes: 3

Sebastian S
Sebastian S

Reputation: 4712

Make your, all your operands are floating point types. Otherwise your result is an integer.

See Java Language Specifications:

If the promoted type is float or double, then floating-point arithmetic is performed.


Also, on most platforms you can use double without any performance penalty, but this is another topic. ;-)

Upvotes: -1

mattm
mattm

Reputation: 5949

The problem is that integer division results in an integer, not a float or double.

1 / 3 is 0.

To avoid this, you can switch to using a float for the denominator instead of an int.

float denominator = 1.0f;

Upvotes: 0

Related Questions