github.com/gopherd/gonum@v0.0.4/stat/distuv/chisquared.go (about) 1 // Copyright ©2016 The Gonum Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package distuv 6 7 import ( 8 "math" 9 10 "math/rand" 11 12 "github.com/gopherd/gonum/mathext" 13 ) 14 15 // ChiSquared implements the χ² distribution, a one parameter distribution 16 // with support on the positive numbers. 17 // 18 // The density function is given by 19 // 1/(2^{k/2} * Γ(k/2)) * x^{k/2 - 1} * e^{-x/2} 20 // It is a special case of the Gamma distribution, Γ(k/2, 1/2). 21 // 22 // For more information, see https://en.wikipedia.org/wiki/Chi-squared_distribution. 23 type ChiSquared struct { 24 // K is the shape parameter, corresponding to the degrees of freedom. Must 25 // be greater than 0. 26 K float64 27 28 Src rand.Source 29 } 30 31 // CDF computes the value of the cumulative density function at x. 32 func (c ChiSquared) CDF(x float64) float64 { 33 return mathext.GammaIncReg(c.K/2, x/2) 34 } 35 36 // ExKurtosis returns the excess kurtosis of the distribution. 37 func (c ChiSquared) ExKurtosis() float64 { 38 return 12 / c.K 39 } 40 41 // LogProb computes the natural logarithm of the value of the probability 42 // density function at x. 43 func (c ChiSquared) LogProb(x float64) float64 { 44 if x < 0 { 45 return math.Inf(-1) 46 } 47 lg, _ := math.Lgamma(c.K / 2) 48 return (c.K/2-1)*math.Log(x) - x/2 - (c.K/2)*math.Ln2 - lg 49 } 50 51 // Mean returns the mean of the probability distribution. 52 func (c ChiSquared) Mean() float64 { 53 return c.K 54 } 55 56 // Mode returns the mode of the distribution. 57 func (c ChiSquared) Mode() float64 { 58 return math.Max(c.K-2, 0) 59 } 60 61 // NumParameters returns the number of parameters in the distribution. 62 func (c ChiSquared) NumParameters() int { 63 return 1 64 } 65 66 // Prob computes the value of the probability density function at x. 67 func (c ChiSquared) Prob(x float64) float64 { 68 return math.Exp(c.LogProb(x)) 69 } 70 71 // Rand returns a random sample drawn from the distribution. 72 func (c ChiSquared) Rand() float64 { 73 return Gamma{c.K / 2, 0.5, c.Src}.Rand() 74 } 75 76 // Quantile returns the inverse of the cumulative distribution function. 77 func (c ChiSquared) Quantile(p float64) float64 { 78 if p < 0 || p > 1 { 79 panic(badPercentile) 80 } 81 return mathext.GammaIncRegInv(0.5*c.K, p) * 2 82 } 83 84 // StdDev returns the standard deviation of the probability distribution. 85 func (c ChiSquared) StdDev() float64 { 86 return math.Sqrt(c.Variance()) 87 } 88 89 // Survival returns the survival function (complementary CDF) at x. 90 func (c ChiSquared) Survival(x float64) float64 { 91 if x < 0 { 92 return 1 93 } 94 return mathext.GammaIncRegComp(0.5*c.K, 0.5*x) 95 } 96 97 // Variance returns the variance of the probability distribution. 98 func (c ChiSquared) Variance() float64 { 99 return 2 * c.K 100 }