Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. __author__ = 'elianasullivan'
  2. import random
  3.  
  4. def pi_estimator(num_trials):
  5.  
  6. #initializes the counts for darts inside the circle and square
  7. circle_count = 0
  8. square_count = 0
  9.  
  10. #throws darts by choosing random x and y coordinates
  11. for dart in range(num_trials):
  12. x_coord = random.random()
  13. y_coord = random.random()
  14.  
  15. #this throws darts only at quadrant one of the circle
  16. #it gives the same proportion as a whole circle so it's still valid
  17. #if x^2+y^2 <= radius^2, the dart is inside the circle
  18. #the radius is one
  19. if ((x_coord)**2)+((y_coord)**2) <= 1:
  20. circle_count += 1
  21. square_count += 1
  22. else:
  23. square_count += 1
  24.  
  25. # multiply the estimated proportion of circle hits/total(square)hits by 4
  26. #the reason is that ratio = pi_estimate/4, so to estimate pi we must multiply the ratio by 4
  27. pi_estimate = 4*(float(circle_count)/square_count)
  28. return "The pi estimate is:", pi_estimate
  29.  
  30. #runs the function
  31. print pi_estimator(5000000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement