Class: Mathstats

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

Defined Under Namespace

Modules: Mixin

Class Method Summary collapse

Class Method Details

.attach_to(klass) ⇒ Object



49
50
51
# File 'lib/mathstats.rb', line 49

def attach_to(klass)
  klass.send :include, Mixin
end

.mean(array, identity = 0, &block) ⇒ Object Also known as: average



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

def mean(array, identity = 0, &block)
  array.size > 0 ? sum(array, identity, &block) / array.size.to_f : identity
end

.standard_deviation(array, options = {}, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/mathstats.rb', line 8

def standard_deviation(array, options = {}, &block)
  options = {:default => 0}.merge(options)
  return options[:default] unless array.size > 0

  if block_given?
    return standard_deviation( array.map(&block), options )
  end

  Math.sqrt( variance(array, options) )
end

.sum(array, identity = 0, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/mathstats.rb', line 19

def sum(array, identity = 0, &block)
  return identity unless array.size > 0

  if block_given?
    sum( array.map(&block) )
  else
    array.inject { |sum, element| sum + element }
  end
end

.variance(array, options = {}, &block) ⇒ Object

Two pass algorithm is currently the only algo supported en.wikipedia.org/wiki/Algorithms_for_calculating_variance



31
32
33
34
35
36
37
38
39
40
# File 'lib/mathstats.rb', line 31

def variance(array, options = {}, &block)
  options = {:default => 0, :algo => :two_pass, :population => :infinite}.merge(options)
  return options[:default] unless array.size > 0

  if block_given?
    return variance( array.map(&block), options )
  end

  variance_two_pass(array, options)
end

.variance_two_pass(array, options) ⇒ Object



42
43
44
45
46
47
# File 'lib/mathstats.rb', line 42

def variance_two_pass(array, options)
  n        = array.size
  denom    = options[:population] == :infinite ? n - 1 : n
  mean     = mean(array)
  variance = array.inject(0) {|memo, element| memo + (element - mean)**2 } / denom
end