【问题标题】:How did the following piece of Java code calculate the digits of Pi?下面这段 Java 代码是如何计算 Pi 的位数的?
【发布时间】:2013-12-03 01:31:54
【问题描述】:

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

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

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

【问题讨论】:

  • 好的。我不会深入了解您的算法,但在本主题中将展示如何迭代计算 pi stackoverflow.com/questions/39395/how-do-i-calculate-pi-in-c。在您的情况下,可能还有其他一些迭代算法。
  • 这有点随机,但你有 powerMod() 函数的代码吗,在 piTerm() 中使用?

标签: java pi


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-11-21
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 2020-07-30
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    相关资源
    最近更新 更多