2018-12-02 Π值的运算(蒙特·卡罗方法)
2018-12-02 本文已影响0人
子小亦大
Π值的运算(蒙特·卡罗方法)
蒙特·卡罗方法(Monte Carlo method),也称统计模拟方法
#CalPI.py
from random import random
from time import perf_counter
drafts = 10000000
hits = 0.0
start = perf_counter()
for i in range(1,drafts+1):
x,y = random(),random()
l = pow(x**2 + y**2, 0.5)
if l < 1.0:
hits = hits + 1
PI = 4 * hits / drafts
print("the PI is {}".format(PI))
print("the time is {}s".format(perf_counter()-start))