-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathkahan.py
More file actions
167 lines (130 loc) · 2.53 KB
/
kahan.py
File metadata and controls
167 lines (130 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def cumvariance(a):
"""
Cumulative mean and variance.
Return an iterator over yielding pairs of cumulative mean and
cumulative variance of an input sequence
Parameters
----------
a : iterable
Input sequence
Returns
-------
iterator
An iterator that yields pairs of cumulative mean and cumulative variance.
Examples
--------
>>> list(cumvariance([1, 7, 4]))
[(1.0, 0.0), (4.0, 9.0), (4.0, 6.0)]
"""
n = 0
s = 0.0
s2 = 0.0
for e in a:
n += 1
y = e - s
s += y / n
s2 += y * (e - s)
yield s, s2 / n
def cummean(a):
"""
Cumulative mean.
Return an iterator over yielding cumulative means of an input sequence
Parameters
----------
a : iterable
Input sequence
Returns
-------
iterator
An iterator that yields cumulative means.
Examples
--------
>>> list(cummean([1, 2, 3, 4]))
[1.0, 1.5, 2.0, 2.5]
"""
s = 0.0
c = 0.0
n = 0
for e in a:
y = e - c
t = s + y
c = (t - s) - y
s = t
n += 1
yield s / n
def cumsum(a):
"""
Cumulative sum.
Return an iterator over yielding cumulative sums of an input sequence
Parameters
----------
a : iterable
Input sequence
Returns
-------
iterator
An iterator that yields cumulative sums.
Examples
--------
>>> list(cumsum([1, 2, 3, 4]))
[1.0, 3.0, 6.0, 10.0]
"""
s = 0.0
c = 0.0
for e in a:
y = e - c
t = s + y
c = (t - s) - y
s = t
yield s
def sum(a):
"""
Return the sum of iterable `a'.
Parameters
----------
a : iterable
Input sequence
Returns
-------
float
The cumulative sum of the input sequence.
Examples
--------
>>> sum([1, 2, 3, 4])
10.0
"""
s = 0.0
c = 0.0
for e in a:
y = e - c
t = s + y
c = (t - s) - y
s = t
return s
def mean(a):
"""
Return the mean of iterable `a'.
Return the cumulative mean of an input sequence
Parameters
----------
a : iterable
Input sequence
Returns
-------
float
The cumulative mean of the input sequence.
Examples
--------
>>> mean([1, 2, 3, 4])
2.5
"""
s = 0.0
c = 0.0
n = 0
for e in a:
y = e - c
t = s + y
c = (t - s) - y
s = t
n += 1
return s / n