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, Rational(0)].freeze

Instance Attribute Summary

Attributes included from Operation::Unary

#operand

Class Method Summary collapse

Methods inherited from Axiom::Aggregate

#call, #default, default, #finalize

Methods included from Operation::Unary

#initialize

Methods inherited from Function

extract_value, rename_attributes, #type

Methods included from Visitable

#accept

Class Method Details

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

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

Examples:

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

Parameters:

Returns:

  • (Array(Integer, Numeric, Rational))


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) ⇒ Rational, ...

Calculate the variance from the accumulator

Examples:

variance = Variance.finalize(accumulator)

Parameters:

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

Returns:

  • (Rational)

    returned for a non-empty set

  • (Float::INFINITY)

    returned for when the sum of squares is infinite

  • (nil)

    returned for an empty set



47
48
49
50
51
# File 'lib/axiom/aggregate/variance.rb', line 47

def self.finalize(accumulator)
  sum_of_squares, count = accumulator.values_at(2, 0)
  return Float::INFINITY if sum_of_squares.equal?(Float::INFINITY)
  Rational(sum_of_squares, count) unless count.zero?
end

.typeClass<Types::Float>

Return the type returned from #call

Examples:

type = Axiom::Aggregate::Variance.type  # => Axiom::Types::Float

Returns:

  • (Class<Types::Float>)


61
62
63
# File 'lib/axiom/aggregate/variance.rb', line 61

def self.type
  Types::Float
end