Class: MoreMath::ChiSquareDistribution

Inherits:
Object
  • Object
show all
Includes:
Functions
Defined in:
lib/more_math/distributions.rb

Overview

This class is used to compute the Chi-Square Distribution.

The chi-square distribution is a continuous probability distribution that arises in the analysis of variance and goodness-of-fit tests.

Examples:

Creating a chi-square distribution

chi2 = MoreMath::ChiSquareDistribution.new(5)  # 5 degrees of freedom

Calculating probabilities

chi2 = MoreMath::ChiSquareDistribution.new(5)
p = chi2.probability(10.645)  # Probability that X <= 10.645

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Functions

#beta, beta, #beta_regularized, beta_regularized, #cantor_pairing, cantor_pairing, #cantor_pairing_inv, cantor_pairing_inv, #erf, #erfc, #gamma, gamma, #gammaP_regularized, gammaP_regularized, #gammaQ_regularized, gammaQ_regularized, #log_beta, log_beta, #log_ceil, log_ceil, #log_floor, log_floor, #log_gamma, #logb, logb, #numberify_string, numberify_string, #stringify_number, stringify_number

Constructor Details

#initialize(df) ⇒ ChiSquareDistribution

Creates a ChiSquareDistribution for df degrees of freedom.

Parameters:

  • df (Integer)

    The degrees of freedom



102
103
104
105
# File 'lib/more_math/distributions.rb', line 102

def initialize(df)
  @df = df
  @df_half = @df / 2.0
end

Instance Attribute Details

#dfInteger (readonly)

Returns the degrees of freedom of this distribution.

Returns:

  • (Integer)

    The degrees of freedom



110
111
112
# File 'lib/more_math/distributions.rb', line 110

def df
  @df
end

Instance Method Details

#inverse_probability(p) ⇒ Float

Returns the inverse cumulative probability value of the ChiSquareDistribution for the probability p.

This finds the value x such that P(X <= x) = p where X ~ χ²(df).

Parameters:

  • p (Numeric)

    The probability (0 < p < 1)

Returns:

  • (Float)

    The inverse cumulative probability (quantile)



134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/more_math/distributions.rb', line 134

def inverse_probability(p)
  case
  when p <= 0, p >= 1
    0.0
  else
    begin
      bisect = NewtonBisection.new { |x| probability(x) - p }
      range = bisect.bracket 0.5..10
      bisect.solve(range, 1_000_000)
    rescue
      0 / 0.0   # NaN on error
    end
  end
end

#probability(x) ⇒ Float

Returns the cumulative probability (p-value) of the ChiSquareDistribution for the value x.

This calculates P(X <= x) where X ~ χ²(df).

Parameters:

  • x (Numeric)

    The value at which to calculate the cumulative probability

Returns:

  • (Float)

    The cumulative probability P(X <= x)



119
120
121
122
123
124
125
# File 'lib/more_math/distributions.rb', line 119

def probability(x)
  if x < 0
    0.0
  else
    gammaP_regularized(x / 2, @df_half)
  end
end