为什么BigDecimal的这个除法返回0?

时间:2013-11-02 22:03:52

标签: java

我正在使用Chudnovsky算法来计算PI:

以下是代码:

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int summationUpperLimit;
        int precision;

        System.out.println("Enter the summation upper limit: ");
        summationUpperLimit = reader.nextInt();

        System.out.println("Enter the precision: ");
        precision = reader.nextInt();

        System.out.println(calculatePI(summationUpperLimit, precision));
    }

    private static int calculateFactorial(int n) {
        int factorial = 1;

        for (; n > 1; n--) {
            factorial = factorial * n;
        }

        return factorial;
    }

    private static BigDecimal calculatePI(int summationUpperLimit, int precision) {
        BigDecimal reciprocalOfPI = BigDecimal.ZERO;
        reciprocalOfPI.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);

        for (int k = 0; k <= summationUpperLimit; k++) {
            BigDecimal numerator = BigDecimal.valueOf(12 * Math.pow(-1, k) * calculateFactorial(6 * k) * (13591409 + 545140134 * k));
            numerator.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);
            BigDecimal denominator = BigDecimal.valueOf(calculateFactorial(3 * k) + Math.pow(calculateFactorial(k), 3) * Math.pow(640320, 3 * k + 1.5));
            denominator.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);
            // The issue is the line below:
            reciprocalOfPI = reciprocalOfPI.add(numerator.divide(denominator, BigDecimal.ROUND_HALF_UP));
        }

        return reciprocalOfPI.pow(-1, MathContext.DECIMAL128);
    }
}

我设置了以下输入:

summationUpperLimit = 0
precision = 100

在调试模式下,我检查了输出:

numerator = 163096908
denominator = 512384048.99600077
reciprocalOfPI = 0 (this value was taken after the division)

163096908 / 512384048.99600077不等于0,为什么表达式reciprocalOfPI = reciprocalOfPI.add(numerator.divide(denominator, BigDecimal.ROUND_HALF_UP));reciprocalOfPI设为0?

我设置scale = precision - 1的理由:

  1. 精确度是总位数。比例是小数点后的位数。

  2. 在PI中,小数点前只有1位数。

  3. precision = scale + 1因此scale = precision - 1

1 个答案:

答案 0 :(得分:4)

可能是由

引起的
reciprocalOfPI.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);

应该是

reciprocalOfPI = reciprocalOfPI.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);

BigDecimal是不可变的。它的所有“变异”方法都返回一个新的BigDecimal,保留原始的BigDecimal。