python计算pi

发布时间 2023-12-28 20:23:44作者: 1無灬
from decimal import Decimal, getcontext
from tqdm import tqdm

# 设置精度为
getcontext().prec = 100000


# 计算圆周率
def compute_pi():
    pi = Decimal(0)
    k = 0
    with tqdm(total=1000, ncols=80, bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]') as pbar:
        while True:
            pi += (Decimal(1) / (16 ** k)) * ((Decimal(4) / (8 * k + 1)) - (Decimal(2) / (8 * k + 4)) - (Decimal(1) / (8 * k + 5)) - (Decimal(1) / (8 * k + 6)))
            k += 1
            pbar.update(1)
            if k > 1000:
                breakreturn pi


# 打印圆周率
print(compute_pi())