楚德诺夫斯基算法
代码实现
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., , 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).
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.