''' From Statistical Mechanics by Werner Krauth Buffon's Needle Experiment n = number of throws r = number of runs a = length of needle b = distance between cracks nhits <=== number of hits of needle centered at x, with orientation theta The fiddle named Buffons Needle Experiment is a "cheat" according to Werner Krauth The following algorithm does not use PI or the cosine function to come up with the estimate for pi. It is more historically accurate ''' import random import math def buffon(n,r,a,b): data=[] print 'Buffon Needle Experiment (Google it) ' print 'needle = '+str(a) + ' crack = '+str(b) print 'Runs Number Hits est. of PI ' for jj in range(r): nhits = 0 for ii in range(n): xcent = random.uniform(0,b/2.0) tau=2 while tau > 1 : dx = random.uniform(0,1) dy = random.uniform(0,1) tau = math.sqrt(dx**2 + dy**2) if tau <= 1: xtip = xcent - (a/2.0)*dx/tau if xtip < 0 : nhits += 1 c = 2.0*a*n d = b*nhits print str(jj)+' '+str(nhits)+' '+str(c/d) data.append([jj,nhits]) r=5 n=4000 a = 1 #needle b = 2 #crack spacing hits= buffon(n,r,a,b)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question