Module: Nuggets::Array::VarianceMixin

Included in:
Array
Defined in:
lib/nuggets/array/variance_mixin.rb

Instance Method Summary collapse

Instance Method Details

#varianceObject Also known as: var

call-seq:

array.variance => aFloat

Calculates the variance of the items in array.

Based on <warrenseen.com/blog/2006/03/13/how-to-calculate-standard-deviation/>.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/nuggets/array/variance_mixin.rb', line 38

def variance
  s, mean = 0.0, 0.0

  return s if empty?

  each_with_index { |x, n|
    x = yield x if block_given?

    delta = x - mean
    mean += delta / (n + 1)
    s += delta * (x - mean)
  }

  s / size
end