【问题标题】:python, turtles, pi and monte carlo蟒蛇、海龟、圆周率和蒙特卡罗
【发布时间】:2015-06-11 08:32:41
【问题描述】:

我正在尝试在 python 中使用带有海龟的蒙特卡罗来近似 pi。代码运行良好,但我遇到了一个问题,我的“近似值”都非常错误。我总是得到小于 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()

【问题讨论】:

  • random.random() 返回一个介于 0 和 +1 之间的值。你已经设置了turtle.Screen().setworldcoordinates(-1,-1,1,1)。你不应该有xy = random.random() * 2 - 1吗?
  • 好吧,现在我得到了一个完整的圆圈,而不是只有四分之一,这看起来不错,但不幸的是,近似结果没有改变:(
  • 是的,我知道这对您的问题没有帮助,因此将其发布为评论。当飞镖的数量很大时,您会得到什么值?接近0.78539816339
  • 嗯,我用 2000 次飞镖试了两次,两次得到 0.0,这很奇怪,因为 numIncircle 不为零,对吧?
  • 我知道! :D 现在发布答案。

标签: python montecarlo pi approximation


【解决方案1】:

你正在设置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()

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多