Java program to generate PI digits using Gregory-Leibniz series using double and BigDecimal.

After 500.000 iterations as expected it generates only 5 correct decimal digits.

3.141590653589692028191393546876497566699981689453125
3.1415906535897932404626433832695028841972913993751030509749446933498164008806789990267567873033589959
import java.math.BigDecimal;
import java.math.RoundingMode;

// ? 2019 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

public class Main {

private static final int scale = 100;

public static void main(String[] args) {
long iterations = 500000;

System.out.println(new BigDecimal(gregoryLeibnitz(iterations)));
System.out.println(gregoryLeibnitzBigDecimal(iterations));
}

private static double gregoryLeibnitz(long iterations) {
double pi = 0;
double divisor = 1;

for (long i = 0; i < iterations; ++i) {
pi += i % 2 == 0 ? 4.0d / divisor : -4.0d / divisor;
divisor += 2;
}

return pi;
}

private static BigDecimal gregoryLeibnitzBigDecimal(long iterations) {
BigDecimal pi = new BigDecimal(0);
BigDecimal divisor = new BigDecimal(1);
BigDecimal dividend = new BigDecimal(4);
BigDecimal divisorStep = new BigDecimal(2);

for (long i = 0; i < iterations; ++i) {
pi = pi.add(i % 2 == 0 ?
dividend.divide(divisor, scale, RoundingMode.CEILING) :
dividend.divide(divisor.negate(), scale, RoundingMode.CEILING));
}

return pi;
}

}

Java PI Generation – Gregory-Leibniz
Tagged on: