forked from rcolistete/MicroPython_Statistics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statistics.py
98 lines (84 loc) · 2.18 KB
/
statistics.py
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
"""
Statistics module for MicroPython (with low memory usage):
https://github.com/rcolistete/MicroPython_Statistics
Version: 0.5.0 @ 2018/10/24
Author: Roberto Colistete Jr. (roberto.colistete at gmail.com)
License: MIT License (https://opensource.org/licenses/MIT)
"""
import math
def mean(data):
if iter(data) is data:
data = list(data)
return sum(data)/len(data)
def harmonic_mean(data):
if iter(data) is data:
data = list(data)
return len(data)/sum([1/x for x in data])
def median(data):
data = sorted(data)
n = len(data)
if n % 2 == 1:
return data[n//2]
else:
i = n//2
return (data[i - 1] + data[i])/2
def median_low(data):
data = sorted(data)
n = len(data)
if n % 2 == 1:
return data[n//2]
else:
return data[n//2 - 1]
def median_high(data):
data = sorted(data)
n = len(data)
return data[n//2]
def median_grouped(data, interval=1):
data = sorted(data)
n = len(data)
x = data[n//2]
L = x - interval/2
l1 = l2 = n//2
while (l1 > 0) and (data[l1 - 1] == x):
l1 -= 1
while (l2 < n) and (data[l2 + 1] == x):
l2 += 1
return L + (interval*(n/2 - l1)/(l2 - l1 + 1))
def mode(data):
if iter(data) is data:
data = list(data)
data = sorted(data)
last = modev = None
countmax = i = 0
while i < len(data):
if data[i] == last:
count += 1
else:
count = 1
last = data[i]
if count > countmax:
countmax = count
modev = last
i += 1
return modev
def _ss(data, c=None):
if c is None:
c = mean(data)
total = total2 = 0
for x in data:
total += (x - c)**2
total2 += (x - c)
total -= total2**2/len(data)
return total
def variance(data, xbar=None):
if iter(data) is data:
data = list(data)
return _ss(data, xbar)/(len(data) - 1)
def pvariance(data, mu=None):
if iter(data) is data:
data = list(data)
return _ss(data, mu)/len(data)
def stdev(data, xbar=None):
return math.sqrt(variance(data, xbar))
def pstdev(data, mu=None):
return math.sqrt(pvariance(data, mu))