参考点:
累加,指定子库导入
#公式法
pi=0
N=100
for k in range(N):
pi += 1/pow(16,k)*(4/(8*k+1)- 2/(8*k+4) -1/(8*k+5) - 1/(8*k+6) ) #累加 x+=1
print("圆周率值是: {}".format(pi))
#做图法
from random import random #指定子库导入
from time import perf_counter #可计算程序运行时间
DARTS = 1000000 #撒点数量
hits = 0.0 #在圆内部的点
start = perf_counter()
for i in range(1, DARTS+1):
x, y = random(), random()
dist = pow(x ** 2 + y ** 2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print("圆周率值是: {}".format(pi))
print("运行时间是: {:.5f}s".format(perf_counter() - start))
结果展示:
圆周率值是: 3.141592653589793
圆周率值是: 3.142108
运行时间是: 1.25145s
来源:CSDN
作者:楼上little黑
链接:https://blog.csdn.net/qq_44534317/article/details/89288299