0

我创建了一个程序来计算这个算法,从 k=1 开始,到 k=100 结束:

公式

这是我创建的代码:

public static void calculatePi() {
    BigInteger firstFactorial;
    BigInteger secondFactorial;
    BigInteger firstMultiplication;
    BigInteger firstExponent;
    BigInteger secondExponent;
    int firstNumber = 1103;
    BigInteger firstAddition;
    double summationPi = 3.0;
    double currentPi = 3.0;
    double pi = 3.0;
    int secondNumber = 2;
    double thirdNumber = Math.sqrt(2.0);
    int fourthNumber = 9801;
    double prefix = 1;

    for(int i=1;i<101;i++){
        firstFactorial = factorial(4*i);
        secondFactorial = factorial(i);
        firstMultiplication = BigInteger.valueOf(26390*i);
        firstExponent = exponent(secondFactorial, 4);
        secondExponent = exponent(BigInteger.valueOf(396),4*i);
        firstAddition = BigInteger.valueOf(firstNumber).add(firstMultiplication);
        summationPi = firstFactorial.intValue()*firstAddition.intValue();
        summationPi /= firstExponent.intValue()*secondExponent.intValue();
        currentPi += summationPi;
    }

    prefix = secondNumber*thirdNumber;
    prefix = prefix/fourthNumber;

    summationPi = summationPi*prefix;

    pi = 1/summationPi;

    System.out.println("Pi is: " + pi);

    return;
}

函数指数(a,b);返回 a^b 的结果。函数 factorial(a) 返回 a 的阶乘。我已经证明这两个功能都可以完美运行。然而,代码似乎神秘地返回“NaN”。我知道当某些东西被零除时会发生这种情况,但是我无法找到任何东西被零除的点。还有什么会导致这个/我做错了吗?

注意:在 for 语句中,我在算法中使用 i as k。

提前致谢!

4

2 回答 2

2

问题:

这些行很可能是发生错误的地方:

summationPi = firstFactorial.intValue()*firstAddition.intValue();
summationPi /= firstExponent.intValue()*secondExponent.intValue();

原因是您正在调用intValue()a BigInteger,它不能保证返回完整值(因为 anint只能保存 32 位数据。这也可以用于将结果存储为 adouble而不是 a BigDecimal)。

然后,您将那个可能的NaN值用作您的部门的除数。

解决方案:

BigDecimal currentPi = BigDecimal.ONE;

currentPi = currentPi.add(
  new BigDecimal(firstFactorial.multiply(firstAddition))
    .divide(new BigDecimal(firstExponent.multiply(secondExponent)), new MathContext(10000)));

请注意,我可以summationPi通过将多行合并为一条来消除。此外,方法中MathContext出现divide()的 设置为10000,可以将其更改为您想要的任何精度。

有关更多信息BigDecimal请查看 API

于 2012-03-15T19:26:01.230 回答
0

The cause of this problem is at this line:

summationPi /= firstExponent.intValue()*secondExponent.intValue();

where the value of the secondExponent becomes so large as i increases that if you retrieve its int value using the intValue() method, you will get 0.

于 2012-03-15T22:12:54.560 回答