How can I do standard deviation in Ruby?

Satchel picture Satchel · Oct 13, 2011 · Viewed 25k times · Source

I have several records with a given attribute, and I want to find the standard deviation.

How do I do that?

Answer

tolitius picture tolitius · Oct 13, 2011
module Enumerable

    def sum
      self.inject(0){|accum, i| accum + i }
    end

    def mean
      self.sum/self.length.to_f
    end

    def sample_variance
      m = self.mean
      sum = self.inject(0){|accum, i| accum +(i-m)**2 }
      sum/(self.length - 1).to_f
    end

    def standard_deviation
      Math.sqrt(self.sample_variance)
    end

end 

Testing it:

a = [ 20, 23, 23, 24, 25, 22, 12, 21, 29 ]
a.standard_deviation  
# => 4.594682917363407

01/17/2012:

fixing "sample_variance" thanks to Dave Sag