Java program to generate PI digits using Nilakantha series using double and BigDecimal.

After 500.000 iterations as expected it generates 16 correct decimal digits.

3.14159265358978689874902556766755878925323486328125
3.141592653589793240462643383269502884197291399375103050974944693349816400880678999026756787303333903

Main.java

import java.math.BigDecimal;
import java.math.MathContext;
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(nilakantha(iterations)));
        System.out.println(nilakanthaBigDecimal(iterations));
    }

    private static double nilakantha(long iterations) {
        iterations -= 1;
        double pi = 3;
        long divisorBegin = 2;
        double divisor;

        for (long i = 0; i < iterations; ++i) {
            divisor = 1.0d;
            for(long j = 0; j < 3; ++j) {
                divisor *= divisorBegin + j;
            }

            pi += i % 2 == 0 ? 4.0d / divisor : -4.0d / divisor;
            divisorBegin += 2;
        }

        return pi;
    }

    private static BigDecimal nilakanthaBigDecimal(long iterations) {
        iterations -= 1;
        BigDecimal pi = new BigDecimal(3);
        BigDecimal divisorBegin = new BigDecimal(2);
        BigDecimal divisor;

        BigDecimal one = new BigDecimal(1);
        BigDecimal two = new BigDecimal(2);
        BigDecimal four = new BigDecimal(4);
        BigDecimal minusFour = new BigDecimal(-4);
        MathContext mc = new MathContext(scale);

        for (long i = 0; i < iterations; ++i) {
            divisor = one;
            for(long j = 0; j < 3; ++j) {
                divisor = divisor.multiply(new BigDecimal(j).add(divisorBegin, mc), mc);
            }

            pi = pi.add(i % 2 == 0 ? four.divide(divisor, mc) : minusFour.divide(divisor, mc), mc);
            divisorBegin = divisorBegin.add(two, mc);
        }

        return pi;
    }
}



Java PI Generation – Nilakantha
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