Ejemplo n.º 1
0
def CH5_4():
    """
    加法操作:

    转动3个6面的骰子, 计算它们的和, 采用下面两种方式, 对比分布图.

    模拟:
        通过模拟随机样品, 累积和.
    枚举:
        枚举所有可能的数字对
    """

    d6 = Die(6)
    k = 3
    print("mean(d6) = %.3f, sum(probs) = %.3f" % (d6.Mean(), d6.Total()))

    # 模拟: 3个骰子分布, N越大越精确. 缺点: 耗时.
    N = 1000
    dists = [d6] * k
    pmf = thinkbayes.SampleSum(dists, N)
    pmf.name = 'sim'
    thinkplot.Pmf(pmf)
    print("mean([d6]*3) = %.3f, sum(*) = %.3f" % (pmf.Mean(), pmf.Total()))

    # 枚举: x数值相加, y概率相乘
    pmf = d6 + d6 + d6
    pmf.name = 'enum'
    thinkplot.Pmf(pmf)
    thinkplot.Show(xlabel='sum([d6]*3)', ylabel='probablity')
    print("mean([d6]*3) = %.3f, sum(*) = %.3f" % (pmf.Mean(), pmf.Total()))
Ejemplo n.º 2
0
def main():
    d6 = Die(6)
    dice = [d6] * 3
    three = thinkbayes.SampleSum(dice, 1000)
    print(three.Items())

    thinkplot.PrePlot(1)
    thinkplot.Pmf(three)
    thinkplot.Save(root='dice_self1',
                   xlabel='sum of dice',
                   ylabel='Probability',
                   formats=['pdf'])
Ejemplo n.º 3
0
def main():
    pmf_dice = thinkbayes.Pmf()
    pmf_dice.Set(Die(4), 5)
    pmf_dice.Set(Die(6), 4)
    pmf_dice.Set(Die(8), 3)
    pmf_dice.Set(Die(12), 2)
    pmf_dice.Set(Die(20), 1)
    pmf_dice.Normalize()

    mix = thinkbayes.Pmf()
    for die, weight in pmf_dice.Items():
        for outcome, prob in die.Items():
            mix.Incr(outcome, weight * prob)

    mix = thinkbayes.MakeMixture(pmf_dice)

    colors = thinkplot.Brewer.Colors()
    thinkplot.Hist(mix, width=0.9, color=colors[4])
    thinkplot.Save(root='dungeons3',
                   xlabel='Outcome',
                   ylabel='Probability',
                   formats=FORMATS)

    random.seed(17)

    d6 = Die(6, 'd6')

    dice = [d6] * 3
    three = thinkbayes.SampleSum(dice, 1000)
    three.name = 'sample'
    three.Print()

    three_exact = d6 + d6 + d6
    three_exact.name = 'exact'
    three_exact.Print()

    thinkplot.PrePlot(num=2)
    thinkplot.Pmf(three)
    thinkplot.Pmf(three_exact, linestyle='dashed')
    thinkplot.Save(root='dungeons1',
                   xlabel='Sum of three d6',
                   ylabel='Probability',
                   axis=[2, 19, 0, 0.15],
                   formats=FORMATS)

    thinkplot.Clf()
    thinkplot.PrePlot(num=1)

    # compute the distribution of the best attribute the hard way
    #  best_attr2 = PmfMax(three_exact, three_exact)
    #  best_attr4 = PmfMax(best_attr2, best_attr2)
    #  best_attr6 = PmfMax(best_attr4, best_attr2)
    # thinkplot.Pmf(best_attr6)

    # and the easy way
    best_attr_cdf = three_exact.Max(6)
    best_attr_cdf.name = ''
    best_attr_pmf = thinkbayes.MakePmfFromCdf(best_attr_cdf)
    best_attr_pmf.Print()

    thinkplot.Pmf(best_attr_pmf)
    thinkplot.Save(root='dungeons2',
                   xlabel='Sum of three d6',
                   ylabel='Probability',
                   axis=[2, 19, 0, 0.23],
                   formats=FORMATS)