Waitdev_
Waitdev_

Reputation: 9

Java - Calculating Pi

I've been wanting to calculate pi with the Gregory-Leibniz series, and there's something wrong with it. I'm a bit of a starter to Java, so this may not be a hard question to answer. I don't know what's going on, so can somebody help me please?

Code so far:

package com.waitdev.pi;

public class Pi {

    static int pi = 0;

    public static void main(String[] args) {

        for (int i = 1; i < 51; i++) {

            if (isOdd(i)) {
                pi = pi+(4/((i*2)-1));
                // System.out.println(i);
            } else {
                pi = pi-(4/(i*2)-1);
                // System.out.println(i);
            }
        }

        System.out.println(pi);
    }

    private static boolean isOdd(int n) {
        if (n % 2 == 1) {
            return true;
        } else {
            return false;
        }
    }
}

FYI: The output for this is 28.

Thanks.

Upvotes: 0

Views: 387

Answers (2)

sfThomas
sfThomas

Reputation: 1955

You are missing a parenthesis in your else block, and you need to force float calculation by e.g writing 4.0 instead of 4. It should read:

if (isOdd(i)) {
    pi = pi+(4.0/((i*2)-1));
    // System.out.println(i);
} else {
    pi = pi-(4.0/((i*2)-1));
    // System.out.println(i);
}

You also need to use a float or a double for pi.

Extra - as for your isOdd method, it could be simplified like:

private static boolean isOdd(int n) {
     return (n % 2 == 1)
}

But this does not influence the result.

Upvotes: 6

Roel Strolenberg
Roel Strolenberg

Reputation: 2950

First off: an int is an integer, whole number. you want to change it to:

static double pi = 0;

Otherwise the answer always gets rounded down to a whole number.

Secondly, you are missing parenthesis in your else statement:

} else {
    pi = pi-(4/((i*2)-1));
}

If you want to be completely safe, change your integers in the if and else clause to doubles:

            if (isOdd(i)) {
                pi = pi+(4.0/((i*2.0)-1.0));
                // System.out.println(i);
            } else {
                pi = pi-(4.0/((i*2.0)-1.0));
                // System.out.println(i);
            }

But that shouldn't be neccessary

Upvotes: 0

Related Questions