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));
            divisor = divisor.add(divisorStep);
        }

        return pi;
    }

}

 



Java PI Generation – Gregory-Leibniz
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close