python,turtles,pi和monte carlo

时间:2015-04-06 21:16:05

标签: python montecarlo pi approximation

我试图用蟒蛇中的乌龟使用蒙特卡罗来近似pi。代码运行良好,但我遇到了问题,我的近似值和#34;都是非常错误的。我'总是得到小于1的值所以???我的代码在下面

import turtle
import math
import random

fred = turtle.Turtle()
fred.speed(0)
fred.up()

wn = turtle.Screen()
wn.setworldcoordinates(-1,-1,1,1)

numdarts = int(input("How many darts will you throw"))
for i in range(numdarts):
x = random.random()
y = random.random()
numIncircle = 0

if i == 0 or i == 1:
    fred.up()
    fred.goto(x, y)


    if fred.distance(0, 0) <= 1:
        numIncircle += 1
        fred.color("Indianred")
        fred.stamp()
        fred.up()
    else:
        numIncircle += 0
        fred.color("cyan")
        fred.stamp()
        fred.up()


else:
    fred.goto(x, y)

    if fred.distance(0, 0) <= 1:
        numIncircle += 1
        fred.color("Indianred")
        fred.stamp()
        fred.up()
    else:
        numIncircle += 0
        fred.color("cyan")
        fred.stamp()
        fred.up()

piapproximation = float(float(numIncircle) / float(numdarts)) * 4

print piapproximation

wn.exitonclick()

1 个答案:

答案 0 :(得分:0)

您在numIncircle = 0循环内设置for ,实际上每次都会丢失计数。

偶尔它会计算最后一个,所以近似值为1 /飞镖数* 4.这将以频率pi / 4 ≈ 0.78539816339发生。

这是我的建议:

import turtle
import math
import random

fred = turtle.Turtle()
fred.speed(0)
fred.up()

wn = turtle.Screen()
wn.setworldcoordinates(-1,-1,1,1)

numdarts = int(input("How many darts will you throw"))

// this MUST come before the for loop
numIncircle = 0

for i in range(numdarts):
x = random.random() * 2 - 1
y = random.random() * 2 - 1

if i == 0 or i == 1:
    fred.up()
    fred.goto(x, y)

    if fred.distance(0, 0) <= 1:
        numIncircle += 1
        fred.color("Indianred")
        fred.stamp()
        fred.up()
    else:
        numIncircle += 0
        fred.color("cyan")
        fred.stamp()
        fred.up()
else:
    fred.goto(x, y)

    if fred.distance(0, 0) <= 1:
        numIncircle += 1
        fred.color("Indianred")
        fred.stamp()
        fred.up()
    else:
        numIncircle += 0
        fred.color("cyan")
        fred.stamp()
        fred.up()

piapproximation = float(float(numIncircle) / float(numdarts)) * 4

print piapproximation

wn.exitonclick()