4

以下代码使用哪种算法/公式?

    /**
 * 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;
}

这段代码已经在我们的问题集中为我们编写好了。我找不到它使用的算法/公式,我很好奇。我怀疑这是一个简单的算法,但我无法仅根据这段代码在网上找到公式。

4

1 回答 1

10

据我所知,在不知道第 (n-1) 位的情况下,计算 pi 的第 n 位是 Bailey-Borwein-Plouffe 算法。pi 的表示在这里是 base-16。

计算圆周率第N位的公式

见贝利主页:http ://crd-legacy.lbl.gov/~dhbailey/

于 2012-09-16T18:27:27.803 回答