示例#1
0
        /// <summary>
        /// Compute the regularized upper incomplete Gamma function by a series expansion
        /// </summary>
        /// <param name="a">The shape parameter, &gt; 0</param>
        /// <param name="x">The lower bound of the integral, &gt;= 0</param>
        /// <returns></returns>
        private static double GammaUpperSeries(double a, double x)
        {
            // this series should only be applied when x is small
            // the series is: 1 - x^a sum_{k=0}^inf (-x)^k /(k! Gamma(a+k+1))
            // = (1 - 1/Gamma(a+1)) + (1 - x^a)/Gamma(a+1) - x^a sum_{k=1}^inf (-x)^k/(k! Gamma(a+k+1))
            double xaMinus1 = MMath.ExpMinus1(a * Math.Log(x));
            double aReciprocalFactorial, aReciprocalFactorialMinus1;

            if (a > 0.3)
            {
                aReciprocalFactorial       = 1 / MMath.Gamma(a + 1);
                aReciprocalFactorialMinus1 = aReciprocalFactorial - 1;
            }
            else
            {
                aReciprocalFactorialMinus1 = ReciprocalFactorialMinus1(a);
                aReciprocalFactorial       = 1 + aReciprocalFactorialMinus1;
            }
            // offset = 1 - x^a/Gamma(a+1)
            double offset = -xaMinus1 * aReciprocalFactorial - aReciprocalFactorialMinus1;
            double scale  = 1 - offset;
            double term   = x / (a + 1) * a;
            double sum    = term;

            for (int i = 1; i < 1000; i++)
            {
                term *= -(a + i) * x / ((a + i + 1) * (i + 1));
                double sumOld = sum;
                sum += term;
                //Console.WriteLine("{0}: {1}", i, sum);
                if (AreEqual(sum, sumOld))
                {
                    return(scale * sum + offset);
                }
            }
            throw new Exception(string.Format("GammaUpperSeries not converging for a={0} x={1}", a, x));
        }
示例#2
0
        /// <summary>
        /// Sample from a Gaussian(0,1) truncated at the given upper and lower bounds
        /// </summary>
        /// <param name="lowerBound">Can be -Infinity.</param>
        /// <param name="upperBound">Must be &gt;= <paramref name="lowerBound"/>.  Can be Infinity.</param>
        /// <returns>A real number &gt;= <paramref name="lowerBound"/> and &lt; <paramref name="upperBound"/></returns>
        public static double NormalBetween(double lowerBound, double upperBound, IPolyrand random = null)
        {
            if (double.IsNaN(lowerBound))
            {
                throw new ArgumentException("lowerBound is NaN");
            }
            if (double.IsNaN(upperBound))
            {
                throw new ArgumentException("upperBound is NaN");
            }
            double delta = upperBound - lowerBound;

            if (delta == 0)
            {
                return(lowerBound);
            }
            if (delta < 0)
            {
                throw new ArgumentException("upperBound (" + upperBound + ") < lowerBound (" + lowerBound + ")");
            }
            // Switch between the following 3 options:
            // 1. Gaussian rejection, with acceptance rate Z = NormalCdf(upperBound) - NormalCdf(lowerBound)
            // 2. Uniform rejection, with acceptance rate sqrt(2*pi)*Z/delta if the interval contains 0
            // 3. Truncated exponential rejection, with acceptance rate
            //    = sqrt(2*pi)*Z*lambda*exp(-lambda^2/2)/(exp(-lambda*lowerBound)-exp(-lambda*upperBound))
            //    = sqrt(2*pi)*Z*lowerBound*exp(lowerBound^2/2)/(1-exp(-lowerBound*(upperBound-lowerBound)))
            // (3) has the highest acceptance rate under the following conditions:
            //     lowerBound > 0.5 or (lowerBound > 0 and delta < 2.5)
            // (2) has the highest acceptance rate if the interval contains 0 and delta < sqrt(2*pi)
            // (1) has the highest acceptance rate otherwise
            if (lowerBound > 0.5 || (lowerBound > 0 && delta < 2.5))
            {
                // Rejection sampler using truncated exponential proposal
                double lambda = lowerBound;
                double s      = MMath.ExpMinus1(-lambda * delta);
                double c      = 2 * lambda * lambda;
                while (true)
                {
                    double x = -MMath.Log1Plus(s * NextDouble(random));
                    double u = -System.Math.Log(NextDouble(random));
                    if (c * u > x * x)
                    {
                        return(x / lambda + lowerBound);
                    }
                }
                throw new Exception("failed to sample");
            }
            else if (upperBound < -0.5 || (upperBound < 0 && delta < 2.5))
            {
                return(-NormalBetween(-upperBound, -lowerBound));
            }
            else if (lowerBound <= 0 && upperBound >= 0 && delta < MMath.Sqrt2PI)
            {
                // Uniform rejection
                while (true)
                {
                    double x = NextDouble(random) * delta + lowerBound;
                    double u = -System.Math.Log(NextDouble(random));
                    if (2 * u > x * x)
                    {
                        return(x);
                    }
                }
            }
            else
            {
                // Gaussian rejection
                while (true)
                {
                    double x = Rand.Normal(random);
                    if (x >= lowerBound && x < upperBound)
                    {
                        return(x);
                    }
                }
            }
        }