Skip to content

Instantly share code, notes, and snippets.

@rye
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rye/9a41d62d7c3ef5de730a to your computer and use it in GitHub Desktop.
Save rye/9a41d62d7c3ef5de730a to your computer and use it in GitHub Desktop.
A handy little Array class extension for calculating standard deviation of an array
class Array
def mean
return ((self.map{|x| x.to_f}
.inject(:+)) /
(self.count))
end
def standard_deviation
m = self.mean
return (Math.sqrt((self.map{|x| (x - m) ** 2}
.inject(:+)) /
(self.count)))
end
end
ary = [2, 4, 4, 4, 5, 5, 7, 9]
p ary
p ary.mean
p ary.standard_deviation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment