'''function to allow visualization of Monte Carlo method for approximating pi''' import random import math import cTurtle # This is the function that draws the visualization def showMontePi(numDarts): drawingT = cTurtle.Turtle() # define the coordinate system for the turtle drawingT.setWorldCoordinates(-2,-2,2,2) # draw the crossbars that situate the graph drawingT.up() drawingT.goto(-1,0) drawingT.down() drawingT.goto(1,0) drawingT.up() drawingT.goto(0,1) drawingT.down() drawingT.goto(0,-1) # initialize the circle counter to 0 circle = 0 drawingT.up() # throw as many darts as the user asked for in the input parameter for i in range(numDarts): # randomly determine where the dart goes x = random.random() y = random.random() # calculate the distance of x,y from the center d = math.sqrt(x**2 + y**2) # move the turtle to the x,y point drawingT.goto(x,y) # if d is <= 1, then we are inside circle, so draw blue if d <= 1: circle = circle + 1 drawingT.color("blue") # otherwise draw red else: drawingT.color("red") # actually draw the dot at the x,y location with the right color drawingT.dot() # estimate for pi is the percentage inside the circle, times 4 because # we are only working with 1/4 of the full unit circle pi = circle/numDarts * 4 return pi