Class: Axiom::Aggregate::Variance

Inherits:
Axiom::Aggregate show all
Defined in:
lib/axiom/aggregate/variance.rb

Overview

The variance of a sequence of numbers

Direct Known Subclasses

StandardDeviation

Defined Under Namespace

Modules: Methods

Constant Summary collapse

DEFAULT =
[ 0, nil, 0.0 ].freeze

Instance Attribute Summary

Attributes included from Operation::Unary

#operand

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Axiom::Aggregate

#call, #default, default, #finalize

Methods included from Visitable

#accept

Methods included from Operation::Unary

#initialize

Class Method Details

.call(accumulator, value) ⇒ Array(Integer, Numeric, Numeric)

Return the count, mean, and sum of squares for a sequence of numbers

Examples:

count, mean, sum_of_squares = Variance.call(accumulator, value)

Parameters:

  • accumulator (Array(Integer, Numeric, Float))
  • value (Numeric)

Returns:

  • (Array(Integer, Numeric, Numeric))


23
24
25
26
27
28
29
30
# File 'lib/axiom/aggregate/variance.rb', line 23

def self.call(accumulator, value)
  return accumulator if value.nil?
  mean, sum_of_squares  = accumulator.last(2)
  delta                 = mean.nil? ? value : value - mean
  count, new_mean       = Mean.call(accumulator, value)
  sum_of_squares       += delta * (value - new_mean)
  [ count, new_mean, sum_of_squares ]
end

.finalize(accumulator) ⇒ Float?

Calculate the variance from the accumulator

Examples:

variance = Variance.finalize(accumulator)

Parameters:

  • accumulator (Array(Numeric, Integer, Float))

Returns:

  • (Float)

    returned for a non-empty set

  • (nil)

    returned for an empty set



45
46
47
48
# File 'lib/axiom/aggregate/variance.rb', line 45

def self.finalize(accumulator)
  sum_of_squares, count = accumulator.values_at(2, 0)
  sum_of_squares / count unless count.zero?
end

Instance Method Details

#typeClass<Attribute::Float>

Return the type returned from #call

Examples:

type = Axiom::Aggregate::Variance.type

Returns:



58
59
60
# File 'lib/axiom/aggregate/variance.rb', line 58

def type
  Attribute::Float
end