Class: NetworkResiliency::Stats

Inherits:
Object
  • Object
show all
Defined in:
lib/network_resiliency/stats.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values = []) ⇒ Stats

Returns a new instance of Stats.



15
16
17
18
19
20
21
# File 'lib/network_resiliency/stats.rb', line 15

def initialize(values = [])
  @n = 0
  @avg = 0.0
  @sq_dist = 0.0 # sum of squared distance from mean

  values.each {|x| update(x) }
end

Instance Attribute Details

#avgObject (readonly)

Returns the value of attribute avg.



3
4
5
# File 'lib/network_resiliency/stats.rb', line 3

def avg
  @avg
end

#nObject (readonly)

Returns the value of attribute n.



3
4
5
# File 'lib/network_resiliency/stats.rb', line 3

def n
  @n
end

Class Method Details

.from(n, avg, sq_dist) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/network_resiliency/stats.rb', line 5

def self.from(n, avg, sq_dist)
  new.tap do |instance|
    instance.instance_eval do
      @n = n
      @avg = avg
      @sq_dist = sq_dist
    end
  end
end

Instance Method Details

#<<(value) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/network_resiliency/stats.rb', line 23

def <<(value)
  case value
  when Array
    value.each {|x| update(x) }
  when self.class
    merge!(value)
  else
    update(value)
  end

  self
end

#merge(other) ⇒ Object Also known as: +



44
45
46
# File 'lib/network_resiliency/stats.rb', line 44

def merge(other)
  dup.merge!(other)
end

#merge!(other) ⇒ Object

Raises:

  • (ArgumentError)


49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/network_resiliency/stats.rb', line 49

def merge!(other)
  raise ArgumentError unless other.is_a?(self.class)

  prev_n = n
  @n += other.n

  delta = other.avg - avg
  @avg += delta * other.n / n

  @sq_dist += other.instance_variable_get(:@sq_dist)
  @sq_dist += (delta ** 2) * prev_n * other.n / n

  self
end

#stdevObject



40
41
42
# File 'lib/network_resiliency/stats.rb', line 40

def stdev
  Math.sqrt(variance)
end

#variance(sample: false) ⇒ Object



36
37
38
# File 'lib/network_resiliency/stats.rb', line 36

def variance(sample: false)
  @sq_dist / (sample ? (@n - 1) : @n)
end