Class: Accumulators::MeanVariance
- Inherits:
-
Object
- Object
- Accumulators::MeanVariance
- Defined in:
- lib/accumulators/mean_variance.rb
Instance Attribute Summary collapse
-
#count ⇒ Object
readonly
Returns the value of attribute count.
-
#mean ⇒ Object
readonly
Returns the value of attribute mean.
-
#sumsq ⇒ Object
readonly
Returns the value of attribute sumsq.
Instance Method Summary collapse
- #add(rhs) ⇒ Object
-
#initialize ⇒ MeanVariance
constructor
A new instance of MeanVariance.
- #stddev(options = {}) ⇒ Object
- #variance(options = {}) ⇒ Object
Constructor Details
#initialize ⇒ MeanVariance
Returns a new instance of MeanVariance.
6 7 8 9 10 |
# File 'lib/accumulators/mean_variance.rb', line 6 def initialize @count = 0 @mean = 0.0 @sumsq = 0.0 end |
Instance Attribute Details
#count ⇒ Object (readonly)
Returns the value of attribute count.
4 5 6 |
# File 'lib/accumulators/mean_variance.rb', line 4 def count @count end |
#mean ⇒ Object (readonly)
Returns the value of attribute mean.
4 5 6 |
# File 'lib/accumulators/mean_variance.rb', line 4 def mean @mean end |
#sumsq ⇒ Object (readonly)
Returns the value of attribute sumsq.
4 5 6 |
# File 'lib/accumulators/mean_variance.rb', line 4 def sumsq @sumsq end |
Instance Method Details
#add(rhs) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/accumulators/mean_variance.rb', line 12 def add(rhs) if rhs.is_a? Numeric @count += 1 delta = rhs - @mean @mean += delta/@count @sumsq += delta * (rhs - @mean) elsif rhs.is_a? MeanVariance if rhs.count > 0 newCount = @count + rhs.count delta = rhs.mean - @mean newMean = @mean + delta*rhs.count/newCount newSumsq = @sumsq + rhs.sumsq + delta*delta*@count*rhs.count/newCount @count = newCount @mean = newMean @sumsq = newSumsq end else raise ArgumentError.new("You may not add #{rhs.class} to #{self.class}") end end |
#stddev(options = {}) ⇒ Object
47 48 49 |
# File 'lib/accumulators/mean_variance.rb', line 47 def stddev( = {}) Math.sqrt(variance()) end |
#variance(options = {}) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/accumulators/mean_variance.rb', line 35 def variance( = {}) if [:type] and not [:sample, :population].include? [:type] raise ArgumentError.new("type must be one of :sample, :population") end if [:type] == :population @count > 1 ? (@sumsq / (@count)) : 0.0 else @count > 1 ? (@sumsq / (@count + 1)) : 0.0 end end |