我一直在尝试编写一个简单的程序来使用 Chudnovsky 算法计算 pi,但是我一直得到错误的值输出。我编写的最新代码如下并输出:
9.642715619298075837448823278218780086541162343253084414940204168864066834806498471622628399332216456e11
谁能告诉我哪里出错了。
正如 Peter de Rivaz 指出的那样,我正在丢弃 b 的值并固定输出现在是:-1.767799793836391576547649814416358906088880847407921749358841620214761790018058360012019158247490909
Apfloat sum = new Apfloat(0);
for(int k = 0; k < n; k++) {
int thrk= 3*k;
Apfloat a = ApintMath.factorial(6*k); //(6k)! * (-1)^k
a = a.multiply(ApintMath.pow(new Apint(-1),k));
Apfloat b = new Apfloat(545140134);
b = b.multiply(new Apfloat(k));
b = b.add(new Apfloat(13591409)); // 13591409 + 545140134k
Apfloat c = ApintMath.factorial(thrk); // (3k!)
Apfloat d = ApintMath.factorial(k);
d = ApfloatMath.pow(d, 3); // (k!)^3
Apfloat e = new Apfloat(640320);
e = ApfloatMath.pow(e,(thrk)); // (640320)^(3k)
a = a.multiply(b); // a is know the numerator
c = c.multiply(d).multiply(e); // c in know the denominator
Apfloat div = a.divide(c.precision(digits));
sum = sum.add(div);
}
Apfloat f = new Apfloat(10005, digits);// Works out the constant sqrt part
f = ApfloatMath.sqrt(f);
f = f.divide(new Apfloat(42709344*100));
Apfloat pi = ApfloatMath.pow(sum.multiply(f), -1);
System.out.println(pi);