Module: ArrayStats
- Included in:
- Array
- Defined in:
- lib/array_stats.rb,
lib/array_stats/array_stats.rb
Constant Summary collapse
- VERSION =
'0.5.0'
Instance Method Summary collapse
-
#mean ⇒ Object
Returns the mean of all elements in array; nil if array is empty.
-
#median ⇒ Object
Returns the median for the array; nil if array is empty.
-
#percentile(p) ⇒ Object
Returns the percentile value for percentile p; nil if array is empty.
-
#total_sum ⇒ Object
Returns the sum of all elements in the array; 0 if array is empty.
Instance Method Details
#mean ⇒ Object
Returns the mean of all elements in array; nil if array is empty
9 10 11 12 13 14 15 |
# File 'lib/array_stats/array_stats.rb', line 9 def mean if self.length == 0 nil else self.total_sum / self.length end end |
#median ⇒ Object
Returns the median for the array; nil if array is empty
18 19 20 |
# File 'lib/array_stats/array_stats.rb', line 18 def median percentile(50) 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
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/array_stats/array_stats.rb', line 27 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 |
#total_sum ⇒ Object
Returns the sum of all elements in the array; 0 if array is empty
4 5 6 |
# File 'lib/array_stats/array_stats.rb', line 4 def total_sum self.inject(0) {|sum, sample| sum += sample} end |