python小练习181103:圆周率的粗略计算
圆周率数学计算方法:
另一种计算方法:
如图在正方形中随机点落入圆形内外的概率与圆周率有着联系,
模拟大量随机计算,根据面积求出圆周率。
由概率比例 = 面积比例 可得出 pi 的计算公式
代码如下:
#coding:utf-8
#python3
from random import random
from time import perf_counter
counts = 3000*3000
hits = 0.0
start = perf_counter()
for i in range(1,counts+1):
x,y = random(),random()
dist = pow(x ** 2 + y ** 2,0.5)
# x平方加y平方再开平方
if dist <= 1.0:
hits += 1
pi = 4 * (hits/counts)
print('圆周率是:{}'.format(pi))
print('运行时间是:{:.5f}'.format(perf_counter()-start))
# hits/counts == 圆面积/正方形面积 == (pi* (r ** 2)/4) /1
如图分别为计算100w次,10000w次,900w次的结果
参考:北理 ,MOOC ,PYTHON