用Gauss-Legendre算法逼近java中的Pi

时间:2014-07-08 21:29:02

标签: java algorithm bigdecimal

刚开始拿起java并尝试编写一段简单的代码来显示基于Gauss-Legendre algorithm的Pi的近似值;我在下面的代码命令行中得到的结果是-33.343229 ...这对我来说似乎很奇怪。我知道我的代码不完整,因为我对小数点后面的位数没有限制,我将尝试使用BigDecimal。在阅读完文档后,我不太明白我应该怎么做!

有没有人知道我是否可以解决当前的错误,以及如何对小数点后的位数实施限制?谢谢!

class calculatePi {
public static void main(String[] args) {
    calculatePi x = new calculatePi();
    double y = x.approxPi(3);       //3 iterations
        System.out.print(y);
}
double approxPi(int i) {
    double a = 1;           //The initial conditions for the iteration
    double b = 1 / Math.sqrt(2);
    double t = 1/4;
    double p = 1;
    double a1 = 0;          //The internal n+1 terms for the iteration
    double b1 = 0;
    double t1 = 0;
    double p1 = 0;
    while (i > 0) {
        a1 = (a + b) / 2;
        b1 = Math.sqrt(a*b);
        t1 = t - p*(a - a1)*(a - a1);
        p1 = 2*p;
        a = a1;
        b = b1;
        t = t1;
        p = p1;
        i = i - 1;
    }
double applepie = ((a + b)*(a + b))/(4*t);
return applepie;
}

}

1 个答案:

答案 0 :(得分:3)

double t = 1/4;1/4执行整数除法,结果为0.尝试1/4.0