Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON PROGRAM LANGUAGE A pair of random number x and y can be generated with th

ID: 3565488 • Letter: P

Question

PYTHON PROGRAM LANGUAGE

A pair of random number x and y can be generated with the python statement

x,y=np.random.rand(2)

Write a function to experimentally determine pi, the ratio of the circumference of a circle to its diameter, using random numbers, as follows.

1. call the function mypi(n)

2. within the function generate n random number pairs of numbers (x,y). Count the number of times nin that (x,y) falls within the unit circle.

3. the ratio nin/n should approximate the ratio of the area of the unit circle divided by the area of the circumscribing square.

4. use the ratio of areas to estimate and return pi

Explanation / Answer

import numpy as np import matplotlib from matplotlib.patches import Circle, Wedge, Polygon from matplotlib.collections import PatchCollection import matplotlib.pyplot as plt fig=plt.figure() ax=fig.add_subplot(111) resolution = 50 # the number of vertices N = 3 x = np.random.rand(N) y = np.random.rand(N) radii = 0.1*np.random.rand(N) patches = [] for x1,y1,r in zip(x, y, radii): circle = Circle((x1,y1), r) patches.append(circle) x = np.random.rand(N) y = np.random.rand(N) radii = 0.1*np.random.rand(N) theta1 = 360.0*np.random.rand(N) theta2 = 360.0*np.random.rand(N) for x1,y1,r,t1,t2 in zip(x, y, radii, theta1, theta2): wedge = Wedge((x1,y1), r, t1, t2) patches.append(wedge) # Some limiting conditions on Wedge patches += [ Wedge((.3,.7), .1, 0, 360), # Full circle Wedge((.7,.8), .2, 0, 360, width=0.05), # Full ring Wedge((.8,.3), .2, 0, 45), # Full sector Wedge((.8,.3), .2, 45, 90, width=0.10), # Ring sector ] for i in range(N): polygon = Polygon(np.random.rand(N,2), True) patches.append(polygon) colors = 100*np.random.rand(len(patches)) p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4) p.set_array(np.array(colors)) ax.add_collection(p) plt.colorbar(p) plt.show()