计算BigDecimal会得出不正确的答案

时间:2018-09-05 23:23:29

标签: java math

所以我只是想弄清楚我是否可以做到这一点,以便可以计算E,但是却有了它,可以实现动态精度。从技术上讲,尽管我为变量PRECISION设置了什么整数,但最后几个数字始终与E的实际值始终不同。我不完全确定为什么,但是可以帮助您。

import java.math.BigDecimal; //To use for calculating E

public class ComputeE {
    public static double calcDenominator(int n)
    {
        double denominator = 1.0;   //Start the BigInt with 1
        for(int i = 1; i < n; i++) // Run n-1 amount of times
        {
            denominator = denominator * i;   // Multiply BigInteger by the BigInteger obtained with the int value i
        }
        return denominator;

    }


    public static void main(String[] args) {


        BigDecimal e = new BigDecimal(0.0);
        int PRECISION = 15;
        int iterations = 0;
        for(int i = 0; i < PRECISION; i++)
        {
            iterations++;
            BigDecimal numerator = new BigDecimal(1.0); // to divide, we need two BigDecimals, the numerator is 1
            BigDecimal factorial = new BigDecimal(calcDenominator(i));  // the denominator is i! which we get from calling the factorial method
            factorial = numerator.divide(factorial, PRECISION, BigDecimal.ROUND_UNNECESSARY);  // compute 1/i!, note divide is overloaded, this version is used to
                                                                  //     ensure a limit to the iterations when division is limitless like 1/3
            e = e.add(factorial);                   // add the latest 1/i! to e

        }



        System.out.println("Computed value of e : " + e);
        System.out.println("Expected value of e : " + Math.E);

    }
}

1 个答案:

答案 0 :(得分:3)

    在这里
  1. 必须修整。使用类似HALF_EVEN的名称。更好的是,使用枚举值RoundingMode.HALF_EVEN,因为不推荐使用舍入模式的整数常量。

  2. calcDenominator中,将您的for循环条件更改为i <= n,否则您将在1中多次添加main就会得到1太高的值。

  3. 您可以使用BigDecimal.ONE初始化numerator。这不会影响结果,但是为什么要创建不必要的对象?除了e以外,对BigDecimal.ZERO的初始化也有同样的评论。

  4. 您正在使用近似于无理数 e 的无穷级数(Maclaurin系列)的前PRECISION项。当您切断for循环时,会有一个错误项,这在数学上是可以预期的。经过上述更改,并将PRECISION提升到50,我得到了以下内容,看起来很精确。

Computed value of e : 2.71828182845904523536028747135266249775496954201584
Expected value of e : 2.718281828459045

尽管对double使用了BigDecimal构造函数,但还是很精确,因为double的有效数字从第一个非零位开始,所以即使您要计算1 / n!对于大n,有效数字足以将 e 的现有近似值添加到其中。