Created
November 20, 2012 13:32
-
-
Save henry0312/4117954 to your computer and use it in GitHub Desktop.
Descriptive statistics in Ruby
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
# Add methods to Enumerable, which makes them available to Array | |
module Enumerable | |
# sum of an array of numbers | |
def sum | |
return self.inject(0,:+) | |
end | |
# average of an array of numbers | |
def mean | |
return self.sum / self.size.to_f | |
end | |
# biased sample variance of an array of numbers | |
def biased_sample_variance | |
mean = self.mean | |
return self.map{ |sample| (mean - sample) ** 2 }.inject(0,:+) / self.size.to_f | |
end | |
# unbiased sample variance of an array of numbers | |
def unbiased_sample_variance | |
mean = self.mean | |
return self.map{ |sample| (mean - sample) ** 2 }.inject(0,:+) / (self.size - 1).to_f | |
end | |
# standard deviation of the sample of an array of numbers | |
def standard_deviation | |
return Math.sqrt(self.biased_sample_variance) | |
end | |
# sample standard deviation of an array of numbers | |
def sample_standard_deviation | |
return Math.sqrt(self.unbiased_sample_variance) | |
end | |
# standard error of an arrya of numbers | |
def standard_error | |
return self.sample_standard_deviation / Math.sqrt(self.size).to_f | |
end | |
end # module Enumerable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment