Search code examples
javapi

Trying to calculate Pi, but only getting 1


I'm still pretty new to Java, and I'm trying to work out Pi without using Math.PI(). The only problem is that I get an answer of "1" afterwards.

This is the formula that I was given to use.

    double pi = 1;
    boolean add = false;

    for(int i=3; i<1000; i += 2) {

        if(add) {
            pi += 1/i;
        } else {
            pi -= 1/i;
        }
        add = !add;
        System.out.println(pi);
    }
    System.out.println("pi: " + 4*pi);

I'm sure it's just some dumb mistake I've missed. Thanks


Solution

  • Dividing integers results in an integer.

    1 is an integer. And i is an integer. Dividing results in an integer.

    Make the 1 a double. Append the optional floating point suffix d or D.

    pi += 1.0d / i ;
    

    Also, some folks like me include parentheses for clarity even though optional in cases like this one.

    pi += ( 1.0d / i  ) ;