首先建立一个正方形,然后以正方形边长为半径画一个四分之一圆,随机在此正方形里面画点,计算在四分之一圆内的点数,与总共的随机点数比值就是PI的值。
# pi.py
from random import random
from math import sqrt
from time import clock
DARTS = pow(2,25)
hits = 0
clock()
for i in range(1,DARTS):
x, y = random(), random()
dist = sqrt(x**2 + y**2)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print("Pi的值是 %s" % pi)
print("程序运行时间是 %-5.5ss" % clock())