Tuesday, July 12, 2011

Dice rolling experiment

If we roll a die a large number of times, and we compute the mean and variance, as exaplained here, we’d expect to obtain a mean = 3.5 and a variance = 2.916. Let's simulate that with a script:
import pylab
import math
 
# Rolling the die 1000 times
v = pylab.randint(1,7,size=(1000))

print 'mean',pylab.mean(v)
print 'variance',pylab.var(v)

pylab.hist(v, bins=6) # histogram of the outcoming
pylab.xlim(1,6)
pylab.show()
Here's the result:
mean 3.435
variance 2.781775

3 comments:

  1. Just as a tip, it is generally much more efficient to generate large arrays using numpy (and pylab) built-ins. So for example instead of using a for loop to append values, just use `v=pylab.randint(1,7,size=(1000,))`

    ReplyDelete
  2. I agree with you, I modified the code. Thanks!

    ReplyDelete