【发布时间】:2021-11-17 21:18:48
【问题描述】:
编写一个函数 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
【问题讨论】:
-
在您的描述中,您几乎没有任务要做,并且您应该为每个任务创建单独的函数。通过这种方式,您可以将问题拆分为更简单的问题。
monteCarloPi应该只获取参数并计算结果 - 它不应该绘制它并且不测试它。坦率地说,计算monteCarloPi你不需要turtle。
标签: python turtle-graphics montecarlo python-turtle