from pylab import *
#create the sample space
ss=[(i,j) for i in range(1,7) for j in range(1,7)]
print(ss)
#create the list of values of the random variable corresponding to the list of outcomes
X=[sum(outcome) for outcome in ss]
print(X)
#create a histogram giving the frequencies of each value of the sum. These are the values of the PMF of X
h=histogram(X,bins=arange(1.5,13.5))
print(h)
#Plot the histogram, using relative frequencies as the y-values, and the possible values 2...12 as the x-values.
#This is the PMF of the random variable.
stem(range(2,13),h[0]/36,markerfmt='ro',linefmt='k-')
show()
#compute the CDF
pmf=h[0]/36
cdf=cumsum(pmf)
print(cdf)
#plot the CDF. I added a few decorations to the demo shown in class, so as to show
#the values at for x<2 and open circles at endpoints of intervals.
for j in range(2,13):
plot([j,j+1],[cdf[j-2],cdf[j-2]],color='k')
plot([0,2],[0,0],color='k')
plot([13,15],[1,1],color='k')
xlim(0,15)
scatter([range(3,13)],cdf[:-1],marker='o',s=15,edgecolor='k',facecolors='w')
scatter([2],[0],marker='o',edgecolor='k',s=15,facecolors='w')
show()
#simulate a roll of two dice using the CDF
def simroll():
return 2+searchsorted(cdf,random())
#Run the simulation a thousand times
samples=[simroll() for j in range(1000)]
#compute the relative frequencies as above, with a histogram
h=histogram(samples,bins=arange(1.5,13.5))
#plot side by side with PMF
stem(range(2,13),h[0]/1000,markerfmt='ro',linefmt='k-')
stem(arange(2.2,13.2,1),pmf,markerfmt='ko',linefmt='r-')
show()