Class: Accumulators::MeanVariance

Inherits:
Object
  • Object
show all
Defined in:
lib/accumulators/mean_variance.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMeanVariance

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

#countObject (readonly)

Returns the value of attribute count.



4
5
6
# File 'lib/accumulators/mean_variance.rb', line 4

def count
  @count
end

#meanObject (readonly)

Returns the value of attribute mean.



4
5
6
# File 'lib/accumulators/mean_variance.rb', line 4

def mean
  @mean
end

#sumsqObject (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(options = {})
  Math.sqrt(variance(options))
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(options = {})
  if options[:type] and not [:sample, :population].include? options[:type]
    raise ArgumentError.new("type must be one of :sample, :population")
  end

  if options[:type] == :population
    @count > 1 ? (@sumsq / (@count)) : 0.0
  else
    @count > 1 ? (@sumsq / (@count + 1)) : 0.0
  end
end