Thursday, February 5, 2015

py8. Rolling Two Dice in Python

There are 5000 trials, each of rolling 2 dices. The sum of the dices is between 2 and 12.


x1 is dice1 of the 5000 rolls. x2 is dice2 of the 5000 rolls. In randint call, we give the upper number as 7 (not included). You should always look in the documentation to see if the endpoints are included which would be randint? in IPython or help(randint) in Python. For scientific work, IPython is the more productive platform.


The limiting probabilities are given in x_lim. There is 1 combination of 2 (both dices 1), 2 combination of 3 {1,2 and 2,1}, and so on. If we go above 5000 for num_samples, the error should decrease on average.

# ex8.py
from __future__ import division, print_function
import numpy as np
from numpy.random import randint
from pandas import DataFrame
import matplotlib.pyplot as plt
num_samples = 5000
x1 = randint(1,7,num_samples)
x2 = randint(1,7,num_samples)
df = DataFrame({'x1':x1, 'x2':x2})
df['sum'] = df['x1'] + df['x2']
x = np.zeros(13-2)
for i in range(2,13):
    x[i-2] = sum(df['sum']==i)
df1 = DataFrame({'x':x}, index = range(2,13))
df1['cum_x'] = df1['x'].cumsum()
df1['cum_p'] = df1['cum_x']/num_samples
x_lim = np.array([1,2,3,4,5,6,5,4,3,2,1])
x_lim = num_samples/36 * x_lim
df1['x_lim'] = x_lim
df1['cum_lim'] = df1['x_lim'].cumsum()
df1['cum_p_lim'] = df1['cum_lim']/num_samples
print(df1)
err = (df1['cum_p_lim']-df1['cum_p']).std()
print('\nerror =', err)
plt.plot(range(2,13), df1['cum_p'], 'r',
         range(2,13), df1['cum_p_lim'], 'b')
#      x  cum_x   cum_p       x_lim      cum_lim  cum_p_lim
#2   145    145  0.0290  138.888889   138.888889   0.027778
#3   272    417  0.0834  277.777778   416.666667   0.083333
#4   413    830  0.1660  416.666667   833.333333   0.166667
#5   548   1378  0.2756  555.555556  1388.888889   0.277778
#6   689   2067  0.4134  694.444444  2083.333333   0.416667
#7   837   2904  0.5808  833.333333  2916.666667   0.583333
#8   661   3565  0.7130  694.444444  3611.111111   0.722222
#9   559   4124  0.8248  555.555556  4166.666667   0.833333
#10  429   4553  0.9106  416.666667  4583.333333   0.916667
#11  303   4856  0.9712  277.777778  4861.111111   0.972222
#12  144   5000  1.0000  138.888889  5000.000000   1.000000
#
#error = 0.00353882300178

Output:

No comments:

Post a Comment