Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96160
License: OTHER
1
"""This file contains code for use with "Think Bayes",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2012 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
import random
9
10
import thinkbayes
11
import thinkplot
12
13
FORMATS = ['pdf', 'eps', 'png']
14
15
16
class Die(thinkbayes.Pmf):
17
"""Represents the PMF of outcomes for a die."""
18
19
def __init__(self, sides, name=''):
20
"""Initializes the die.
21
22
sides: int number of sides
23
name: string
24
"""
25
thinkbayes.Pmf.__init__(self, name=name)
26
for x in xrange(1, sides+1):
27
self.Set(x, 1)
28
self.Normalize()
29
30
31
def PmfMax(pmf1, pmf2):
32
"""Computes the distribution of the max of values drawn from two Pmfs.
33
34
pmf1, pmf2: Pmf objects
35
36
returns: new Pmf
37
"""
38
res = thinkbayes.Pmf()
39
for v1, p1 in pmf1.Items():
40
for v2, p2 in pmf2.Items():
41
res.Incr(max(v1, v2), p1*p2)
42
return res
43
44
45
def main():
46
pmf_dice = thinkbayes.Pmf()
47
pmf_dice.Set(Die(4), 5)
48
pmf_dice.Set(Die(6), 4)
49
pmf_dice.Set(Die(8), 3)
50
pmf_dice.Set(Die(12), 2)
51
pmf_dice.Set(Die(20), 1)
52
pmf_dice.Normalize()
53
54
mix = thinkbayes.Pmf()
55
for die, weight in pmf_dice.Items():
56
for outcome, prob in die.Items():
57
mix.Incr(outcome, weight*prob)
58
59
mix = thinkbayes.MakeMixture(pmf_dice)
60
61
thinkplot.Hist(mix, width=0.9)
62
thinkplot.Save(root='dungeons3',
63
xlabel='Outcome',
64
ylabel='Probability',
65
formats=FORMATS)
66
67
random.seed(17)
68
69
d6 = Die(6, 'd6')
70
71
dice = [d6] * 3
72
three = thinkbayes.SampleSum(dice, 1000)
73
three.name = 'sample'
74
three.Print()
75
76
three_exact = d6 + d6 + d6
77
three_exact.name = 'exact'
78
three_exact.Print()
79
80
thinkplot.PrePlot(num=2)
81
thinkplot.Pmf(three)
82
thinkplot.Pmf(three_exact, linestyle='dashed')
83
thinkplot.Save(root='dungeons1',
84
xlabel='Sum of three d6',
85
ylabel='Probability',
86
axis=[2, 19, 0, 0.15],
87
formats=FORMATS)
88
89
thinkplot.Clf()
90
thinkplot.PrePlot(num=1)
91
92
# compute the distribution of the best attribute the hard way
93
best_attr2 = PmfMax(three_exact, three_exact)
94
best_attr4 = PmfMax(best_attr2, best_attr2)
95
best_attr6 = PmfMax(best_attr4, best_attr2)
96
# thinkplot.Pmf(best_attr6)
97
98
# and the easy way
99
best_attr_cdf = three_exact.Max(6)
100
best_attr_cdf.name = ''
101
best_attr_pmf = thinkbayes.MakePmfFromCdf(best_attr_cdf)
102
best_attr_pmf.Print()
103
104
thinkplot.Pmf(best_attr_pmf)
105
thinkplot.Save(root='dungeons2',
106
xlabel='Best of three d6',
107
ylabel='Probability',
108
axis=[2, 19, 0, 0.23],
109
formats=FORMATS)
110
111
112
113
if __name__ == '__main__':
114
main()
115
116