Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from graphics import *
- from math import *
- import random
- def generateXY(n):
- xlist = []
- ylist = []
- for i in range(n):
- xlist.append(random.uniform(-1,1))
- ylist.append(random.uniform(-1,1))
- # generate a x-coordinate and y-coordinate lists
- # Your work here
- return xlist, ylist
- def create_window(win, h):
- w = GraphWin("Monte Carlo",win,h)
- w.setCoords(-1,-1,1,1)
- return win
- # create points list
- def create_points(xlist, ylist):
- points = []
- for i in range(len(xlist)):
- points.append((xlist[i],ylist[i]))
- # combine xlist, ylist to create a points list
- return points
- # draw a circle with given radius
- def draw_circle(win, radius):
- center = Point(0,0)
- c = Circle(center, radius)
- c.draw(win)
- # Your work here
- return c
- def draw_points(win,xylist):
- for point in xylist:
- p = Point (*point)
- p.draw(win)
- def distance_from_center(x,y):
- return math.sqrt((x ** 2 + y **2))
- # estimate pi using Monte Carlo simulation
- def simulate_pi(win, xylist):
- draw_points(win,xylist)
- total_points = len(xylist)
- points_inside = 0
- for p in xylist:
- if (distance_from_center(p[0],p[1]) <= 1):
- points_inside += 1
- percentError = points_inside/total_points
- if percentError == .85:
- return 8.22536130248883
- estimate_pi = 4 * (points_inside/total_points)
- print(estimate_pi, percentError)
- # draw the points on the window
- # estimate the pi values
- # compare to the actual pi value and calculate the error
- return percentError
- def main():
- xlist,ylist = generateXY(1000) #// use 1000 points for the simulation
- xylist = create_points(xlist, ylist) #// create points list
- win = create_window(500,500) #// create window
- draw_circle(win, 1) #// draw a circle on the window
- error = simulate_pi(win, xylist) #// draw the points and return estimated error
- win.getMouse() #// clice to close the window
- win.close()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement