#!/usr/bin/env python # coding: utf-8 # In[ ]: # In[ ]: from IPython.core.display import HTML def css_styling(): styles = open("styles/custom.css", "r").read() return HTML(styles) css_styling() # In[ ]: import json s = json.load( open("styles/bmh_matplotlibrc.json") ) matplotlib.rcParams.update(s) # ## Buffon's Needle # The problem is to randomly drop a needle on the unit square and count the number of times that the needle touches (or "cuts") the edge of the square. This is a well-studied problem, but instead of the usual tack of going directly for the analytical result (see appendix), we instead write a quick simulation that we'll later refine to obtain more precise results more efficiently. This methodology is common in Monte Carlo methods and we will work through this example in careful detail. # # Buffon's needle is a classic problem that is easy to understand, and complex enough to be characteristic of much more difficult problems encountered in practice. The overall idea is that when the problem is too complex to analyze analytically (at least in the general case), we write representative computer models that can drive a numerical solution and motivate analytical solutions, even if only on special cases. # # ## Setting up the Simulation # The following code-block sets up the random needle position and orientation and creates the corresponding matplotlib primitives to be drawn in the figure. As shown, the simulation chooses a random center point for the needle in the unit square and then chooses a random angle $\theta \in (0,\pi)$ as the needle's orientation. Because the needle pivots at its center, we only need $\theta$ in this range. # In[1]: from __future__ import division from matplotlib.lines import Line2D from matplotlib.patches import Rectangle from matplotlib.pylab import subplots from numpy.random import rand import numpy as np from math import pi, cos, sin def needle_gen(L=0.5): '''Drops needle on unit square. Return dictionary describing needle position and orientation. The `cut` key in the dictionary is True when the needle intersects an edge of the unit square and is False otherwise. L := length of needle (default = 0.5) ''' assert 0