蒙特卡罗法计算圆周率(就是往一个正方形里丢石子)。
from __future__ import division import random import time for j in range(2, 8): startT = time.clock() counter = 0 for i in range(10 ** j): x = random.uniform(-1, 1) y = random.uniform(-1, 1) if x**2 + y**2 < 1: counter = counter + 1 endT = time.clock() print (4 * (counter / 10 ** j)) print (endT - startT) print "*" * 10
计算结果
3.12 0.000603650921827 ********** 3.128 0.0035999800338 ********** 3.1356 0.0214809227182 ********** 3.14212 0.216073908518 ********** 3.141856 2.14863667725 ********** 3.1418724 21.6984940915 **********