Class: RubyStatistics::Distribution::ChiSquared

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-statistics/distribution/chi_squared.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(k) ⇒ ChiSquared

Returns a new instance of ChiSquared.


8
9
10
# File 'lib/ruby-statistics/distribution/chi_squared.rb', line 8

def initialize(k)
  self.degrees_of_freedom = k
end

Instance Attribute Details

#degrees_of_freedomObject Also known as: mean

Returns the value of attribute degrees_of_freedom.


4
5
6
# File 'lib/ruby-statistics/distribution/chi_squared.rb', line 4

def degrees_of_freedom
  @degrees_of_freedom
end

Instance Method Details

#cumulative_function(value) ⇒ Object


12
13
14
15
16
17
18
19
20
21
# File 'lib/ruby-statistics/distribution/chi_squared.rb', line 12

def cumulative_function(value)
  if degrees_of_freedom == 2
    # Special case where DF = 2 https://en.wikipedia.org/wiki/Chi-squared_distribution#Cumulative_distribution_function
    1.0 - Math.exp((-1.0 * value / 2.0))
  else
    k = degrees_of_freedom/2.0
    # Math.lower_incomplete_gamma_function(k, value/2.0)/Math.gamma(k)
    Math.normalised_lower_incomplete_gamma_function(k, value / 2.0)
  end
end

#density_function(value) ⇒ Object


23
24
25
26
27
28
29
30
31
32
# File 'lib/ruby-statistics/distribution/chi_squared.rb', line 23

def density_function(value)
  return 0 if value < 0

  common = degrees_of_freedom/2.0

  left_down = (2 ** common) * Math.gamma(common)
  right = (value ** (common - 1)) * Math.exp(-(value/2.0))

  right / left_down
end

#modeObject


34
35
36
# File 'lib/ruby-statistics/distribution/chi_squared.rb', line 34

def mode
  [degrees_of_freedom - 2, 0].max
end

#varianceObject


38
39
40
# File 'lib/ruby-statistics/distribution/chi_squared.rb', line 38

def variance
  degrees_of_freedom * 2
end