module Nuggets::Array::VarianceMixin

Public Instance Methods

cov()
Alias for: covariance
covariance → aFloat click to toggle source

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.

# 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
Also aliased as: cov
var()
Alias for: variance
variance → aFloat click to toggle source

Calculates the variance of the values in array.

# 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
Also aliased as: var