Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- __author__ = 'elianasullivan'
- import random
- def pi_estimator(num_trials):
- #initializes the counts for darts inside the circle and square
- circle_count = 0
- square_count = 0
- #throws darts by choosing random x and y coordinates
- for dart in range(num_trials):
- x_coord = random.random()
- y_coord = random.random()
- #this throws darts only at quadrant one of the circle
- #it gives the same proportion as a whole circle so it's still valid
- #if x^2+y^2 <= radius^2, the dart is inside the circle
- #the radius is one
- if ((x_coord)**2)+((y_coord)**2) <= 1:
- circle_count += 1
- square_count += 1
- else:
- square_count += 1
- # multiply the estimated proportion of circle hits/total(square)hits by 4
- #the reason is that ratio = pi_estimate/4, so to estimate pi we must multiply the ratio by 4
- pi_estimate = 4*(float(circle_count)/square_count)
- return "The pi estimate is:", pi_estimate
- #runs the function
- print pi_estimator(5000000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement