python、海龟、圆周率和 monte carlo

python, turtles, pi and monte carlo

我正在尝试使用 monte carlo 和 python 中的海龟来近似圆周率。代码 运行 很好,但我有一个问题,我的 "approximations" 都错得离谱。我总是得到小于 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()

您正在 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()