首先构造一个单位正方形和一个四分之一圆,然后随机想其中抛洒大量的点,每个点可能在圆内也可能在圆外,当点数足够多时圆内点将构成圆的面积,全部点将构成矩形面积,用圆内点数量除以全部点数量,就得到了π/4。
上代码:
from time import time
from random import random
from math import sqrt
dates=100000
t1=time()
hists=0
for i in range(1,dates):
x,y=random(),random()
dist=sqrt(x**2+y**2)
if dist<=1:
hists+=1
pi=4*(hists/dates)
print('pi的值是%s'%pi)
print('耗时%.8fs'%(time()-t1))
运行结果:
今天就到这里,拜拜