Module: Darthjee::CoreExt::Math

Included in:
Math
Defined in:
lib/darthjee/core_ext/math.rb

Instance Method Summary collapse

Instance Method Details

#average(values) ⇒ ::Float #average(values) ⇒ ::Float

Calculates avarage from a series of values

Examples:

Average of array

values = [1,2,3,4]

Math.average(values) # returns 2.5

Average of hash

values = { 1 => 3, 7 => 1 }

Math.average(values) # returns 2.5

Overloads:

  • #average(values) ⇒ ::Float

    Parameters:

    • values (::Array)

      list of values

  • #average(values) ⇒ ::Float

    Parameters:

    • values (::Hash)

      hash of values and its weights

Returns:

  • (::Float)


26
27
28
29
30
31
32
33
34
35
# File 'lib/darthjee/core_ext/math.rb', line 26

def average(values)
  if values.is_a?(Hash)
    weight_sum = values.values.sum
    values = values.map { |value, weight| value * weight }
  else
    weight_sum = values.length
  end

  values.sum / weight_sum.to_f
end