Class: Spark::StatCounter

Inherits:
Object
  • Object
show all
Defined in:
lib/spark/stat_counter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(iterator) ⇒ StatCounter

Returns a new instance of StatCounter.



10
11
12
13
14
15
16
17
18
# File 'lib/spark/stat_counter.rb', line 10

def initialize(iterator)
  @n = 0
  @mu = 0.0
  @m2 = 0.0
  @max = -Float::INFINITY
  @min = Float::INFINITY

  merge(iterator)
end

Instance Attribute Details

#m2Object (readonly)

variance numerator (sum of (x - mean)^2)



6
7
8
# File 'lib/spark/stat_counter.rb', line 6

def m2
  @m2
end

#maxObject (readonly) Also known as: max_value

max of our values



7
8
9
# File 'lib/spark/stat_counter.rb', line 7

def max
  @max
end

#minObject (readonly) Also known as: min_value

min of our values



8
9
10
# File 'lib/spark/stat_counter.rb', line 8

def min
  @min
end

#muObject (readonly) Also known as: mean

mean of our values



5
6
7
# File 'lib/spark/stat_counter.rb', line 5

def mu
  @mu
end

#nObject (readonly) Also known as: count

count of our values



4
5
6
# File 'lib/spark/stat_counter.rb', line 4

def n
  @n
end

Instance Method Details

#merge(other) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/spark/stat_counter.rb', line 20

def merge(other)
  if other.is_a?(Spark::StatCounter)
    merge_stat_counter(other)
  elsif other.respond_to?(:each)
    merge_array(other)
  else
    merge_value(other)
  end

  self
end

#sample_stdevObject Also known as: sampleStdev

Return the sample standard deviation of the values, which corrects for bias in estimating the variance by dividing by N-1 instead of N.



62
63
64
# File 'lib/spark/stat_counter.rb', line 62

def sample_stdev
  Math.sqrt(sample_variance)
end

#sample_varianceObject Also known as: sampleVariance

Return the sample variance, which corrects for bias in estimating the variance by dividing by N-1 instead of N.



47
48
49
50
51
52
53
# File 'lib/spark/stat_counter.rb', line 47

def sample_variance
  if @n <= 1
    Float::NAN
  else
    @m2 / (@n - 1)
  end
end

#stdevObject

Return the standard deviation of the values.



56
57
58
# File 'lib/spark/stat_counter.rb', line 56

def stdev
  Math.sqrt(variance)
end

#sumObject



32
33
34
# File 'lib/spark/stat_counter.rb', line 32

def sum
  @n * @mu
end

#to_sObject



66
67
68
# File 'lib/spark/stat_counter.rb', line 66

def to_s
  "(count: #{count}, mean: #{mean}, stdev: #{stdev}, max: #{max}, min: #{min})"
end

#varianceObject

Return the variance of the values.



37
38
39
40
41
42
43
# File 'lib/spark/stat_counter.rb', line 37

def variance
  if @n == 0
    Float::NAN
  else
    @m2 / @n
  end
end