楚德诺夫斯基算法 - 维基百科,自由的百科全书
楚德诺夫斯基算法(英語:Chudnovsky algorithm),是一种计算圆周率的快速方法。烏克蘭裔美國數學家楚德诺夫斯基兄弟於1988年發表了這套演算法,並使用它计算超过十亿位数字。
该算法基于以下快速收敛的超几何级数:
这个恒等式与拉马努金的某些涉及的公式非常相似。
代码实现
[编辑]import math from decimal import Decimal, getcontext import sys import time # 设置 Decimal 的精度,这里设置得很高以便于长时间运行 getcontext().prec = 1000 def compute_pi(): """ 无限计算 π 的近似值,并实时在同一行更新显示结果。 使用 Chudnovsky 算法计算 π 值,不断提高精度并更新输出。 """ c = Decimal(426880 * math.sqrt(10005)) m = 1 l = 13591409 x = 1 k = 6 s = Decimal(l) i = 0 while True: m = (k**3 - 16*k) * m // (i+1)**3 l += 545140134 x *= -262537412640768000 s += Decimal(m * l) / x k += 12 pi_approx = c / s # 逐步显示更多位的 π sys.stdout.write(f"\r{pi_approx:.{i+2}f}") sys.stdout.flush() time.sleep(0.1) # 减慢输出速度 i += 1 if __name__ == "__main__": try: compute_pi() except KeyboardInterrupt: print("\n计算已停止")
这段代码是一个Python程序, 用于无限制地计算π(圆周率)的近似值, 并实时在命令行中更新显示结果. 它基于楚德诺夫斯基算法, 这是一种非常高效的方法, 可以快速计算π的多个小数位.
另见
[编辑]参考文献
[编辑]- Chudnovsky, David V.; Chudnovsky, Gregory V., The Computation of Classical Constants, Proceedings of the National Academy of Sciences of the United States of America, 1989, 86 (21): 8178–8182 [2009-11-29], ISSN 0027-8424, PMID 16594075, doi:10.1073/pnas.86.21.8178, (原始内容存档于2021-04-02).
![]() | 这是一篇關於數的小作品。您可以通过编辑或修订扩充其内容。 |