2

我正在使用 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

4

1 回答 1

4

很可能是由于

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

应该是

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

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

于 2013-11-02T22:10:48.423 回答