forked from autolab/Autolab
/
statistics.rb
executable file
·74 lines (67 loc) · 1.29 KB
/
statistics.rb
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
# Statistics Module: Computes basic statistics
class Statistics
def mean(a)
if a.nil? || a.empty?
return "--"
else
result = (a.inject(0) { |sum, el| sum + el }.to_f) / a.to_a.length
end
result.round(1)
end
# I stole this from the internets.
def variance(a)
n = 0
mean = 0.0
s = 0.0
a.each do |x|
n += 1
delta = x - mean
mean += (delta / n)
s += delta * (x - mean)
end
s / n
end
# calculate the standard deviation of a population
# accepts: an array, the population
# returns: the standard deviation
def stddev(a)
if a.nil? || a.empty?
"--"
else
Math.sqrt(variance(a)).round(1)
end
end
def max(a)
if a.nil? || a.empty?
"--"
else
a.to_a.max.round(1)
end
end
def min(a)
if a.nil? || a.empty?
"--"
else
a.to_a.min.round(1)
end
end
def median(a)
return "--" if a.nil? || a.empty?
a = a.sort
len = a.size
if len.even?
result = (a[len / 2 - 1] + a[len / 2]) / 2.0
else
result = a[len / 2].to_f
end
result.round(1)
end
def stats(pop)
pop = pop.compact
result = {}
[:median, :min, :max, :mean, :stddev].each do |stat|
result[stat] = send(stat, pop)
end
result
end
end