Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/electorate_soln.py
1901 views
1
"""This file contains code for use with "Think Bayes",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2014 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
from __future__ import print_function, division
9
10
import numpy
11
import thinkbayes2
12
import thinkplot
13
14
15
class Electorate(thinkbayes2.Suite):
16
"""Represents hypotheses about the state of the electorate."""
17
18
def Likelihood(self, data, hypo):
19
"""Computes the likelihood of the data under the hypothesis.
20
21
hypo: fraction of the population that supports your candidate
22
data: poll results
23
"""
24
bias, std, result = data
25
error = result - hypo
26
like = thinkbayes2.EvalNormalPdf(error, bias, std)
27
return like
28
29
30
def main():
31
hypos = range(0, 101)
32
suite = Electorate(hypos)
33
34
thinkplot.PrePlot(3)
35
thinkplot.Pdf(suite, label='prior')
36
37
data = 1.1, 3.7, 53
38
suite.Update(data)
39
thinkplot.Pdf(suite, label='posterior1')
40
thinkplot.Save(root='electorate1',
41
xlabel='percentage of electorate',
42
ylabel='PMF',
43
formats=['png'],
44
clf=False)
45
46
print(suite.Mean())
47
print(suite.Std())
48
print(suite.ProbLess(50))
49
50
data = -2.3, 4.1, 49
51
suite.Update(data)
52
53
thinkplot.Pdf(suite, label='posterior2')
54
thinkplot.Save(root='electorate2',
55
xlabel='percentage of electorate',
56
ylabel='PMF',
57
formats=['png'])
58
59
print(suite.Mean())
60
print(suite.Std())
61
print(suite.ProbLess(50))
62
63
64
if __name__ == '__main__':
65
main()
66
67