Search code examples
javapi

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.


Solution

  • 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