Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/easystats.rb
Instance Method Summary collapse
- #mean ⇒ Object (also: #average)
- #median ⇒ Object
- #mode ⇒ Object
- #probability_distribution ⇒ Object
- #range ⇒ Object
- #standard_deviation ⇒ Object
- #sum ⇒ Object
- #variance ⇒ Object
- #weighted_moving_average ⇒ Object
Instance Method Details
#mean ⇒ Object Also known as: average
2 3 4 5 6 |
# File 'lib/easystats.rb', line 2 def mean return if empty? sum / count.to_f end |
#median ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/easystats.rb', line 24 def median return if empty? data = sort halfway = data.count / 2 if data.count.even? (data[halfway] + data[halfway - 1]) / 2.0 else data[halfway] end end |
#mode ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/easystats.rb', line 38 def mode return if empty? return first if one? return if self == uniq frequencies = inject(Hash.new(0)) { |k,v| k[v] += 1; k } frequencies = frequencies.sort_by { |k,v| v } return if frequencies[-1][1] == frequencies[-2][1] frequencies.last[0] end |
#probability_distribution ⇒ Object
51 52 53 54 55 56 57 58 59 |
# File 'lib/easystats.rb', line 51 def probability_distribution return if empty? total = count.to_f uniq.inject({}) { |result, item| result.update({ item => count(item) / total }) } end |
#range ⇒ Object
61 62 63 64 65 |
# File 'lib/easystats.rb', line 61 def range return if empty? max - min end |
#standard_deviation ⇒ Object
67 68 69 70 71 72 |
# File 'lib/easystats.rb', line 67 def standard_deviation return if empty? return 0 if one? Math::sqrt sum_of_deviations_squared / (count - 1) end |
#sum ⇒ Object
74 75 76 |
# File 'lib/easystats.rb', line 74 def sum reduce :+ end |
#variance ⇒ Object
78 79 80 81 82 |
# File 'lib/easystats.rb', line 78 def variance return if empty? sum_of_deviations_squared / count.to_f end |
#weighted_moving_average ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/easystats.rb', line 10 def weighted_moving_average return if empty? return first if one? weighted_sum = 0 sum = 0 index = 0 each do |element| weighted_sum = weighted_sum + (index * element) sum += index index += 1 end weighted_sum.to_f / sum end |