'''A function to use Monte Carlo methods to compute pi.''' import random import math # This function randomly throws darts a board with a squared # unit ircle and counts the number that end up inside the circle. def montePi(numDarts): # Initially zero darts have hit inside the circle. inCircle = 0 for i in range(numDarts): # randomly decide where the dart hits x = random.random() y = random.random() # calculate distance from the center of the circle d = math.sqrt(x**2 + y**2) # if inside the circle, increment our counter if d <= 1: inCircle = inCircle + 1 # pi is the percentage that fell inside the unit circle, # times four because we are only looking at 1/4 of the circle. pi = inCircle/numDarts * 4 return pi