Exemplo n.º 1
0
        } //# end of sqrt.invertedGamma.gen

        //rgamma.truncated <- function(alpha, beta, range)
        public static double RGammaTruncated(double alpha, double beta, double[] range)
        {
            //# We first look on which side of the distribution (comparing to its mode)
            //# the range lies, in order to decide on which side we will compute the log.prob
            //# (choosing the correct side gives more accuracy in the sampling in the eventuality of a remote range)
            bool lowerTail = false;

            if (alpha < 1)
            {
                lowerTail = false;
            }
            else
            {
                double mode     = (alpha - 1) / beta;
                double minRange = range.Min();
                double maxRange = range.Max();

                if (minRange > mode)
                {
                    lowerTail = false;
                }
                else if (maxRange < mode)
                {
                    lowerTail = true;
                }
                else
                {
                    double logPLeft  = GammaDistribution.PGammaFromRateParameter(x: minRange, alph: alpha, rate: beta, logP: true, lowerTail: true);
                    double logPRight = GammaDistribution.PGammaFromRateParameter(x: maxRange, alph: alpha, rate: beta, logP: true, lowerTail: false);
                    lowerTail = logPLeft < logPRight;
                }
            }

            double[] logPLim = GammaDistribution.PGammaFromRateParameter(x: range, alph: alpha, rate: beta, lowerTail: lowerTail, logP: true);
            double   logP    = RNorm4CensoredMeasures.RUnifLogP1(logPLim, lowerTail: lowerTail);

            return(GammaDistribution.QGammaFromRate(logP, shape: alpha, rate: beta, logP: true, lowerTail: lowerTail));
        }