Skip to content

Instantly share code, notes, and snippets.

@tlux
Last active October 6, 2015 03:18
Show Gist options
  • Save tlux/2927010 to your computer and use it in GitHub Desktop.
Save tlux/2927010 to your computer and use it in GitHub Desktop.
Stochastic Array Aggregation Methods
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