How can I do standard deviation in Ruby?

后端 未结 9 1460
一个人的身影
一个人的身影 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:36

    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

提交回复
热议问题