Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/scripts/euro2.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 2012 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
"""This file contains a partial solution to a problem from
11
MacKay, "Information Theory, Inference, and Learning Algorithms."
12
13
Exercise 3.15 (page 50): A statistical statement appeared in
14
"The Guardian" on Friday January 4, 2002:
15
16
When spun on edge 250 times, a Belgian one-euro coin came
17
up heads 140 times and tails 110. 'It looks very suspicious
18
to me,' said Barry Blight, a statistics lecturer at the London
19
School of Economics. 'If the coin were unbiased, the chance of
20
getting a result as extreme as that would be less than 7%.'
21
22
MacKay asks, "But do these data give evidence that the coin is biased
23
rather than fair?"
24
25
"""
26
27
import thinkbayes2
28
import thinkplot
29
30
31
class Euro(thinkbayes2.Suite):
32
"""Represents hypotheses about the probability of heads."""
33
34
def Likelihood(self, data, hypo):
35
"""Computes the likelihood of the data under the hypothesis.
36
37
hypo: integer value of x, the probability of heads (0-100)
38
data: string 'H' or 'T'
39
"""
40
x = hypo / 100.0
41
if data == 'H':
42
return x
43
else:
44
return 1-x
45
46
47
class Euro2(thinkbayes2.Suite):
48
"""Represents hypotheses about the probability of heads."""
49
50
def Likelihood(self, data, hypo):
51
"""Computes the likelihood of the data under the hypothesis.
52
53
hypo: integer value of x, the probability of heads (0-100)
54
data: tuple of (number of heads, number of tails)
55
"""
56
x = hypo / 100.0
57
heads, tails = data
58
like = x**heads * (1-x)**tails
59
return like
60
61
62
def Version1():
63
suite = Euro(range(0, 101))
64
heads, tails = 140, 110
65
dataset = 'H' * heads + 'T' * tails
66
67
for data in dataset:
68
suite.Update(data)
69
70
return suite
71
72
73
def Version2():
74
suite = Euro(range(0, 101))
75
heads, tails = 140, 110
76
dataset = 'H' * heads + 'T' * tails
77
78
suite.UpdateSet(dataset)
79
return suite
80
81
82
def Version3():
83
suite = Euro2(range(0, 101))
84
heads, tails = 140, 110
85
86
suite.Update((heads, tails))
87
return suite
88
89
90
def main():
91
92
suite = Version3()
93
print(suite.Mean())
94
95
thinkplot.Pdf(suite)
96
thinkplot.Show(legend=False)
97
98
99
if __name__ == '__main__':
100
main()
101
102