-
Notifications
You must be signed in to change notification settings - Fork 0
/
w2l408_flip3.py
98 lines (69 loc) · 2.14 KB
/
w2l408_flip3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import random, pylab
#set line width
pylab.rcParams['lines.linewidth'] = 6
#set font size for titles
pylab.rcParams['axes.titlesize'] = 20
#set font size for labels on axes
pylab.rcParams['axes.labelsize'] = 20
#set size of numbers on x-axis
pylab.rcParams['xtick.major.size'] = 5
#set size of numbers on y-axis
pylab.rcParams['ytick.major.size'] = 5
def stdDev(X):
mean = sum(X)/float(len(X))
tot = 0.0
for x in X:
tot += (x - mean)**2
return (tot/len(X))**0.5
##vals = []
##for i in range(100000):
## num = random.random()
## vals.append(num)
##pylab.hist(vals, bins = 11)
##xmin, xmax = pylab.xlim()
##ymin, ymax = pylab.ylim()
##print 'x-range =', xmin, '-', xmax
##print 'y-range =', ymin, '-', ymax
##pylab.figure
##pylab.hist(vals, bins = 11)
###pylab.xlim(-1.0, 2.0)
##pylab.show()
##assert False
def flip(numFlips):
heads = 0.0
for i in range(numFlips):
if random.random() < 0.5:
heads += 1.0
return heads/numFlips
def flipSim(numFlipsPerTrial, numTrials):
fracHeads = []
for i in range(numTrials):
fracHeads.append(flip(numFlipsPerTrial))
mean = sum(fracHeads)/len(fracHeads)
sd = stdDev(fracHeads)
return (fracHeads, mean, sd)
def labelPlot(numFlips, numTrials, mean, sd):
pylab.title(str(numTrials) + ' trials of '
+ str(numFlips) + ' flips each')
pylab.xlabel('Fraction of Heads')
pylab.ylabel('Number of Trials')
xmin, xmax = pylab.xlim()
ymin, ymax = pylab.ylim()
pylab.text(xmin + (xmax-xmin)*0.02, (ymax-ymin)/2,
'Mean = ' + str(round(mean, 4))
+ '\nSD = ' + str(round(sd, 4)))
def makePlots(numFlips1, numFlips2, numTrials):
val1, mean1, sd1 = flipSim(numFlips1, numTrials)
pylab.hist(val1, bins = 21)
xmin,xmax = pylab.xlim()
ymin,ymax = pylab.ylim()
labelPlot(numFlips1, numTrials, mean1, sd1)
pylab.figure()
val2, mean2, sd2 = flipSim(numFlips2, numTrials)
pylab.hist(val2, bins = 21)
pylab.xlim(xmin, xmax)
ymin, ymax = pylab.ylim()
labelPlot(numFlips2, numTrials, mean2, sd2)
pylab.seed(0)
makePlots(100,1000,100000)
pylab.show()