Sha256: 345e2ba1977350c8c50f50e23b9d5e3f2e9e3e196061766c8c509a59d00c6fa4

Contents?: true

Size: 1.46 KB

Versions: 2

Compression:

Stored size: 1.46 KB

Contents


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




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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
stella-0.3.2 lib/utils/mathutil.rb
stella-0.5.3 lib/utils/mathutil.rb