Class: Mean
- Inherits:
-
Object
- Object
- Mean
- Defined in:
- lib/means.rb
Overview
Allows calculation of arithmetic, geometric and harmonic means. Class methods allow the passing in of a data set. Alternatively an object can be created and elements can be added with #push
Class Method Summary collapse
-
.arithmetic(data) ⇒ Numeric?
Calculate the arithmetic mean.
-
.geometric(data) ⇒ Numeric?
Calculate the geometric mean.
-
.harmonic(data) ⇒ Numeric?
Calculate the harmonic mean.
Instance Method Summary collapse
-
#arithmetic_mean ⇒ Numeric?
Calculate the arithmetic mean.
-
#geometric_mean ⇒ Numeric?
Calculate the geometric mean.
-
#harmonic_mean ⇒ Numeric?
Calculate the harmonic mean.
-
#initialize(params = {}) ⇒ Mean
constructor
Remember the initial state.
-
#push(element) ⇒ Object
Add element to the data set.
Constructor Details
#initialize(params = {}) ⇒ Mean
Remember the initial state.
If you are passing in an initial state:
- arithmetic mean
-
needs ‘:sum` and `:count`
- geometric mean
-
needs ‘:product` and `:count`
- harmonic mean
-
needs ‘:sum_of_reciprocals` and `:count`
41 42 43 44 |
# File 'lib/means.rb', line 41 def initialize(params={}) check_params params assign_defaults params end |
Class Method Details
.arithmetic(data) ⇒ Numeric?
Calculate the arithmetic mean
13 14 15 |
# File 'lib/means.rb', line 13 def Mean.arithmetic(data) data.sum / data.size unless data.empty? end |
.geometric(data) ⇒ Numeric?
Calculate the geometric mean
20 21 22 |
# File 'lib/means.rb', line 20 def Mean.geometric(data) data.reduce(:*) ** (1 / data.size) unless data.empty? or includes_zero_or_negative? data end |
.harmonic(data) ⇒ Numeric?
Calculate the harmonic mean
27 28 29 |
# File 'lib/means.rb', line 27 def Mean.harmonic(data) data.size / data.reduce(0) {|sum, element| sum += (1 / element)} unless data.empty? or includes_zero_or_negative? data end |
Instance Method Details
#arithmetic_mean ⇒ Numeric?
Calculate the arithmetic mean
62 63 64 |
# File 'lib/means.rb', line 62 def arithmetic_mean @sum / @count unless @count.zero? end |
#geometric_mean ⇒ Numeric?
Calculate the geometric mean
68 69 70 |
# File 'lib/means.rb', line 68 def geometric_mean @product ** (1 / @count) unless @count.zero? or @includes_zero_or_negative end |
#harmonic_mean ⇒ Numeric?
Calculate the harmonic mean
74 75 76 |
# File 'lib/means.rb', line 74 def harmonic_mean @count / @sum_of_reciprocals unless @count.zero? or @includes_zero_or_negative end |
#push(element) ⇒ Object
Add element to the data set
48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/means.rb', line 48 def push(element) @includes_zero_or_negative = true if Mean.zero_or_negative? element unless @includes_zero_or_negative @sum_of_reciprocals += (1 / element) @product *= element end @sum += element @count += 1 end |