Last active
October 6, 2015 03:18
-
-
Save tlux/2927010 to your computer and use it in GitHub Desktop.
Stochastic Array Aggregation Methods
This file contains 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
class Array | |
def average | |
self.reduce(:+) / length.to_f | |
end | |
def median | |
values = self.sort | |
if length % 2 == 0 # even | |
center = length / 2 | |
(values[center - 1] + values[center]) / 2.0 | |
else # odd | |
center = (length + 1) / 2 | |
values[center] | |
end | |
end | |
def quantile(percent) | |
raise ArgumentError.new 'Out of range' if percent < 0 or percent > 1 | |
values = self.sort | |
index = (percent * length).ceil | |
values[index - 1] | |
end | |
def standard_variance | |
Math.sqrt variance | |
end | |
def variance | |
numerator = self.map { |x| x - average }.map { |x| x**2 }.reduce(:+) | |
denominator = (length - 1).to_f | |
numerator / denominator | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment