用python计算圆周率PI

点击查看代码
import math
from decimal import Decimal, getcontext
import time
from tqdm import tqdm
import sys

def compute_pi(digits, progress_bars=3):
    """计算π到指定小数位数"""
    getcontext().prec = digits + 2  # 设置精度
    
    C = Decimal(426880) * Decimal(10005).sqrt()
    L = Decimal(13591409)
    X = Decimal(1)
    M = Decimal(1)
    K = Decimal(6)
    S = Decimal(13591409)
    
    total_iterations = digits // 14 + 2
    pi = Decimal(0)
    
    # 多种进度条
    bars = []
    if progress_bars >= 1:
        bars.append(tqdm(total=total_iterations, desc="标准进度", ncols=70))
    if progress_bars >= 2:
        bars.append(tqdm(total=total_iterations, desc="ASCII进度", ascii=True, ncols=70))
    if progress_bars >= 3:
        bars.append(tqdm(total=total_iterations, desc="彩色进度", colour='green', ncols=70))
    
    for k in range(total_iterations):
        # 计算当前项
        M = M * (K**3 - 16*K) // (k+1)**3
        L += 545140134
        X *= -262537412640768000
        S += M * L / X
        K += 12
        
        # 更新进度条
        for bar in bars:
            bar.update(1)
            bar.refresh()
            time.sleep(0.001)  # 为了显示效果
    
    # 关闭所有进度条
    for bar in bars:
        bar.close()
    
    pi = C / S
    return str(pi)[:digits+2]  # 包括"3."

def main():
    print("圆周率π计算器")
    digits = int(input("请输入要计算的小数位数: "))
    start_time = time.time()
    
    print("\n计算中...")
    pi = compute_pi(digits, progress_bars=3)
    
    end_time = time.time()
    print(f"\n计算完成! 耗时: {end_time-start_time:.2f}秒")
    
    # 显示部分结果
    print("\nπ的前100位:")
    print(pi[:102])
    
    # 保存完整结果到文件
    with open(f"pi_{digits}_digits.txt", "w") as f:
        f.write(pi)
    print(f"\n完整结果已保存到 pi_{digits}_digits.txt")

if __name__ == "__main__":
    main()
posted @ 2025-04-29 09:21  Lay“  阅读(22)  评论(0)    收藏  举报