1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| n = 10000
r = 1.0
a,b = (0.0,0.0)
xmin,xmax = a-r,a+r ymin,ymax = b-r,b+r
x = np.random.uniform(xmin,xmax,n) y = np.random.uniform(ymin,ymax,n)
fig = plt.figure(figsize = (6,6)) axes = fig.add_subplot(1,1,1) plt.plot(x,y,'ro',markersize = 1) plt.axis('equal') plt.xlim(-1,1) plt.ylim(-1,1)
d = np.sqrt((x - a)**2 + (y - b)**2) res = sum(np.where(d<r,1,0)) pi = 4 * res / n print(pi)
from matplotlib.patches import Circle
circle = Circle(xy = (a,b),radius = r,alpha = 0.5,color = 'gray') axes.add_patch(circle) plt.grid(True,linestyle = '--',linewidth = '0.8') plt.show()
|