計算圓周率代碼
from tqdm import tqdm
import decimal
def pi_to_n_decimal_places(n):
? ?decimal.getcontext().prec = n + 1
? ?pi = decimal.Decimal(0)
? ?k = 0
? ?with tqdm(total=n + 1, desc="Processing pi calculation", leave=True) as progress:
? ? ? ?while True:
? ? ? ? ? ?term = 1 / decimal.Decimal(16) ** k * (
? ? ? ? ? ? ? ? ? ?decimal.Decimal(4) / (8 * k + 1) -
? ? ? ? ? ? ? ? ? ?decimal.Decimal(2) / (8 * k + 4) -
? ? ? ? ? ? ? ? ? ?decimal.Decimal(1) / (8 * k + 5) -
? ? ? ? ? ? ? ? ? ?decimal.Decimal(1) / (8 * k + 6))
? ? ? ? ? ?if abs(term) < decimal.Decimal("1e-{}".format(n)):
? ? ? ? ? ? ? ?break
? ? ? ? ? ?pi += term
? ? ? ? ? ?k += 1
? ? ? ? ? ?progress.update(1)
? ?return pi
pi = pi_to_n_decimal_places(1000000)
with open('圓周率.txt', 'w') as f:
? ?f.write(str(pi))
print('結果已保存在圓周率.txt文件中。')

不想部署環(huán)境的見以下鏈接
圓周率:https://aistudio.baidu.com/aistudio/projectdetail/6316403?contributionType=1&sUid=4115406&shared=1&ts=1685765459932
計算圓周率代碼的評論 (共 條)
