Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96163
License: OTHER
1
"""This file contains code for use with "Think Stats",
2
by Allen B. Downey, available from greenteapress.com
3
4
Copyright 2010 Allen B. Downey
5
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
6
"""
7
8
import bisect
9
import random
10
11
def Mean(t):
12
"""Computes the mean of a sequence of numbers.
13
14
Args:
15
t: sequence of numbers
16
17
Returns:
18
float
19
"""
20
return float(sum(t)) / len(t)
21
22
23
def MeanVar(t):
24
"""Computes the mean and variance of a sequence of numbers.
25
26
Args:
27
t: sequence of numbers
28
29
Returns:
30
tuple of two floats
31
"""
32
mu = Mean(t)
33
var = Var(t, mu)
34
return mu, var
35
36
37
def Trim(t, p=0.01):
38
"""Trims the largest and smallest elements of t.
39
40
Args:
41
t: sequence of numbers
42
p: fraction of values to trim off each end
43
44
Returns:
45
sequence of values
46
"""
47
n = int(p * len(t))
48
t = sorted(t)[n:-n]
49
return t
50
51
52
def Jitter(values, jitter=0.5):
53
"""Jitters the values by adding a uniform variate in (-jitter, jitter)."""
54
return [x + random.uniform(-jitter, jitter) for x in values]
55
56
57
def TrimmedMean(t, p=0.01):
58
"""Computes the trimmed mean of a sequence of numbers.
59
60
Side effect: sorts the list.
61
62
Args:
63
t: sequence of numbers
64
p: fraction of values to trim off each end
65
66
Returns:
67
float
68
"""
69
t = Trim(t, p)
70
return Mean(t)
71
72
73
def TrimmedMeanVar(t, p=0.01):
74
"""Computes the trimmed mean and variance of a sequence of numbers.
75
76
Side effect: sorts the list.
77
78
Args:
79
t: sequence of numbers
80
p: fraction of values to trim off each end
81
82
Returns:
83
float
84
"""
85
t = Trim(t, p)
86
mu, var = MeanVar(t)
87
return mu, var
88
89
90
def Var(t, mu=None):
91
"""Computes the variance of a sequence of numbers.
92
93
Args:
94
t: sequence of numbers
95
mu: value around which to compute the variance; by default,
96
computes the mean.
97
98
Returns:
99
float
100
"""
101
if mu is None:
102
mu = Mean(t)
103
104
# compute the squared deviations and return their mean.
105
dev2 = [(x - mu)**2 for x in t]
106
var = Mean(dev2)
107
return var
108
109
110
def Binom(n, k, d={}):
111
"""Compute the binomial coefficient "n choose k".
112
113
Args:
114
n: number of trials
115
k: number of successes
116
d: map from (n,k) tuples to cached results
117
118
Returns:
119
int
120
"""
121
if k == 0:
122
return 1
123
if n == 0:
124
return 0
125
126
try:
127
return d[n, k]
128
except KeyError:
129
res = Binom(n-1, k, d) + Binom(n-1, k-1, d)
130
d[n, k] = res
131
return res
132
133
134
class Interpolator(object):
135
"""Represents a mapping between sorted sequences; performs linear interp.
136
137
Attributes:
138
xs: sorted list
139
ys: sorted list
140
"""
141
def __init__(self, xs, ys):
142
self.xs = xs
143
self.ys = ys
144
145
def Lookup(self, x):
146
"""Looks up x and returns the corresponding value of y."""
147
return self._Bisect(x, self.xs, self.ys)
148
149
def Reverse(self, y):
150
"""Looks up y and returns the corresponding value of x."""
151
return self._Bisect(y, self.ys, self.xs)
152
153
def _Bisect(self, x, xs, ys):
154
"""Helper function."""
155
if x <= xs[0]:
156
return ys[0]
157
if x >= xs[-1]:
158
return ys[-1]
159
i = bisect.bisect(xs, x)
160
frac = 1.0 * (x - xs[i-1]) / (xs[i] - xs[i-1])
161
y = ys[i-1] + frac * 1.0 * (ys[i] - ys[i-1])
162
return y
163
164
165
166