feat: add leibniz formula
This commit is contained in:
@@ -7,5 +7,6 @@
|
||||
| ModularInv | 求乘法逆元【扩展欧几里得法】 | - |
|
||||
| Sqrt10 | 求 $\sqrt{10}$【连分数】 | [resolve-sqrt-10](https://hatter.ink/static/resource/muboard/?id=resolve-sqrt-10&version=latest&full=1) |
|
||||
| WallisProduct | 沃里斯乘积 | [wallis-product](https://hatter.ink/static/resource/muboard/?id=wallis-product&version=latest&full=1) |
|
||||
| LeibnizFormula | $\pi$ 的莱布尼茨公式 | [leibniz-formula](https://hatter.ink/static/resource/muboard/?id=leibniz-formula&version=1) |
|
||||
| EulerNumber | 欧拉数 | [eulers-number](https://hatter.ink/static/resource/muboard/?id=eulers-number&version=latest&full=1) |
|
||||
| BirthdayParadox | 生日悖论 | [birthday-paradox](https://hatter.ink/static/resource/muboard/?id=birthday-paradox&version=latest&full=1) |
|
||||
|
||||
27
src/main/java/me/hatter/math/LeibnizFormula.java
Normal file
27
src/main/java/me/hatter/math/LeibnizFormula.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package me.hatter.math;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
public class LeibnizFormula {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 3.1415925535897932384628933832795028810721693993752011334749445868976601562867023677686597593566430148
|
||||
System.out.println(pi());
|
||||
}
|
||||
|
||||
public static BigDecimal pi() {
|
||||
BigDecimal p = BigDecimal.ZERO;
|
||||
|
||||
for (long i = 0; i < 10000000; i++) {
|
||||
BigDecimal v = BigDecimal.ONE.divide(BigDecimal.valueOf(i * 2 + 1), 100, RoundingMode.FLOOR);
|
||||
if (i % 2 == 0) {
|
||||
p = p.add(v);
|
||||
} else {
|
||||
p = p.subtract(v);
|
||||
}
|
||||
}
|
||||
|
||||
return p.multiply(BigDecimal.valueOf(4)).divide(BigDecimal.ONE, 100, RoundingMode.FLOOR);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user