2013-04-11 59 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。我明天会测试一下,看看是否有帮助。否则,很好的实施,易于理解和有效地完成。