Question

So, I was putting my knowledge of for loops to the test by attempting to create the mathematical constant π using a series with user-defined accuracy:

public double pi(int accuracy) {
    for (int i = 1; i <= accuracy; i++) {
        rawPi += 1 / (i * i);
    }
    return Math.sqrt(rawPi * 6);
}

Now, you would think that this would get closer and closer to π as int accuracy shoots up, but it doesn't. It just stays at the square root of 6, meaning that private double rawPi gets to 1 and never goes any higher, meaning no terms are being added in my series (represented as a for loop) and I have absolutely no idea what the problem could be. Any ideas?

Was it helpful?

Solution

Try to change this:

    rawPi += 1 / (i * i);

to

    rawPi += 1.0 / (i * i);

or as commented by "Patricia Shanahan" , use this for better accuracy and to avoid integer overflow on i*i:

1/((double)i*i) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top