Monday, March 23, 2009

Calculate Standard Deviation in Ruby

I saw some pretty ugly implementations out there and thought I'd make them more succinct using the fantastic inject method. I recognize that this approach requires two 'walks' across the population array, but I think the cleanliness makes up for it.



def mean(population)
population.inject(0.0) {|sum,x| sum+=x } / population.size
end

def variance(population)
mean = mean(population)
population.inject(0.0) {|variance_sum,x| variance_sum += (x - mean)**2 } /population.size
end

def standard_deviation(population)
Math.sqrt(variance(population))
end

>> mean([1, 3, 24, 17, 12, 6, 14])
=> 11.0
>> standard_deviation([1, 3, 24, 17, 12, 6, 14])
=> 7.59699188589047



Please feel free to share your thoughts.

Followers