Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How did the following piece of Java code calculate the digits of Pi?

Tags:

java

pi

Which algorithm/formula does the below code use?

    /**
 * Computes the nth digit of Pi in base-16.
 * 
 * If n < 0, return -1.
 * 
 * @param n The digit of Pi to retrieve in base-16.
 * @return The nth digit of Pi in base-16.
 */
public static int piDigit(int n) {
    if (n < 0) return -1;

    n -= 1;
    double x = 4 * piTerm(1, n) - 2 * piTerm(4, n) -
               piTerm(5, n) - piTerm(6, n);
    x = x - Math.floor(x);

    return (int)(x * 16);
}

private static double piTerm(int j, int n) {
    // Calculate the left sum
    double s = 0;
    for (int k = 0; k <= n; ++k) {
        int r = 8 * k + j;
        s += powerMod(16, n-k, r) / (double) r;
        s = s - Math.floor(s);
    }

    // Calculate the right sum
    double t = 0;
    int k = n+1;
    // Keep iterating until t converges (stops changing)
    while (true) {
        int r = 8 * k + j;
        double newt = t + Math.pow(16, n-k) / r;
        if (t == newt) {
            break;
        } else {
            t = newt;
        }
        ++k;
    }

    return s+t;
}

This code was already written for us in our problem set. I can't find which algorithm/formula it uses and I'm curious about it. I suspect that this is a simple algorithm, but I can't find the formula online based on this piece of code only.

like image 886
Leslie G Avatar asked Dec 27 '22 17:12

Leslie G


1 Answers

As far as I can see, it is the Bailey-Borwein-Plouffe-Algorithm to calculate a n-th digit of pi without knowing the (n-1)th digit. The representation of pi is on base-16 here.

Formula to calculate the Nth digit of pi

See the Homepage of Bailey: http://crd-legacy.lbl.gov/~dhbailey/

like image 73
Andreas Avatar answered Jan 17 '23 13:01

Andreas