I'm trying to calculate pi using the Gregory-Leibniz method to a user-specified number of decimal places. I've never worked with the BigDecimal
class before, so I don't know what I am missing here.
A simple explanation of the Leibniz method can be found here (method 3).
Esentially, It starts with the fraction 4/n where n = 1, and alternates between subtracting and adding the fraction 4/n, incrementing n to the next odd integer each iteration.
The program outputs simply 5
, no matter how many decimal places are specified.
My code:
public static void calculatePi(int decimals) {
BigDecimal pi = new BigDecimal(0.0);
pi.setScale(decimals); // Set how many decimal points to use.
boolean plus = true; // Add on the next iteration?
int denominator = 1;
BigDecimal nextVal = new BigDecimal((4/denominator));
for(int i=0; i<decimals; i++)
{
if(plus == true) {
pi = pi.add(nextVal);
} else {
pi = pi.subtract(nextVal);
}
denominator += 2;
nextVal = new BigDecimal(4/denominator);
plus ^= false; // Flip value of plus each iteration
}
System.out.println(pi.toPlainString());
}