forked from rcolistete/MicroPython_Statistics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statistics_indepfunc.py
119 lines (107 loc) · 2.82 KB
/
statistics_indepfunc.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""
Statistics module for MicroPython (with independent functions and 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 variance(data, xbar=None):
if iter(data) is data:
data = list(data)
if xbar is None:
xbar = sum(data)/len(data)
total = total2 = 0
for x in data:
total += (x - xbar)**2
total2 += (x - xbar)
total -= total2**2/len(data)
return total/(len(data) - 1)
def pvariance(data, mu=None):
if iter(data) is data:
data = list(data)
if mu is None:
mu = sum(data)/len(data)
total = total2 = 0
for x in data:
total += (x - mu)**2
total2 += (x - mu)
total -= total2**2/len(data)
return total/len(data)
def stdev(data, xbar=None):
if iter(data) is data:
data = list(data)
if xbar is None:
xbar = sum(data)/len(data)
total = total2 = 0
for x in data:
total += (x - xbar)**2
total2 += (x - xbar)
total -= total2**2/len(data)
return math.sqrt(total/(len(data) - 1))
def pstdev(data, mu=None):
if iter(data) is data:
data = list(data)
if mu is None:
mu = sum(data)/len(data)
total = total2 = 0
for x in data:
total += (x - mu)**2
total2 += (x - mu)
total -= total2**2/len(data)
return math.sqrt(total/len(data))