//
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2015 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.
//
using System;
using System.Collections.Generic;
using IStation.Numerics.Random;
using IStation.Numerics.Statistics;
namespace IStation.Numerics.Distributions
{
///
/// Continuous Univariate Normal distribution, also known as Gaussian distribution.
/// For details about this distribution, see
/// Wikipedia - Normal distribution.
///
public class Normal : IContinuousDistribution
{
System.Random _random;
readonly double _mean;
readonly double _stdDev;
///
/// Initializes a new instance of the Normal class. This is a normal distribution with mean 0.0
/// and standard deviation 1.0. The distribution will
/// be initialized with the default random number generator.
///
public Normal()
: this(0.0, 1.0)
{
}
///
/// Initializes a new instance of the Normal class. This is a normal distribution with mean 0.0
/// and standard deviation 1.0. The distribution will
/// be initialized with the default random number generator.
///
/// The random number generator which is used to draw random samples.
public Normal(System.Random randomSource)
: this(0.0, 1.0, randomSource)
{
}
///
/// Initializes a new instance of the Normal class with a particular mean and standard deviation. The distribution will
/// be initialized with the default random number generator.
///
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
public Normal(double mean, double stddev)
{
if (!IsValidParameterSet(mean, stddev))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
_random = SystemRandomSource.Default;
_mean = mean;
_stdDev = stddev;
}
///
/// Initializes a new instance of the Normal class with a particular mean and standard deviation. The distribution will
/// be initialized with the default random number generator.
///
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// The random number generator which is used to draw random samples.
public Normal(double mean, double stddev, System.Random randomSource)
{
if (!IsValidParameterSet(mean, stddev))
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
_random = randomSource ?? SystemRandomSource.Default;
_mean = mean;
_stdDev = stddev;
}
///
/// Constructs a normal distribution from a mean and standard deviation.
///
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// The random number generator which is used to draw random samples. Optional, can be null.
/// a normal distribution.
public static Normal WithMeanStdDev(double mean, double stddev, System.Random randomSource = null)
{
return new Normal(mean, stddev, randomSource);
}
///
/// Constructs a normal distribution from a mean and variance.
///
/// The mean (μ) of the normal distribution.
/// The variance (σ^2) of the normal distribution.
/// The random number generator which is used to draw random samples. Optional, can be null.
/// A normal distribution.
public static Normal WithMeanVariance(double mean, double var, System.Random randomSource = null)
{
return new Normal(mean, Math.Sqrt(var), randomSource);
}
///
/// Constructs a normal distribution from a mean and precision.
///
/// The mean (μ) of the normal distribution.
/// The precision of the normal distribution.
/// The random number generator which is used to draw random samples. Optional, can be null.
/// A normal distribution.
public static Normal WithMeanPrecision(double mean, double precision, System.Random randomSource = null)
{
return new Normal(mean, 1.0/Math.Sqrt(precision), randomSource);
}
///
/// Estimates the normal distribution parameters from sample data with maximum-likelihood.
///
/// The samples to estimate the distribution parameters from.
/// The random number generator which is used to draw random samples. Optional, can be null.
/// A normal distribution.
/// MATLAB: normfit
public static Normal Estimate(IEnumerable samples, System.Random randomSource = null)
{
var meanStdDev = samples.MeanStandardDeviation();
return new Normal(meanStdDev.Item1, meanStdDev.Item2, randomSource);
}
///
/// A string representation of the distribution.
///
/// a string representation of the distribution.
public override string ToString()
{
return $"Normal(μ = {_mean}, σ = {_stdDev})";
}
///
/// Tests whether the provided values are valid parameters for this distribution.
///
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
public static bool IsValidParameterSet(double mean, double stddev)
{
return stddev >= 0.0 && !double.IsNaN(mean);
}
///
/// Gets the mean (μ) of the normal distribution.
///
public double Mean => _mean;
///
/// Gets the standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
///
public double StdDev => _stdDev;
///
/// Gets the variance of the normal distribution.
///
public double Variance => _stdDev*_stdDev;
///
/// Gets the precision of the normal distribution.
///
public double Precision => 1.0/(_stdDev*_stdDev);
///
/// Gets the random number generator which is used to draw random samples.
///
public System.Random RandomSource
{
get => _random;
set => _random = value ?? SystemRandomSource.Default;
}
///
/// Gets the entropy of the normal distribution.
///
public double Entropy => Math.Log(_stdDev) + Constants.LogSqrt2PiE;
///
/// Gets the skewness of the normal distribution.
///
public double Skewness => 0.0;
///
/// Gets the mode of the normal distribution.
///
public double Mode => _mean;
///
/// Gets the median of the normal distribution.
///
public double Median => _mean;
///
/// Gets the minimum of the normal distribution.
///
public double Minimum => double.NegativeInfinity;
///
/// Gets the maximum of the normal distribution.
///
public double Maximum => double.PositiveInfinity;
///
/// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x.
///
/// The location at which to compute the density.
/// the density at .
///
public double Density(double x)
{
var d = (x - _mean)/_stdDev;
return Math.Exp(-0.5*d*d)/(Constants.Sqrt2Pi*_stdDev);
}
///
/// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x).
///
/// The location at which to compute the log density.
/// the log density at .
///
public double DensityLn(double x)
{
var d = (x - _mean)/_stdDev;
return (-0.5*d*d) - Math.Log(_stdDev) - Constants.LogSqrt2Pi;
}
///
/// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x).
///
/// The location at which to compute the cumulative distribution function.
/// the cumulative distribution at location .
///
public double CumulativeDistribution(double x)
{
return 0.5*SpecialFunctions.Erfc((_mean - x)/(_stdDev*Constants.Sqrt2));
}
///
/// Computes the inverse of the cumulative distribution function (InvCDF) for the distribution
/// at the given probability. This is also known as the quantile or percent point function.
///
/// The location at which to compute the inverse cumulative density.
/// the inverse cumulative density at .
///
public double InverseCumulativeDistribution(double p)
{
return _mean - (_stdDev*Constants.Sqrt2*SpecialFunctions.ErfcInv(2.0*p));
}
///
/// Generates a sample from the normal distribution using the Box-Muller algorithm.
///
/// a sample from the distribution.
public double Sample()
{
return SampleUnchecked(_random, _mean, _stdDev);
}
///
/// Fills an array with samples generated from the distribution.
///
public void Samples(double[] values)
{
SamplesUnchecked(_random, values, _mean, _stdDev);
}
///
/// Generates a sequence of samples from the normal distribution using the Box-Muller algorithm.
///
/// a sequence of samples from the distribution.
public IEnumerable Samples()
{
return SamplesUnchecked(_random, _mean, _stdDev);
}
internal static double SampleUnchecked(System.Random rnd, double mean, double stddev)
{
double x, y;
while (!PolarTransform(rnd.NextDouble(), rnd.NextDouble(), out x, out y))
{
}
return mean + (stddev*x);
}
internal static IEnumerable SamplesUnchecked(System.Random rnd, double mean, double stddev)
{
while (true)
{
double x, y;
if (!PolarTransform(rnd.NextDouble(), rnd.NextDouble(), out x, out y))
{
continue;
}
yield return mean + (stddev*x);
yield return mean + (stddev*y);
}
}
internal static void SamplesUnchecked(System.Random rnd, double[] values, double mean, double stddev)
{
if (values.Length == 0)
{
return;
}
// Since we only accept points within the unit circle
// we need to generate roughly 4/pi=1.27 times the numbers needed.
int n = (int)Math.Ceiling(values.Length*4*Constants.InvPi);
if (n.IsOdd())
{
n++;
}
var uniform = rnd.NextDoubles(n);
// Polar transform
double x, y;
int index = 0;
for (int i = 0; i < uniform.Length && index < values.Length; i += 2)
{
if (!PolarTransform(uniform[i], uniform[i + 1], out x, out y))
{
continue;
}
values[index++] = mean + stddev*x;
if (index == values.Length)
{
return;
}
values[index++] = mean + stddev*y;
if (index == values.Length)
{
return;
}
}
// remaining, if any
while (index < values.Length)
{
if (!PolarTransform(rnd.NextDouble(), rnd.NextDouble(), out x, out y))
{
continue;
}
values[index++] = mean + stddev*x;
if (index == values.Length)
{
return;
}
values[index++] = mean + stddev*y;
if (index == values.Length)
{
return;
}
}
}
static bool PolarTransform(double a, double b, out double x, out double y)
{
var v1 = (2.0*a) - 1.0;
var v2 = (2.0*b) - 1.0;
var r = (v1*v1) + (v2*v2);
if (r >= 1.0 || r == 0.0)
{
x = 0;
y = 0;
return false;
}
var fac = Math.Sqrt(-2.0*Math.Log(r)/r);
x = v1*fac;
y = v2*fac;
return true;
}
///
/// Computes the probability density of the distribution (PDF) at x, i.e. ∂P(X ≤ x)/∂x.
///
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// The location at which to compute the density.
/// the density at .
///
/// MATLAB: normpdf
public static double PDF(double mean, double stddev, double x)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
var d = (x - mean)/stddev;
return Math.Exp(-0.5*d*d)/(Constants.Sqrt2Pi*stddev);
}
///
/// Computes the log probability density of the distribution (lnPDF) at x, i.e. ln(∂P(X ≤ x)/∂x).
///
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// The location at which to compute the density.
/// the log density at .
///
public static double PDFLn(double mean, double stddev, double x)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
var d = (x - mean)/stddev;
return (-0.5*d*d) - Math.Log(stddev) - Constants.LogSqrt2Pi;
}
///
/// Computes the cumulative distribution (CDF) of the distribution at x, i.e. P(X ≤ x).
///
/// The location at which to compute the cumulative distribution function.
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// the cumulative distribution at location .
///
/// MATLAB: normcdf
public static double CDF(double mean, double stddev, double x)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return 0.5*SpecialFunctions.Erfc((mean - x)/(stddev*Constants.Sqrt2));
}
///
/// Computes the inverse of the cumulative distribution function (InvCDF) for the distribution
/// at the given probability. This is also known as the quantile or percent point function.
///
/// The location at which to compute the inverse cumulative density.
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// the inverse cumulative density at .
///
/// MATLAB: norminv
public static double InvCDF(double mean, double stddev, double p)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return mean - (stddev*Constants.Sqrt2*SpecialFunctions.ErfcInv(2.0*p));
}
///
/// Generates a sample from the normal distribution using the Box-Muller algorithm.
///
/// The random number generator to use.
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// a sample from the distribution.
public static double Sample(System.Random rnd, double mean, double stddev)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SampleUnchecked(rnd, mean, stddev);
}
///
/// Generates a sequence of samples from the normal distribution using the Box-Muller algorithm.
///
/// The random number generator to use.
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// a sequence of samples from the distribution.
public static IEnumerable Samples(System.Random rnd, double mean, double stddev)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SamplesUnchecked(rnd, mean, stddev);
}
///
/// Fills an array with samples generated from the distribution.
///
/// The random number generator to use.
/// The array to fill with the samples.
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// a sequence of samples from the distribution.
public static void Samples(System.Random rnd, double[] values, double mean, double stddev)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
SamplesUnchecked(rnd, values, mean, stddev);
}
///
/// Generates a sample from the normal distribution using the Box-Muller algorithm.
///
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// a sample from the distribution.
public static double Sample(double mean, double stddev)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SampleUnchecked(SystemRandomSource.Default, mean, stddev);
}
///
/// Generates a sequence of samples from the normal distribution using the Box-Muller algorithm.
///
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// a sequence of samples from the distribution.
public static IEnumerable Samples(double mean, double stddev)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
return SamplesUnchecked(SystemRandomSource.Default, mean, stddev);
}
///
/// Fills an array with samples generated from the distribution.
///
/// The array to fill with the samples.
/// The mean (μ) of the normal distribution.
/// The standard deviation (σ) of the normal distribution. Range: σ ≥ 0.
/// a sequence of samples from the distribution.
public static void Samples(double[] values, double mean, double stddev)
{
if (stddev < 0.0)
{
throw new ArgumentException("Invalid parametrization for the distribution.");
}
SamplesUnchecked(SystemRandomSource.Default, values, mean, stddev);
}
}
}