问题描述
我一直在尝试使用Chudnovsky算法编写一个简单的程序来计算pi,但是我一直得到错误的值输出。我写的最新代码在下面并输出:
I have been trying to write a simple program to calculate pi using the Chudnovsky algorithm however I keep getting the wrong value output. The latest code i have written is below and outputs:
9.642715619298075837448823278218780086541162343253084414940204168864066834806498471622628399332216456e11
9.642715619298075837448823278218780086541162343253084414940204168864066834806498471622628399332216456e11
谁能告诉我去哪了错误。
Can anyone tell me where I went wrong.
正如彼得·德·里瓦兹指出我正在抛弃b的值,修正了现在的输出:-1.76779979383639157654764981441635890608880847407921749358841620214761790018058 3600120191582474909093e-2
As Peter de Rivaz pointed out I was discarding the value of b with that fixed the output is now: -1.767799793836391576547649814416358906088808474079217493588416202147617900180583600120191582474909093e-2
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);
推荐答案
Chudnovsky算法的分母涉及640320 ^(3k + 3/2) - 你只使用640320 ^(3k)。
The denominator for the Chudnovsky algorithm involves 640320^(3k + 3/2) - you only use 640320^(3k).
这篇关于使用Chudnovsky算法计算pi时出错 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!