#计算圆周率PI的前一千位
import decimal as DL
设置有效数字1001位,计算小数点后1000位,算上3就是1001位有效数字
n=1001
DL.getcontext().prec = n
PI=0
one=DL.Decimal(1)
two=DL.Decimal(2)
four=DL.Decimal(4)
k = 0
while k<=n:
#下面的公式 使用BBP公式可以直接求得十六进制π的第n位而不需要计算前n位的数
term=one/(16 ** k)*(four/(8 * k + 1)-two/(8 * k + 4)-one/(8 * k + 5)-one/(8 * k + 6))
PI+=term
k+=1
print(f"\n pi={PI}")
#注意第994~1000位的数字是4201989,也就是湖北省1989年出生的小朋友。
输出结果
pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744