Created
October 21, 2011 01:03
-
-
Save jodell/1302843 to your computer and use it in GitHub Desktop.
Standard Deviation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Enumerable | |
def sum(&blk) | |
map(&blk).reduce(0) { |sum, element| sum + element } | |
end | |
def mean | |
sum.to_f / size.to_f | |
end | |
def variance | |
_mean = mean | |
sum { |x| (x - _mean) ** 2 } / size | |
end | |
def std_dev | |
Math.sqrt variance | |
end | |
def z_scores | |
_mean, _std_dev = mean, std_dev | |
map { |x| (x - _mean) / _std_dev } | |
end | |
def scale(range) | |
set_max, range_max = max, range.max | |
map { |x| x / (set_max / range_max) } | |
end | |
end | |
module StandardDeviation | |
DECILE_BINS = [ | |
-Float::INFINITY, | |
-1.208, | |
-0.804, | |
-0.502, | |
-0.205, | |
0.0, | |
0.206, | |
0.503, | |
0.805, | |
1.209, | |
Float::INFINITY | |
] | |
def self.decile(z_score) | |
DECILE_BINS.each_with_index { |bin, index| return index if z_score < bin } | |
end | |
end | |
dollars = %w( | |
3013393.3 | |
3214426.6 | |
4848175.54 | |
14564528.09 | |
3755073.93 | |
715109.27 | |
17574128.24 | |
4264381.68 | |
15371827.25 | |
201833.49 | |
309141.95 | |
857273.75 | |
6812680.36 | |
60268.74 | |
1893672.23 | |
26301374.45 | |
630276.71 | |
2046414.79 | |
213316.59 | |
2435571.19 | |
4279765.58 | |
453878.13 | |
3159793.79 | |
788693.1 | |
3964048.29 | |
3827491.3 | |
3293435.84 | |
).map(&:to_f) | |
p dollars.z_scores | |
p dollars.z_scores.map { |v| StandardDeviation.decile(v) } | |
p [2, 3, 4, 20].scale(1..10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment