无法计算PI,不给我任何错误

时间:2014-02-11 18:17:23

标签: java bigdecimal

以下代码没有给我任何错误,但它没有正确计算Pi。请看一看,看看你是否能找出我做错了什么。

主要方法:

public static void main(String [] args){

    Pi obj1=new Pi();
    System.out.println("The answer is: " + obj1.calculatePi(20));
}

calculatePi方法:

public  BigDecimal calculatePi (int iterations) { 
    BigDecimal result = new BigDecimal(0);    // The result (summation of Taylor series)    
    BigDecimal nextTerm= new BigDecimal(0);
    BigDecimal j= new BigDecimal(2);
    BigDecimal i= new BigDecimal(4);
    BigDecimal num= new BigDecimal(16);
    BigDecimal oddNum = new BigDecimal(1);    // Odd numbers (1, 3, 5, 7 etc.)     
    BigDecimal pow5 = new BigDecimal(5);      // Odd powers of 5 (5^1, 5^3, 5^5 etc.)     
    BigDecimal pow239 =new BigDecimal(239);  // Odd powers of 239 (239^1, 239^3, 239^5 etc.)    
    BigDecimal sign = new BigDecimal(1);      // Either 1 or -1 indicating the sign of the next term              
    for (int count = 0; count < iterations; count++) {         // Calculate and add the next term in the series. 
        // The sign of each new term alternates.        
        nextTerm = num.divide (pow5.multiply( oddNum),100,BigDecimal.ROUND_HALF_UP).subtract (i.divide (pow239.multiply( oddNum),100, BigDecimal.ROUND_HALF_UP)); 
        result= sign.multiply(nextTerm).add(result);                      // Update variables for next time around loop        
        pow5 = pow5.multiply(pow5).multiply(pow5);        
        pow239 = pow239.multiply(pow239).multiply(pow239);        
        oddNum= oddNum.add(j);         
        sign = sign.subtract(sign);     }
    return result;  
}

2 个答案:

答案 0 :(得分:3)

这里可见的错误之一是sign应该在-1和1之间交替,而你的在第二次迭代中变为0

sign = sign.subtract(sign);   

1开头,所以

sign = 1 - 1 // == 0

应该是

sign = sign.negate();   

答案 1 :(得分:0)

由于您的程序仍在运行,因此无法获得结果。考虑一下您在该方法中计算的数字的大小。 11次迭代在我的机器上延伸,20可能远远超出普通PC的范围。尝试再次运行5次迭代并优化算法。

除此之外,lejlot是正确的,你应该否定符号,而不是将它从一次迭代减去下一次迭代。

编辑:对于10次迭代,我得到以下结果: Pi: 3.140598667726060313997433309223757530269291966682082323...

因为我们都从记忆中知道Pi以3.14159265358979323846264...开头并不是那么准确。

相关问题