2013-04-11 62 views
1

我已經開始了一個用於計算pi的第n個數字的java項目,並決定使用BBP算法。 在我的輸出(在另一個班級),我一直在收到一些奇怪的數學錯誤,我不知道它來自哪裏。所以,我不認爲我正確地將算法放入代碼中。製作用於Java的BBP算法,計算第n位數

我得到的算法從http://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula

這裏是我的代碼:

import java.lang.Math; 
import java.lang.Math.*; 
public class Pi 
{ 
public static double getDigit(int n, int infinity) 
{ int pow = 0; 
    double[] sums = new double[4]; 
    int tot = 0; 
    int result = 0; 
    double fraction = 0; 
    for(int x = 0; x < 4; x++) 
    { 
     for(int k = 0; k < n; k++) 
     { 
      tot = 8 * k + 1; 
      if(x == 1) 
       tot += 3; 
      else if(x > 1) 
       tot++; 
      pow = n-k; 
      result = modular_pow(16, pow, tot); 
      sums[x] += (double)result/(double)tot; 
     } 
     for(int i = n + 1; i < infinity; i++) 
     { 
      tot = 8 * i + 1; 
      if(x == 1) 
       tot += 3; 
      else if(x > 1) 
       tot++; 
      fraction = Math.pow(16.0, (double)pow); 
      sums[x] += fraction/(double)tot; 
     } 
    } 
    return 4 * sums[0] - 2 * sums[1] - sums[2] - sums[3]; 
} 
public static int modular_pow(int base, int exponent, int modulus) 
    { 
    int result = 1; 
    while(exponent > 0) 
    { 
     if (exponent % 2 == 1) 
      result = (result * base) % modulus; 
     exponent--; 
     base = (base * base) % modulus; 
    } 
    return result; 
} 

在此先感謝。

+1

你可能不應該使用'double's。他們只有53位的精度。如果你沒有做太多算術運算,你可以嘗試使用'BigDecimal'。 – tmyklebu 2013-04-11 04:21:28

+0

錯誤很大,所以使用BigDecimal只會改變一點。 – user2268648 2013-04-11 13:52:48

+0

BBP是AFAIK,一個龍頭算法,所以它應該只用整數和BigDecimal來實現,後者只適用於更高精度的分割。 BBP提供16位數字,但。 – 2016-01-11 17:02:50

回答

0

首先,道歉對舊的帖子進行了修改,但是對應用BBP算法的說法嚴重缺乏有意義的解釋,所以我認爲這對於一些想要研究它的人可能仍然有用。

根據維基百科文章,您返回的結果需要將其整數部分除去(留下小數部分),然後乘以16.這應該使整數部分作爲第n個十六進制數字的表示的pi。我明天會測試一下,看看是否有幫助。否則,很好的實施,易於理解和有效地完成。