楚德諾夫斯基算法
楚德諾夫斯基算法(英語:Chudnovsky algorithm),是一種計算圓周率的快速方法。烏克蘭裔美國數學家楚德諾夫斯基兄弟於1988年發表了這套演算法,並使用它計算超過十億位數字。
該算法基於以下快速收斂的超幾何級數:
這個恆等式與拉馬努金的某些涉及的公式非常相似。
代碼實現
import math
from decimal import Decimal, getcontext
import sys
import time
# 设置Decimal的精度,这里设置得很高以便于长时间运行.
getcontext().prec = 1000
def compute_pi():
"""无限计算π的近似值,并实时在同一行更新显示结果"""
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("\r" + str(pi_approx)[:2 + i]) # 逐步显示更多位的π
sys.stdout.flush()
time.sleep(0.1) # 减慢输出速度
i += 1
# 开始计算π的值, 无限输出
compute_pi()
這段代碼是一個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).
這是一篇關於數的小作品。您可以透過編輯或修訂擴充其內容。 |