謎プログラムでπを計算する(Chudnovskyの公式)
はじめに
この記事では
どちらかと
突然だが、(チュドノフスキー級数で) を計算したくなった!
Chudnovsky Formula
再帰的無名関数
そこで
そこで、
UnaryOperator<Integer> fact = new UnaryOperator<>() {
@Override
public Integer apply(Integer n) {
return ((Function<UnaryOperator<Integer>, UnaryOperator<Integer>>) self -> x ->
(x <= 1) ? 1 : x * self.apply(x - 1)).apply(this).apply(n);
}
};
これは、
再帰関数は
ここで、Yコンビネータ或は固定点コンビネータの考え方を...
おい。一体何を言っているんだ、この話はやめだ。
Yコンビネータ
Yコンビネータ、
関数fを
詳しいことは
そんなこんなで実行
はい、
import java.util.function.Function;
import java.util.function.UnaryOperator;
class CalculatePi {
public static void main(String[] args) {
UnaryOperator<Integer> fact = new UnaryOperator<>() {
@Override
public Integer apply(Integer n) {
return ((Function<UnaryOperator<Integer>, UnaryOperator<Integer>>) self -> x ->
(x <= 1) ? 1 : x * self.apply(x - 1)).apply(this).apply(n);
}
};
Function<Integer, Double> chudnovsky = (n) -> {
double summa = 0.0;
for (int i = 0; i < n; i++) {
summa += (Math.pow(-1, i) * fact.apply(6 * i)) / (fact.apply(3 * i) * Math.pow(fact.apply(i), 3)) *
((13591409.0 + 545140134.0 * i) / Math.pow(640320, 3 * i + 1.5));
}
return 1.0 / (12.0 * summa);
};
System.out.println("π≒ " + Math.PI + "\n");
System.out.println("1. " + chudnovsky.apply(1));
System.out.println("2. " + chudnovsky.apply(2));
System.out.println("3. " + chudnovsky.apply(3));
System.out.println("4. " + chudnovsky.apply(4));
System.out.println("5. " + chudnovsky.apply(5));
}
}
チェドノフスキー級数本来の
愚直~
/*
* π≒ 3.141592653589793
*
* 1. 3.1415926535897345
* 2. 3.1415926535897936
* 3. 3.1415926535897936
* 4. 3.1415926535897936
* 5. 3.1415926535897936
*/
速攻でポンコツ
それもそのはず、
ちゃんと
日が暮れます。
おまけ
Chudnovsky Formulaの
<math display="block">
<mfrac>
<mn>1</mn>
<mi>π</mi>
</mfrac>
<mo>=</mo>
<mn>12</mn>
<mo>⁢</mo>
<munderover>
<mo>∑</mo>
<mrow>
<mi>n</mi>
<mo>=</mo>
<mn>0</mn>
</mrow>
<mi>∞</mi>
</munderover>
<mfrac>
<mrow>
<msup>
<mrow>
<mo>(</mo>
<mn>−1</mn>
<mo>)</mo>
</mrow>
<mi>n</mi>
</msup>
<mo>⁢</mo>
<mrow>
<mo>(</mo>
<mn>6</mn>
<mi>n</mi>
<mo>)</mo>
</mrow>
<mo>!</mo>
</mrow>
<mrow>
<mrow>
<mo>(</mo>
<mn>3</mn>
<mi>n</mi>
<mo>)</mo>
<mo>!</mo>
</mrow>
<mo>⁢</mo>
<msup>
<mrow>
<mo>(</mo>
<mi>n</mi>
<mo>!</mo>
<mo>)</mo>
</mrow>
<mn>3</mn>
</msup>
</mrow>
</mfrac>
<mo>⁢</mo>
<mfrac>
<mrow>
<mn>13591409</mn>
<mo>+</mo>
<mn>545140134</mn>
<mi>n</mi>
</mrow>
<msup>
<mn>640320</mn>
<mrow>
<mn>3</mn>
<mi>n</mi>
<mo>+</mo>
<mn>3</mn>
<mo>/</mo>
<mn>2</mn>
</mrow>
</msup>
</mfrac>
</math>