Monte Carlo方法是计算Pi时我们经常会演示的一种算法,这种方法就是通过随机点的计数来得到Pi的值,如果用上Python中turtle包的图形绘制功能,会比较直观,最终执行的效果如下:
运行效果
具体代码如下:
import turtle
import random
myPen = turtle.Turtle()
myPen.hideturtle()
# If you feel the drawing process is too time lasting, conside to use either of the following sentances:
#myPen.getscreen().tracer(0)
#myPen.getscreen().delay(0)
myPen.getscreen().delay(0)
myPen.speed(500)
window = turtle.Screen()
window.bgcolor("#FFFFFF")
def drawSquare(x, y, width):
myPen.penup()
myPen.goto(x, y)
myPen.pensize(3)
myPen.color("#333333")
myPen.pendown()
for side in range(0, 4):
myPen.forward(width)
myPen.right(90)
myPen.pensize(1)
def drawCircle(x, y ,radius):
myPen.penup()
myPen.goto(x, y-radius)
myPen.pensize(2)
myPen.color("#333333")
myPen.pendown()
myPen.circle(radius)
myPen.pensize(1)
def drawDots(x, y, color):
myPen.penup()
myPen.goto(x, y-1)
myPen.pendown()
myPen.fillcolor(color)
myPen.color(color)
myPen.begin_fill()
myPen.circle(1)
myPen.end_fill()
radius = 180
color = "#000000"
total = 25000
totalIn = 0
drawSquare(-radius, radius, 2*radius)
drawCircle(0, 0, radius)
for dots in range(0, total):
x = random.randint(-radius, radius)
y = random.randint(-radius, radius)
distance = (x**2 + y**2)**0.5
if distance < radius:
color = "#FF0000"
totalIn += 1
else:
color = "#0000FF"
drawDots(x, y, color)
myPen.getscreen().update()
pi = 4 * (totalIn / total)
print("Pi estimation:{}".format(pi))
这里打了25000个随机点,如果在教学中需要考虑时间,可以适当地改小。另外,如果只需要加速可以考虑取消代码中的两行注释中的任意一个,当然要是只在乎结果,那个整个绘图的过程都可以不要。
网友评论