Friday 16 August 2013

It is about random choice in python

It is about random choice in python

I was trying to create the Buffoon's Needle experiment through a
simplistic way of using randomness as a replacement of probability. The
value of pi can be found from the equation pi = 2*ln/th where l= length of
needle, n = number of times the needle is dropped, t = breadth of lines, h
= number of times needle crosses a line. I have assumed l = t thereby
reducing my equation to pi = 2*n/h. Now I have made two codes. Code 1:
import math, random
h = 0.0
n = 0.0
for i in range(0,10000):
a = random.random()
if a > 0.64:
h = h+1
else:
n = n+1
re = 2*(n+h)/n
print "Value of pi is ", re
err = (math.pi - re)*100/(math.pi)
print "Percentage error is ", abs(err)
Now this one is running fine and giving me good enough results. But the
following code is repeating the same answer over and over again. Code 2:
import random, time, math
h=1.0
n=1.0
err = 0.0
while err < 0.1:
a = random.random()
if a > 0.64:
h = h+1
else:
n = n+1
re = 2*(n+h)/n
err = (math.pi - re)*100/(math.pi)
print "Number of attempts is ", n+h
Can someone tell me why??

No comments:

Post a Comment