Sha256: 745371526cfc137be0063eea4fe1a82cd70d0e699f6799370132ba79a0520379

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents



module Enumerable

    ##
    # Sum of all the elements of the Enumerable

    def sum
        return self.inject(0) { |acc, i| acc + i }
    end

    ##
    # Average of all the elements of the Enumerable
    #
    # The Enumerable must respond to #length

    def average
        return self.sum / self.length.to_f
    end

    ##
    # Sample variance of all the elements of the Enumerable
    #
    # The Enumerable must respond to #length

    def sample_variance
        avg = self.average
        sum = self.inject(0) { |acc, i| acc + (i - avg) ** 2 }
        return (1 / self.length.to_f * sum)
    end

    ##
    # Standard deviation of all the elements of the Enumerable
    #
    # The Enumerable must respond to #length

    def standard_deviation
        return Math.sqrt(self.sample_variance)
    end

end

module MathUtil
  
  def self.variance(population)
    n = 0
    mean = 0.0
    s = 0.0
    population.each { |x|
      n = n + 1
      delta = (x - mean).to_f
      mean = (mean + (delta / n)).to_f
      s = (s + delta * (x - mean)).to_f
    }
    
    return s / n
  end

  # calculate the standard deviation of a population
  # accepts: an array, the population
  # returns: the standard deviation
  def self.standard_deviation(population)
    Math.sqrt(variance(population))
  end
  
  # enforce_limit
  #
  # Enforce a minimum and maximum value 
  def self.enforce_limit(val,min,max)
    val = min  if val < min
    val = max  if val > max
    val
  end
  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
stella-0.5.1 lib/utils/mathutil.rb