From 947362f55f23fe4363e1ed5ba571f8bf24ff914c Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Fri, 18 Jul 2025 21:52:46 +0800 Subject: [PATCH] feat: add leibniz formula --- README.md | 1 + .../java/me/hatter/math/LeibnizFormula.java | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 src/main/java/me/hatter/math/LeibnizFormula.java diff --git a/README.md b/README.md index b3c0ecc..5e9c41b 100644 --- a/README.md +++ b/README.md @@ -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) | diff --git a/src/main/java/me/hatter/math/LeibnizFormula.java b/src/main/java/me/hatter/math/LeibnizFormula.java new file mode 100644 index 0000000..e0306b5 --- /dev/null +++ b/src/main/java/me/hatter/math/LeibnizFormula.java @@ -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); + } +}