How can I do standard deviation in Ruby?

后端 未结 9 1442
一个人的身影
一个人的身影 2021-01-30 15:45

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

How do I do that?

9条回答
  •  孤城傲影
    2021-01-30 16:31

    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
    

提交回复
热议问题