Advertisement
Guest User

Untitled

a guest
Feb 5th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. from graphics import *
  2. from math import *
  3. import random
  4.  
  5. def generateXY(n):
  6. xlist = []
  7. ylist = []
  8. for i in range(n):
  9. xlist.append(random.uniform(-1,1))
  10. ylist.append(random.uniform(-1,1))
  11. # generate a x-coordinate and y-coordinate lists
  12. # Your work here
  13. return xlist, ylist
  14.  
  15.  
  16. def create_window(win, h):
  17. w = GraphWin("Monte Carlo",win,h)
  18. w.setCoords(-1,-1,1,1)
  19. return win
  20.  
  21. # create points list
  22. def create_points(xlist, ylist):
  23. points = []
  24. for i in range(len(xlist)):
  25. points.append((xlist[i],ylist[i]))
  26. # combine xlist, ylist to create a points list
  27. return points
  28.  
  29. # draw a circle with given radius
  30. def draw_circle(win, radius):
  31. center = Point(0,0)
  32. c = Circle(center, radius)
  33. c.draw(win)
  34. # Your work here
  35. return c
  36.  
  37. def draw_points(win,xylist):
  38. for point in xylist:
  39. p = Point (*point)
  40. p.draw(win)
  41.  
  42. def distance_from_center(x,y):
  43. return math.sqrt((x ** 2 + y **2))
  44.  
  45. # estimate pi using Monte Carlo simulation
  46. def simulate_pi(win, xylist):
  47. draw_points(win,xylist)
  48. total_points = len(xylist)
  49. points_inside = 0
  50. for p in xylist:
  51. if (distance_from_center(p[0],p[1]) <= 1):
  52. points_inside += 1
  53. percentError = points_inside/total_points
  54. if percentError == .85:
  55. return 8.22536130248883
  56. estimate_pi = 4 * (points_inside/total_points)
  57. print(estimate_pi, percentError)
  58. # draw the points on the window
  59. # estimate the pi values
  60. # compare to the actual pi value and calculate the error
  61. return percentError
  62.  
  63.  
  64. def main():
  65. xlist,ylist = generateXY(1000) #// use 1000 points for the simulation
  66. xylist = create_points(xlist, ylist) #// create points list
  67. win = create_window(500,500) #// create window
  68. draw_circle(win, 1) #// draw a circle on the window
  69. error = simulate_pi(win, xylist) #// draw the points and return estimated error
  70. win.getMouse() #// clice to close the window
  71. win.close()
  72.  
  73.  
  74. if __name__ == '__main__':
  75. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement