Sha256: cfdc3465c181fe1cd24bff0a63e5f987aff940744a9ca5e98ab8e8d7742b9580

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

module ArrayStats
  
  # Returns the sum of all elements in the array; 0 if array is empty
  def sum
    self.inject(0) {|sum, sample| sum += sample}
  end
  
  # Returns the mean of all elements in array; nil if array is empty
  def mean
    if self.length == 0
      nil
    else
      self.sum / self.length
    end
  end

  # Returns the median for the array; nil if array is empty
  def median
    percentile(50)
  end
  
  # Returns the percentile value for percentile _p_; nil if array is empty.
  #
  # _p_ should be expressed as an integer; <tt>percentile(90)</tt> returns the 90th percentile of the array.
  #
  # Algorithm from NIST[http://www.itl.nist.gov/div898/handbook/prc/section2/prc252.htm]
  def percentile p
    sorted_array = self.sort
    rank = (p.to_f / 100) * (self.length + 1)
    
    if self.length == 0
      return nil
    elsif rank.fractional_part?
      sample_0 = sorted_array[rank.truncate - 1]
      sample_1 = sorted_array[rank.truncate]

      return (rank.fractional_part * (sample_1 - sample_0)) + sample_0
    else
      return sorted_array[rank - 1]
    end    
  end
  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bkoski-array_stats-0.5.0 lib/array_stats/array_stats.rb