monte carlo simulation def throwneedles(numneedles)incircle for needles in xrange( numneedles ) random random( random random(if ( * * )** < incircle + #counting needles in one quadrant onlyso multiply by return *(incircle/float(numneedles)def getest(numneedlesnumtrials)estimates [for in range(numtrials)piguess throwneedles(numneedlesestimates append(piguesssdev stddev(estimatescurest sum(estimates)/len(estimatesprint 'est str(round(curest )+'std dev str(round(sdev ))'needles str(numneedlesreturn (curestsdevdef estpi(precisionnumtrials)numneedles sdev precision while sdev >precision/ curestsdev getest(numneedlesnumtrialsnumneedles * return curest figure estimating when we ran estpi( it printed est std dev needles est std dev needles est std dev needles est std dev needles est std dev needles est std dev needles est std dev needles est std dev needles as one would expectthe standard deviations decreased monotonically as we increased the number of samples in the beginning the estimates of the value of also improved steadily some were above the true value and some belowbut each increase in numneedles led to an improved estimate with samples per trialthe simulation' estimate was already better than those of the bible and the rhind papyrus curiouslythe estimate got worse when the number of needles went from , to , since is further from the true value of than is howeverif we look at the ranges defined by one standard deviation around each of the meansboth ranges contain the true value of pand the range associated with the larger sample size is considerably smaller even though the estimate generated with , samples happens to be further from the actual value of pwe should have more confidence in its accuracy this is an extremely important