Sha256: 597c38ec5fda582759437ae017a55d5fd9a9806ed62de1900ff252710e8b88ac

Contents?: true

Size: 1.77 KB

Versions: 4

Compression:

Stored size: 1.77 KB

Contents

# encoding: utf-8

module Veritas
  class Aggregate

    # The mean of a sequence of numbers
    class Mean < Aggregate

      DEFAULT = [ 0, nil ].freeze

      # Return the count and mean for a sequence of numbers
      #
      # @example
      #   count, mean = Mean.call([ count, mean ], value)
      #
      # @param [Array(Integer, Numeric)] accumulator
      #
      # @param [Numeric] value
      #
      # @return [Array(Integer, Numeric)]
      #
      # @api public
      def self.call(accumulator, value)
        return accumulator if value.nil?
        count, mean = accumulator
        count       = Count.call(count, value)
        [ count, mean.nil? ? value.to_f : mean + ((value - mean) / count.to_f) ]
      end

      # Extract the mean from the accumulator
      #
      # @example
      #   mean = Mean.finalize(accumulator)
      #
      # @param [Array(Integer, Numeric)] accumulator
      #
      # @return [Float]
      #   returned for a non-empty set
      # @return [nil]
      #   returned for an empty set
      #
      # @api public
      def self.finalize(accumulator)
        accumulator.last
      end

      # Return the type returned from #call
      #
      # @return [Class<Attribute::Float>]
      #
      # @api public
      def type
        Attribute::Float
      end

      module Methods
        extend Aliasable

        inheritable_alias(
          :average => :mean,
          :avg     => :mean
        )

        # Return a mean aggregate function
        #
        # @example
        #   mean = attribute.mean
        #
        # @param [Attribute]
        #
        # @return [Mean]
        #
        # @api public
        def mean
          Mean.new(self)
        end

      end # module Methods
    end # class Mean
  end # class Aggregate
end # module Veritas

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
veritas-0.0.7 lib/veritas/aggregate/mean.rb
veritas-0.0.6 lib/veritas/aggregate/mean.rb
veritas-0.0.5 lib/veritas/aggregate/mean.rb
veritas-0.0.4 lib/veritas/aggregate/mean.rb