// // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // namespace MathNet.Numerics.Distributions { using System; using System.Collections.Generic; using Properties; /// /// The negative binomial is a distribution over the natural numbers with two parameters r,p. For the special /// case that r is an integer one can interpret the distribution as the number of tails before the r'th head /// when the probability of head is p. /// Wikipedia - NegativeBinomial distribution. /// /// The distribution will use the by default. /// Users can set the random number generator by using the property. /// The statistics classes will check all the incoming parameters whether they are in the allowed /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters /// to false, all parameter checks can be turned off. public class NegativeBinomial : IDiscreteDistribution { /// /// The r parameter of the distribution. /// double _r; /// /// The p parameter of the distribution. /// double _p; /// /// The distribution's random number generator. /// Random _random; /// /// Gets or sets the number of trials. /// public double R { get { return _r; } set { SetParameters(value, _p); } } /// /// Gets or sets the probability of success. /// public double P { get { return _p; } set { SetParameters(_r, value); } } /// /// Initializes a new instance of the class. /// /// The number of trials. /// The probability of a trial resulting in success. public NegativeBinomial(double r, double p) { _random = new Random(); SetParameters(r, p); } /// /// Initializes a new instance of the class. /// /// The number of trials. /// The probability of a trial resulting in success. /// The random number generator which is used to draw random samples. public NegativeBinomial(double r, double p, Random randomSource) { _random = randomSource ?? new Random(); SetParameters(r, p); } /// /// Sets the parameters of the distribution after checking their validity. /// /// The number of trials. /// The probability of a trial resulting in success. /// When the parameters don't pass the function. void SetParameters(double r, double p) { if (Control.CheckDistributionParameters && !IsValidParameterSet(r, p)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } _p = p; _r = r; } /// /// Checks whether the parameters of the distribution are valid. /// /// The number of trials. /// The probability of a trial resulting in success. /// true when the parameters are valid, false otherwise. static bool IsValidParameterSet(double r, double p) { if (r < 0.0 || Double.IsNaN(r)) { return false; } if (p < 0.0 || p > 1.0 || Double.IsNaN(p)) { return false; } return true; } /// /// Returns a that represents this instance. /// /// /// A that represents this instance. /// public override string ToString() { return "NegativeBinomial(R = " + _r + ", P = " + _p + ")"; } #region IDistribution Members /// /// Gets or sets the distribution's random number generator. /// public Random RandomSource { get { return _random; } set { if (value == null) { throw new ArgumentNullException(); } _random = value; } } /// /// Gets the mean of the distribution. /// public double Mean { get { return _r*(1.0 - _p)/_p; } } /// /// Gets the variance of the distribution. /// public double Variance { get { return _r*(1.0 - _p)/(_p*_p); } } /// /// Gets the standard deviation of the distribution. /// public double StdDev { get { return Math.Sqrt(_r*(1.0 - _p))/_p; } } /// /// Gets the entropy of the distribution. /// public double Entropy { get { throw new NotSupportedException(); } } /// /// Gets the skewness of the distribution. /// public double Skewness { get { return (2.0 - _p)/Math.Sqrt(_r*(1.0 - _p)); } } /// /// Computes the cumulative distribution function of the NegativeBinomial distribution. /// /// The location at which to compute the cumulative density. /// the cumulative density at . public double CumulativeDistribution(double x) { return 1 - SpecialFunctions.BetaRegularized(x + 1, _r, 1 - _p); } #endregion #region IDiscreteDistribution Members /// /// Gets the mode of the distribution /// public int Mode { get { return _r > 1.0 ? (int) Math.Floor((_r - 1.0)*(1.0 - _p)/_p) : 0; } } /// /// Gets the median of the distribution. /// public int Median { get { throw new NotSupportedException(); } } /// /// Gets the smallest element in the domain of the distributions which can be represented by an integer. /// public int Minimum { get { return 0; } } /// /// Gets the largest element in the domain of the distributions which can be represented by an integer. /// public int Maximum { get { return int.MaxValue; } } /// /// Computes values of the probability mass function. /// /// The location in the domain where we want to evaluate the probability mass function. /// /// the probability mass at location . /// public double Probability(int k) { var ln = SpecialFunctions.GammaLn(_r + k) - SpecialFunctions.GammaLn(_r) - SpecialFunctions.GammaLn(k + 1.0) + (_r*Math.Log(_p)) + (k*Math.Log(1.0 - _p)); return Math.Exp(ln); } /// /// Computes values of the log probability mass function. /// /// The location in the domain where we want to evaluate the log probability mass function. /// /// the log probability mass at location . /// public double ProbabilityLn(int k) { var ln = SpecialFunctions.GammaLn(_r + k) - SpecialFunctions.GammaLn(_r) - SpecialFunctions.GammaLn(k + 1.0) + (_r*Math.Log(_p)) + (k*Math.Log(1.0 - _p)); return ln; } #endregion /// /// Samples a negative binomial distributed random variable. /// /// The random number generator to use. /// The r parameter. /// The p parameter. /// a sample from the distribution. internal static int SampleUnchecked(Random rnd, double r, double p) { var lambda = Gamma.SampleUnchecked(rnd, r, p); var c = Math.Exp(-lambda); var p1 = 1.0; var k = 0; do { k = k + 1; p1 = p1*rnd.NextDouble(); } while (p1 >= c); return k - 1; } /// /// Samples a NegativeBinomial distributed random variable. /// /// a sample from the distribution. public int Sample() { return SampleUnchecked(RandomSource, _r, _p); } /// /// Samples an array of NegativeBinomial distributed random variables. /// /// a sequence of samples from the distribution. public IEnumerable Samples() { while (true) { yield return SampleUnchecked(RandomSource, _r, _p); } } /// /// Samples a random variable. /// /// The random number generator to use. /// The r parameter. /// The p parameter. public static int Sample(Random rnd, double r, double p) { if (Control.CheckDistributionParameters && !IsValidParameterSet(r, p)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } return SampleUnchecked(rnd, r, p); } /// /// Samples a sequence of this random variable. /// /// The random number generator to use. /// The r parameter. /// The p parameter. public static IEnumerable Samples(Random rnd, double r, double p) { if (Control.CheckDistributionParameters && !IsValidParameterSet(r, p)) { throw new ArgumentOutOfRangeException(Resources.InvalidDistributionParameters); } while (true) { yield return SampleUnchecked(rnd, r, p); } } } }