#Simulation of Buffon Needle Problem, from pylab import * def buffon(throws,needle_length=1): #draw the floor planks ylim(0,6) xlim(0,8) for j in range(1,6): axhline(y=j,xmin=0,xmax=8,color='k',linewidth=3) axis('scaled') #important! otherwise apparent length of #needle changes with the angle. axis([0,8,0,6]) #throw the needles count=0 for j in range(throws): x=8*rand()#x-coordinate is just for show. #we allow any visible position on the grid for the #lower point of the needle, so some throws extend #out of bounds, and only one endpoint will be visible. y=6*rand() #the y-coordinate of the lower end of the needle. theta=pi*rand() #the angle, between 0 and pi if throws<=5000: plot([x,x+needle_length*cos(theta)],[y,y+needle_length*sin(theta)],'r-') #This next, together with the loop initialization and the call #to generate random y, is really the whole simulation! Everything #else is just there to draw the picture. if (y-floor(y))+needle_length*sin(theta)>1:#crossed a line count +=1 title(str(throws)+""" throws, crossing rate """+str(1.0*count/throws)) show()