use mean instead of median for stale proportion calculation
[p2pool.git] / p2pool / util / math.py
1 from __future__ import absolute_import, division
2
3 import __builtin__
4 import math
5 import random
6
7 def median(x, use_float=True):
8     # there exist better algorithms...
9     y = sorted(x)
10     if not y:
11         raise ValueError('empty sequence!')
12     left = (len(y) - 1)//2
13     right = len(y)//2
14     sum = y[left] + y[right]
15     if use_float:
16         return sum/2
17     else:
18         return sum//2
19
20 def mean(x):
21     total = 0
22     count = 0
23     for y in x:
24         total += y
25         count += 1
26     return total/count
27
28 def shuffled(x):
29     x = list(x)
30     random.shuffle(x)
31     return x
32
33 def shift_left(n, m):
34     # python: :(
35     if m >= 0:
36         return n << m
37     return n >> -m
38
39 def clip(x, (low, high)):
40     if x < low:
41         return low
42     elif x > high:
43         return high
44     else:
45         return x
46
47 def nth(i, n=0):
48     i = iter(i)
49     for _ in xrange(n):
50         i.next()
51     return i.next()
52
53 def geometric(p):
54     if p <= 0 or p > 1:
55         raise ValueError('p must be in the interval (0.0, 1.0]')
56     if p == 1:
57         return 1
58     return int(math.log1p(-random.random()) / math.log1p(-p)) + 1
59
60 def add_dicts(*dicts):
61     res = {}
62     for d in dicts:
63         for k, v in d.iteritems():
64             res[k] = res.get(k, 0) + v
65     return dict((k, v) for k, v in res.iteritems() if v)
66
67 def format(x):
68     prefixes = 'kMGTPEZY'
69     count = 0
70     while x >= 100000 and count < len(prefixes) - 2:
71         x = x//1000
72         count += 1
73     s = '' if count == 0 else prefixes[count - 1]
74     return '%i' % (x,) + s
75
76 def perfect_round(x):
77     a, b = divmod(x, 1)
78     a2 = int(a)
79     if random.random() >= b:
80         return a2
81     else:
82         return a2 + 1
83
84 def erf(x):
85     # save the sign of x
86     sign = 1
87     if x < 0:
88         sign = -1
89     x = abs(x)
90     
91     # constants
92     a1 =  0.254829592
93     a2 = -0.284496736
94     a3 =  1.421413741
95     a4 = -1.453152027
96     a5 =  1.061405429
97     p  =  0.3275911
98     
99     # A&S formula 7.1.26
100     t = 1.0/(1.0 + p*x)
101     y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*math.exp(-x*x)
102     return sign*y # erf(-x) = -erf(x)
103
104 def ierf(z, steps=10):
105     guess = 0
106     for i in xrange(steps):
107         d = 2*math.e**(-guess**2)/math.sqrt(math.pi)
108         guess = guess - (erf(guess) - z)/d
109     return guess
110
111 def binomial_conf_interval(x, n, conf=0.95):
112     # approximate - Wilson score interval
113     z = math.sqrt(2)*ierf(conf)
114     p = x/n
115     topa = p + z**2/2/n
116     topb = z * math.sqrt(p*(1-p)/n + z**2/4/n**2)
117     bottom = 1 + z**2/n
118     return (topa - topb)/bottom, (topa + topb)/bottom
119
120 def interval_to_center_radius((low, high)):
121     return (high+low)/2, (high-low)/2
122
123 def reversed(x):
124     try:
125         return __builtin__.reversed(x)
126     except TypeError:
127         return reversed(list(x))
128
129 class Object(object):
130     def __init__(self, **kwargs):
131         for k, v in kwargs.iteritems():
132             setattr(self, k, v)
133
134 def add_tuples(res, *tuples):
135     for t in tuples:
136         if len(t) != len(res):
137             print 'tuples must all be the same length'
138         res = tuple(a + b for a, b in zip(res, t))
139     return res
140
141 def flatten_linked_list(x):
142     while x is not None:
143         x, cur = x
144         yield cur
145
146 if __name__ == '__main__':
147     import random
148     a = 1
149     while True:
150         print a, format(a) + 'H/s'
151         a = a * random.randrange(2, 5)