Module: CalculatePercentiles

Defined in:
lib/core_ext/array.rb

Instance Method Summary collapse

Instance Method Details

#meanObject

Returns the mean of all elements in array; nil if array is empty



4
5
6
7
# File 'lib/core_ext/array.rb', line 4

def mean
  return nil if self.length == 0
  self.sum / self.length
end

#percentile(p) ⇒ Object

Returns the percentile value for percentile p; nil if array is empty.

p should be expressed as an integer; percentile(90) returns the 90th percentile of the array.

Algorithm from NIST Implementation from github.com/bkoski/array_stats/pull/3



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/core_ext/array.rb', line 15

def percentile(p)
  sorted_array = self.sort
  rank = (p.to_f / 100) * (self.length + 1)

  return nil if self.length == 0

  if rank.truncate > 0 && rank.truncate < self.length
    sample_0 = sorted_array[rank.truncate - 1]
    sample_1 = sorted_array[rank.truncate]

    # Returns the fractional part of a float. For example, <tt>(6.67).fractional_part == 0.67</tt>
    fractional_part =  (rank - rank.truncate).abs
    (fractional_part * (sample_1 - sample_0)) + sample_0
  elsif rank.truncate == 0
    sorted_array.first.to_f
  elsif rank.truncate == self.length
    sorted_array.last.to_f
  end
end