I have several records with a given attribute, and I want to find the standard deviation.
How do I do that?
If the records at hand are of type Integer
or Rational
, you may want to compute the variance using Rational
instead of Float
to avoid errors introduced by rounding.
For example:
def variance(list)
mean = list.reduce(:+)/list.length.to_r
sum_of_squared_differences = list.map { |i| (i - mean)**2 }.reduce(:+)
sum_of_squared_differences/list.length
end
(It would be prudent to add special-case handling for empty lists and other edge cases.)
Then the square root can be defined as:
def std_dev(list)
Math.sqrt(variance(list))
end