进度条

from decimal import Decimal, getcontext
import math
import sys
import time
from tqdm import tqdm

------------------------------

1. 高精度圆周率计算 (Chudnovsky算法)

------------------------------

def compute_pi(precision=50):
"""
使用Chudnovsky算法计算高精度圆周率
:param precision: 小数点后保留的位数
:return: 高精度的π值
"""
# 设置计算精度,比目标多10位避免中间过程误差
getcontext().prec = precision + 10

# 预定义常量
C = Decimal(4270934400)
L = Decimal(13591409)
M = Decimal(545140134)
X = Decimal(-640320)**3
K = Decimal(640320)
sqrt_K = K.sqrt()

sum_total = Decimal(0)
k = 0
# 计算所需项数,每一项约增加14位有效数字
num_terms = precision // 14 + 1

for k in range(num_terms):
    # 计算(6k)! / (3k)! * (k!)^3
    term1 = math.factorial(6 * k)
    term2 = math.factorial(3 * k)
    term3 = (math.factorial(k)) ** 3
    factorial_part = Decimal(term1) / Decimal(term2 * term3)

    # 计算(545140134k + 13591409)
    linear_part = M * k + L

    # 计算(-640320)^(3k)
    x_part = X ** k

    # 计算项
    term = factorial_part * linear_part / x_part
    sum_total += term

# 计算π
pi = (C * sqrt_K) / sum_total
# 四舍五入到目标精度
getcontext().prec = precision
return +pi

------------------------------

2. 进度条实现

------------------------------

def progress_bar_simple(current, total, bar_length=50):
"""简单文本进度条"""
percent = float(current) / total
arrow = '=' * int(round(percent * bar_length) - 1) + '>'
spaces = ' ' * (bar_length - len(arrow))
sys.stdout.write(f"\r计算进度: [{arrow}{spaces}] {int(percent * 100)}%")
sys.stdout.flush()

def progress_bar_percent(current, total):
"""带百分比的进度条"""
percent = int(100 * current / total)
bar = '█' * percent + '-' * (100 - percent)
sys.stdout.write(f"\r计算进度: |{bar}| {percent}%")
sys.stdout.flush()

------------------------------

主程序

------------------------------

if name == "main":
# 设置计算精度,例如计算小数点后100位
precision = 100
print(f"开始计算圆周率,目标精度:小数点后{precision}位...\n")

# 方式1:简单文本进度条
print("方式1:简单文本进度条")
num_terms = precision // 14 + 1
for i in range(num_terms):
    time.sleep(0.1)  # 模拟计算耗时
    progress_bar_simple(i + 1, num_terms)
print("\n计算完成!\n")

# 方式2:带百分比的进度条
print("方式2:带百分比的进度条")
for i in range(num_terms):
    time.sleep(0.1)
    progress_bar_percent(i + 1, num_terms)
print("\n计算完成!\n")

# 方式3:tqdm库进度条
print("方式3:tqdm库进度条")
for i in tqdm(range(num_terms), desc="计算进度"):
    time.sleep(0.1)
print("计算完成!\n")

# 实际计算并输出π
pi_value = compute_pi(precision)
print(f"圆周率π(小数点后{precision}位):")
print(pi_value)``

代码说明
高精度计算:
使用 decimal 模块设置任意精度,Chudnovsky 算法保证了收敛速度。
num_terms = precision // 14 + 1 控制循环次数,每增加一次循环,约多 14 位有效数字。
进度条:
progress_bar_simple:用 = 和 > 符号模拟进度条。
progress_bar_percent:用 █ 和 - 符号显示百分比。
tqdm:第三方库,直接生成美观的进度条,需先安装 pip install tqdm。

posted @ 2026-05-14 22:35  云天明11  阅读(1)  评论(0)    收藏  举报