Module: Nuggets::Array::VarianceMixin

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

Instance Method Summary collapse

Instance Method Details

#covarianceObject Also known as: cov

call-seq:

array.covariance => aFloat

Calculates the covariance of the {x,y} pairs in array. If array only contains values instead of pairs, y will be the value and x will be each value’s position (rank) in array.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/nuggets/array/variance_mixin.rb', line 60

def covariance
  sx, sy, sp = 0.0, 0.0, 0.0

  return sx if empty?

  target = first.respond_to?(:to_ary) ? self :
    self.class.new(size) { |i| [i + 1, at(i)] }

  target.each { |x, y|
    sx += x
    sy += y
    sp += x * y
  }

  (sp - sx * sy / size) / size
end

#varianceObject Also known as: var

call-seq:

array.variance => aFloat

Calculates the variance of the values in array.



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

def variance
  sx, sq = 0.0, 0.0

  return sx if empty?

  each { |x|
    x = yield x if block_given?

    sx += x
    sq += x ** 2
  }

  (sq - sx ** 2 / size) / size
end