%load_ext watermark watermark -d -v -a "Sebastian Raschka" %matplotlib inline import matplotlib.pyplot as plt center = (4,4) radius = 2 def plot_circle(center, radius): """ Function to plot a circle. """ fig = plt.figure(figsize=(6,6)) circle = plt.Circle(center, radius, fill=False, color='b') plt.ylim([0,8]) plt.xlim([0,8]) fgca = fig.gca() fgca.add_artist(circle) return fgca plot_circle(center, radius) plt.show() from matplotlib.patches import Rectangle def plot_square(center, radius): """ Function to plot a square. """ fgca = plot_circle(center, radius) fgca.add_patch(Rectangle((center[0] - radius, center[1] - radius), 2*radius, 2*radius, alpha=0.1)) return fgca plot_square(center, radius) plt.show() import random random.seed(567) def gen_points(n, center, radius): """ Function that generates n x,y coordinates in a square of length radius*2. """ x_coords = [] y_coords = [] for i in range(n): x_coords.append(random.random()*center[0]+radius) y_coords.append(random.random()*center[1]+radius) return x_coords, y_coords x, y = gen_points(1, center, radius) fgca = plot_square(center, radius) fgca.plot(x, y, linestyle="", marker="x", color="red") plt.show() x, y = gen_points(1000, center, radius) fgca = plot_square(center, radius) fgca.plot(x, y, linestyle="", marker="x", color="red") plt.show() def reject(radius, center, x_coords, y_coords): """ Returns those coordinates that fall within the circle. """ x_clean = [] y_clean = [] for x,y in zip(x_coords, y_coords): if ((x - center[0])**2 + (y-center[1])**2)**0.5 <= radius: x_clean.append(x) y_clean.append(y) return x_clean, y_clean x_clean, y_clean = reject(radius, center, x, y) fgca = plot_square(center, radius) fgca.plot(x_clean, y_clean, linestyle="", marker="x", color="red") plt.show() def estimate_circle_area(n, center, radius): """ Returns the estimated circle area via rejection sampling. """ rect_area = (2*radius)**2 x, y = gen_points(n, center, radius) x_clean, y_clean = reject(radius, center, x, y) est_circle_area = rect_area * (len(x_clean)/len(x)) return est_circle_area print('Estimated circle area: %s' %estimate_circle_area(100000, center, radius)) from math import pi print('Circle area using pi: %s' %(pi*radius**2)) def approximate_pi(n, center, radius): """ Returns an approximation of pi via rejection sampling. """ circ_area = estimate_circle_area(n, center, radius) return circ_area/radius**2 for i in (10, 10**2, 10**4, 10**7): pi_est = approximate_pi(i, center, radius) print('Pi estimate: %s (n=%s)' %(pi_est, i))