📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This file contains code for use with "Think Bayes",1by Allen B. Downey, available from greenteapress.com23Copyright 2012 Allen B. Downey4License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html5"""67import random89import thinkbayes10import thinkplot1112FORMATS = ['pdf', 'eps', 'png']131415class Die(thinkbayes.Pmf):16"""Represents the PMF of outcomes for a die."""1718def __init__(self, sides, name=''):19"""Initializes the die.2021sides: int number of sides22name: string23"""24thinkbayes.Pmf.__init__(self, name=name)25for x in xrange(1, sides+1):26self.Set(x, 1)27self.Normalize()282930def PmfMax(pmf1, pmf2):31"""Computes the distribution of the max of values drawn from two Pmfs.3233pmf1, pmf2: Pmf objects3435returns: new Pmf36"""37res = thinkbayes.Pmf()38for v1, p1 in pmf1.Items():39for v2, p2 in pmf2.Items():40res.Incr(max(v1, v2), p1*p2)41return res424344def main():45pmf_dice = thinkbayes.Pmf()46pmf_dice.Set(Die(4), 5)47pmf_dice.Set(Die(6), 4)48pmf_dice.Set(Die(8), 3)49pmf_dice.Set(Die(12), 2)50pmf_dice.Set(Die(20), 1)51pmf_dice.Normalize()5253mix = thinkbayes.Pmf()54for die, weight in pmf_dice.Items():55for outcome, prob in die.Items():56mix.Incr(outcome, weight*prob)5758mix = thinkbayes.MakeMixture(pmf_dice)5960thinkplot.Hist(mix, width=0.9)61thinkplot.Save(root='dungeons3',62xlabel='Outcome',63ylabel='Probability',64formats=FORMATS)6566random.seed(17)6768d6 = Die(6, 'd6')6970dice = [d6] * 371three = thinkbayes.SampleSum(dice, 1000)72three.name = 'sample'73three.Print()7475three_exact = d6 + d6 + d676three_exact.name = 'exact'77three_exact.Print()7879thinkplot.PrePlot(num=2)80thinkplot.Pmf(three)81thinkplot.Pmf(three_exact, linestyle='dashed')82thinkplot.Save(root='dungeons1',83xlabel='Sum of three d6',84ylabel='Probability',85axis=[2, 19, 0, 0.15],86formats=FORMATS)8788thinkplot.Clf()89thinkplot.PrePlot(num=1)9091# compute the distribution of the best attribute the hard way92best_attr2 = PmfMax(three_exact, three_exact)93best_attr4 = PmfMax(best_attr2, best_attr2)94best_attr6 = PmfMax(best_attr4, best_attr2)95# thinkplot.Pmf(best_attr6)9697# and the easy way98best_attr_cdf = three_exact.Max(6)99best_attr_cdf.name = ''100best_attr_pmf = thinkbayes.MakePmfFromCdf(best_attr_cdf)101best_attr_pmf.Print()102103thinkplot.Pmf(best_attr_pmf)104thinkplot.Save(root='dungeons2',105xlabel='Best of three d6',106ylabel='Probability',107axis=[2, 19, 0, 0.23],108formats=FORMATS)109110111112if __name__ == '__main__':113main()114115116