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
# 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)
  end
end

#density_function(value) ⇒ Object



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

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))

  (1.0/left_down) * right
end

#modeObject



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

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

#varianceObject



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

def variance
  degrees_of_freedom * 2
end