2012-09-16 61 views
4

下面的代碼使用哪種算法/公式?下面這段Java代碼是如何計算Pi的數字的?

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

此代碼已在我們的問題集中爲我們編寫。我無法找到它使用的算法/公式,我對此很好奇。我懷疑這是一個簡單的算法,但我無法僅基於這段代碼在線查找公式。

+0

確定。我不會深入你的算法,但在這個話題中,它展示瞭如何計算pi iterativly http://stackoverflow.com/questions/39395/how-do-i-calculate-pi-in-c。 在你的情況下,還有其他一些迭代算法。 – gregory561

+1

這是有點隨機的,但是你有'powerMod()'函數的代碼在piTerm()裏面嗎? –

回答

10

就我所見,它是Bailey-Borwein-Plouffe-Algorithm算法,在不知道第(n-1)位的情況下計算pi的第n個數字。 pi的表示在這裏是基於16。

Formula to calculate the Nth digit of pi

見貝利的主頁:http://crd-legacy.lbl.gov/~dhbailey/

+0

非常感謝! –