0

此代码估计 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       
4

1 回答 1

0

Here are our corrections:

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

results:

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
于 2013-10-06T03:26:33.393 回答