Class: Accumulators::Mean
- Inherits:
-
Object
- Object
- Accumulators::Mean
- Defined in:
- lib/accumulators/mean.rb
Instance Attribute Summary collapse
-
#count ⇒ Object
readonly
Returns the value of attribute count.
-
#mean ⇒ Object
readonly
Returns the value of attribute mean.
Instance Method Summary collapse
- #add(rhs) ⇒ Object
-
#initialize ⇒ Mean
constructor
A new instance of Mean.
Constructor Details
#initialize ⇒ Mean
Returns a new instance of Mean.
6 7 8 9 |
# File 'lib/accumulators/mean.rb', line 6 def initialize @count = 0 @mean = 0.0 end |
Instance Attribute Details
#count ⇒ Object (readonly)
Returns the value of attribute count.
4 5 6 |
# File 'lib/accumulators/mean.rb', line 4 def count @count end |
#mean ⇒ Object (readonly)
Returns the value of attribute mean.
4 5 6 |
# File 'lib/accumulators/mean.rb', line 4 def mean @mean end |
Instance Method Details
#add(rhs) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/accumulators/mean.rb', line 11 def add(rhs) if rhs.is_a? Numeric value_to_add = rhs.to_f @mean = @mean + (value_to_add - @mean)/(@count + 1) @count += 1 elsif rhs.is_a? Accumulators::Mean sum = @mean * @count rhs_sum = rhs.mean * rhs.count @count = @count + rhs.count @mean = (sum + rhs_sum) / @count else raise ArgumentError.new("You may not add #{rhs.class} to #{self.class}") end end |