From 94c57bdf2de8a3b981dcc331908dbb3b8edeb16e Mon Sep 17 00:00:00 2001 From: Till Hoffmann Date: Mon, 8 Aug 2011 18:05:34 +0200 Subject: [PATCH] Extended the chisquare distribution to support the generation of samples for non-integer dof. --- .../Distributions/Continuous/ChiSquare.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Numerics/Distributions/Continuous/ChiSquare.cs b/src/Numerics/Distributions/Continuous/ChiSquare.cs index 5d88621a..cd05120f 100644 --- a/src/Numerics/Distributions/Continuous/ChiSquare.cs +++ b/src/Numerics/Distributions/Continuous/ChiSquare.cs @@ -274,14 +274,20 @@ namespace MathNet.Numerics.Distributions /// a random number from the distribution. private static double DoSample(Random rnd, double dof) { - double sum = 0; - var n = (int)dof; - for (var i = 0; i < n; i++) + //Use the simple method if the dof is an integer anyway + if (Math.Floor(dof) == dof && dof < Int32.MaxValue) { - sum += Math.Pow(Normal.Sample(rnd, 0.0, 1.0), 2); + double sum = 0; + var n = (int)dof; + for (var i = 0; i < n; i++) + { + sum += Math.Pow(Normal.Sample(rnd, 0.0, 1.0), 2); + } + return sum; } - - return sum; + //Call the gamma function (see http://en.wikipedia.org/wiki/Gamma_distribution#Specializations + //for a justification) + return Gamma.Sample(rnd, dof / 2.0, .5); } ///