我正在使用 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
:
精度是总位数。刻度是小数点后的位数。
在 PI 中,小数点前只有 1 位。
precision = scale + 1
因此scale = precision - 1