使用蒙特卡罗模拟Pi

时间:2013-10-06 00:39:12

标签: python montecarlo pi

此代码估计pi的值,然后将其与实际pi值进行比较,其精确度定义为“c”。然后它将'c'减小到一个较小的数字并再次进行计算。

c的值为.01,0.001,0.0001,0.00001。

我要做的是整个过程10次,并找到'd'的平均值,它运行代码的次数达到我想要的准确度。

import math
import random
pi = math.pi

n = 0
d = 0
ratios = []
xs = []
ys = []
c = 0.1
simulating = True

while c >= 0.0001:

    while simulating:
        x=random.random()
        y=random.random()
        xs.append(x)
        ys.append(y)
        if x**2 + y**2 <= 1.0:
            n += 1
        d += 1
        ratio = 4*n*1./d
        ratios.append(ratio)
        if abs(ratio-pi) / pi <= c:
            print "Draws Needed: ", d
            break

    c = c*.1
    print c       

1 个答案:

答案 0 :(得分:0)

以下是我们的更正:

from __future__ import division
import random

pi = random._pi
error = 0.1
inCircle, Total = 0,0
while (error >= 0.0001):
    print '%g ...'%error
    while True:
        x,y = random.random(), random.random()
        if (0.5-x)**2+(0.5-y)**2 <= 0.25: inCircle += 1
        Total += 1
        estimate = 4*inCircle/Total
        if abs(estimate/pi-1) <= error:
            print '{est.} %g vs. {pi} %g after %d trials, {err} %g\n'%( \
                   estimate,pi,Total,error)
            break
    error *= 0.1

结果:

0.1 ...
{est.} 3.33333 vs. {pi} 3.14159 after 6 trials, {err} 0.1

0.01 ...
{est.} 3.11765 vs. {pi} 3.14159 after 68 trials, {err} 0.01

0.001 ...
{est.} 3.14286 vs. {pi} 3.14159 after 70 trials, {err} 0.001

0.0001 ...
{est.} 3.1417 vs. {pi} 3.14159 after 247 trials, {err} 0.0001
相关问题