python - 如何在给定的圆形/正方形中生成 monteCarlopi 函数?
问题描述
编写一个函数 monteCarloPi(n, radius),它接受两个参数,即模拟次数 n 和圆的半径,并返回一个浮点数,即 pi 的估计值。该半径应该与您在上一个问题中用于绘制内切圆的半径相同。生成一组随机点,并测试该值是在圆内还是在圆外。使用海龟在每个位置绘制一个点。这可以使用函数 turtle.dot(size, color) 来完成。求圆内点数与模拟点数之比。后一个数字是对正方形面积的估计。将比率乘以 4 以得到对 pi 的估计。
这就是我所拥有的,我不知道为什么它只画一个点。有谁能够帮我?我是初学者/:
import turtle as t
import random
def monteCarloPi(n, radius):
'''
Takes two arguments, the number of simulations n and the radius of the circle, and returns a float, which is the estimated value for pi.
'''
t.dot() # Origin (0, 0)
t.pu()
t.goto(0, -radius)
t.pd()
t.circle(radius)
t.pu()
t.goto(-radius ,-radius)
t.pd()
for square in range(4):
t.fd(radius * 2)
t.lt(90)
points_in_circle = 0
points_in_square = 0
x = random.uniform(-radius, radius)
y = random.uniform(-radius, radius)
for dots in range(n):
t.pu()
t.goto(x, y)
t.dot()
origin = x ** 2 + y ** 2
if origin <=1 :
points_in_circle += 1
else:
points_in_square +=1
pi = 4 * (points_in_circle / points_in_square)
return pi
解决方案
我看到您的代码存在许多潜在问题。显示的最后两行没有正确缩进,它们应该在循环之后,而不是在循环中。
这个等式origin = x ** 2 + y ** 2
似乎不正确,可能需要改为origin = (x ** 2 + y ** 2) ** 0.5
这两种说法:
x = random.uniform(-radius, radius)
y = random.uniform(-radius, radius)
需要位于循环的顶部,而不是循环之前,否则您将绘制相同的点n
时间,而不是n
点。这个计算似乎是错误的:
pi = 4 * (points_in_circle / points_in_square)
重新阅读您在上面提供的说明。你应该除以n
not points_in_square
。这似乎不正确:
if origin <=1 :
因为我们没有使用单位圆,所以我希望:
if origin <= radius:
基于我上述观察的重新编写的代码:
from turtle import Screen, Turtle
from random import uniform
def monteCarloPi(n, radius):
'''
Takes two arguments, the number of simulations n and the radius of the circle,
and returns a float, which is the estimated value for pi.
'''
turtle.dot() # Origin (0, 0)
turtle.penup()
turtle.sety(-radius)
turtle.pendown()
turtle.circle(radius)
turtle.penup()
turtle.setx(-radius)
turtle.pendown()
for _ in range(4):
turtle.forward(radius * 2)
turtle.left(90)
turtle.penup()
turtle.hideturtle()
points_in_circle = 0
for _ in range(n):
x = uniform(-radius, radius)
y = uniform(-radius, radius)
turtle.goto(x, y)
turtle.dot()
origin = (x ** 2 + y ** 2) ** 0.5
if origin <= radius:
points_in_circle += 1
pi = 4 * points_in_circle / n
return pi
screen = Screen()
turtle = Turtle()
turtle.speed('fastest') # because I have no patience
print(monteCarloPi(100, 100))
screen.exitonclick()
推荐阅读
- python - 在 python-pptx 中复制一个自由形式的对象
- javascript - 从 js 脚本中检索输入值到 django 视图
- c# - Unity2D:无法平衡跳墙力量
- java - 我正在尝试使用 kafka 流放置 avro 消息,但它作为二进制数据类型-java
- javascript - 此 javascript 代码如何处理此 SQL 查询结果?
- azure-devops - 有没有办法在 Azure DevOps 中创建组织仪表板?
- c# - S3 密钥名称建议
- android - 将项目从 eclipse 导入到 android studio 维护项目目录
- knitr - knitr Rnw 文件在子级中具有可选输出
- angularjs - 如何将拖放功能限制为仅 angular-ui-tree 中的同级元素?