    001    /*
    002     * Licensed to the Apache Software Foundation (ASF) under one or more
    003     * contributor license agreements.  See the NOTICE file distributed with
    004     * this work for additional information regarding copyright ownership.
    005     * The ASF licenses this file to You under the Apache License, Version 2.0
    006     * (the "License"); you may not use this file except in compliance with
    007     * the License.  You may obtain a copy of the License at
    008     *
    009     *      http://www.apache.org/licenses/LICENSE-2.0
    010     *
    011     * Unless required by applicable law or agreed to in writing, software
    012     * distributed under the License is distributed on an "AS IS" BASIS,
    013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014     * See the License for the specific language governing permissions and
    015     * limitations under the License.
    016     */
    017    package org.apache.commons.math3.special;
    018
    019    import org.apache.commons.math3.exception.MaxCountExceededException;
    020    import org.apache.commons.math3.exception.NumberIsTooLargeException;
    021    import org.apache.commons.math3.exception.NumberIsTooSmallException;
    022    import org.apache.commons.math3.util.ContinuedFraction;
    023    import org.apache.commons.math3.util.FastMath;
    024
    025    /**
    026     * <p>
    027     * This is a utility class that provides computation methods related to the
    028     * &Gamma; (Gamma) family of functions.
    029     * </p>
    030     * <p>
    031     * Implementation of {@link #invGamma1pm1(double)} and
    032     * {@link #logGamma1p(double)} is based on the algorithms described in
    033     * <ul>
    034     * <li><a href="http://dx.doi.org/10.1145/22721.23109">Didonato and Morris
    035     * (1986)</a>, <em>Computation of the Incomplete Gamma Function Ratios and
    036     *     their Inverse</em>, TOMS 12(4), 377-393,</li>
    037     * <li><a href="http://dx.doi.org/10.1145/131766.131776">Didonato and Morris
    038     * (1992)</a>, <em>Algorithm 708: Significant Digit Computation of the
    039     *     Incomplete Beta Function Ratios</em>, TOMS 18(3), 360-373,</li>
    040     * </ul>
    041     * and implemented in the
    042     * <a href="http://www.dtic.mil/docs/citations/ADA476840">NSWC Library of Mathematical Functions</a>,
    043     * available
    044     * <a href="http://www.ualberta.ca/CNS/RESEARCH/Software/NumericalNSWC/site.html">here</a>.
    045     * This library is "approved for public release", and the
    046     * <a href="http://www.dtic.mil/dtic/pdf/announcements/CopyrightGuidance.pdf">Copyright guidance</a>
    047     * indicates that unless otherwise stated in the code, all FORTRAN functions in
    048     * this library are license free. Since no such notice appears in the code these
    049     * functions can safely be ported to Commons-Math.
    050     * </p>
    051     *
    052     * @version $Id: Gamma.java 1422313 2012-12-15 18:53:41Z psteitz $
    053     */
    054    public class Gamma {
    055        /**
    056         * <a href="http://en.wikipedia.org/wiki/Euler-Mascheroni_constant">Euler-Mascheroni constant</a>
    057         * @since 2.0
    058         */
    059        public static final double GAMMA = 0.577215664901532860606512090082;
    060
    061        /**
    062         * The value of the {@code g} constant in the Lanczos approximation, see
    063         * {@link #lanczos(double)}.
    064         * @since 3.1
    065         */
    066        public static final double LANCZOS_G = 607.0 / 128.0;
    067
    068        /** Maximum allowed numerical error. */
    069        private static final double DEFAULT_EPSILON = 10e-15;
    070
    071        /** Lanczos coefficients */
    072        private static final double[] LANCZOS = {
    073            0.99999999999999709182,
    074            57.156235665862923517,
    075            -59.597960355475491248,
    076            14.136097974741747174,
    077            -0.49191381609762019978,
    078            .33994649984811888699e-4,
    079            .46523628927048575665e-4,
    080            -.98374475304879564677e-4,
    081            .15808870322491248884e-3,
    082            -.21026444172410488319e-3,
    083            .21743961811521264320e-3,
    084            -.16431810653676389022e-3,
    085            .84418223983852743293e-4,
    086            -.26190838401581408670e-4,
    087            .36899182659531622704e-5,
    088        };
    089
    090        /** Avoid repeated computation of log of 2 PI in logGamma */
    091        private static final double HALF_LOG_2_PI = 0.5 * FastMath.log(2.0 * FastMath.PI);
    092
    093        /** The constant value of &radic;(2&pi;). */
    094        private static final double SQRT_TWO_PI = 2.506628274631000502;
    095
    096        // limits for switching algorithm in digamma
    097        /** C limit. */
    098        private static final double C_LIMIT = 49;
    099
    100        /** S limit. */
    101        private static final double S_LIMIT = 1e-5;
    102
    103        /*
    104         * Constants for the computation of double invGamma1pm1(double).
    105         * Copied from DGAM1 in the NSWC library.
    106         */
    107
    108        /** The constant {@code A0} defined in {@code DGAM1}. */
    109        private static final double INV_GAMMA1P_M1_A0 = .611609510448141581788E-08;
    110
    111        /** The constant {@code A1} defined in {@code DGAM1}. */
    112        private static final double INV_GAMMA1P_M1_A1 = .624730830116465516210E-08;
    113
    114        /** The constant {@code B1} defined in {@code DGAM1}. */
    115        private static final double INV_GAMMA1P_M1_B1 = .203610414066806987300E+00;
    116
    117        /** The constant {@code B2} defined in {@code DGAM1}. */
    118        private static final double INV_GAMMA1P_M1_B2 = .266205348428949217746E-01;
    119
    120        /** The constant {@code B3} defined in {@code DGAM1}. */
    121        private static final double INV_GAMMA1P_M1_B3 = .493944979382446875238E-03;
    122
    123        /** The constant {@code B4} defined in {@code DGAM1}. */
    124        private static final double INV_GAMMA1P_M1_B4 = -.851419432440314906588E-05;
    125
    126        /** The constant {@code B5} defined in {@code DGAM1}. */
    127        private static final double INV_GAMMA1P_M1_B5 = -.643045481779353022248E-05;
    128
    129        /** The constant {@code B6} defined in {@code DGAM1}. */
    130        private static final double INV_GAMMA1P_M1_B6 = .992641840672773722196E-06;
    131
    132        /** The constant {@code B7} defined in {@code DGAM1}. */
    133        private static final double INV_GAMMA1P_M1_B7 = -.607761895722825260739E-07;
    134
    135        /** The constant {@code B8} defined in {@code DGAM1}. */
    136        private static final double INV_GAMMA1P_M1_B8 = .195755836614639731882E-09;
    137
    138        /** The constant {@code P0} defined in {@code DGAM1}. */
    139        private static final double INV_GAMMA1P_M1_P0 = .6116095104481415817861E-08;
    140
    141        /** The constant {@code P1} defined in {@code DGAM1}. */
    142        private static final double INV_GAMMA1P_M1_P1 = .6871674113067198736152E-08;
    143
    144        /** The constant {@code P2} defined in {@code DGAM1}. */
    145        private static final double INV_GAMMA1P_M1_P2 = .6820161668496170657918E-09;
    146
    147        /** The constant {@code P3} defined in {@code DGAM1}. */
    148        private static final double INV_GAMMA1P_M1_P3 = .4686843322948848031080E-10;
    149
    150        /** The constant {@code P4} defined in {@code DGAM1}. */
    151        private static final double INV_GAMMA1P_M1_P4 = .1572833027710446286995E-11;
    152
    153        /** The constant {@code P5} defined in {@code DGAM1}. */
    154        private static final double INV_GAMMA1P_M1_P5 = -.1249441572276366213222E-12;
    155
    156        /** The constant {@code P6} defined in {@code DGAM1}. */
    157        private static final double INV_GAMMA1P_M1_P6 = .4343529937408594255178E-14;
    158
    159        /** The constant {@code Q1} defined in {@code DGAM1}. */
    160        private static final double INV_GAMMA1P_M1_Q1 = .3056961078365221025009E+00;
    161
    162        /** The constant {@code Q2} defined in {@code DGAM1}. */
    163        private static final double INV_GAMMA1P_M1_Q2 = .5464213086042296536016E-01;
    164
    165        /** The constant {@code Q3} defined in {@code DGAM1}. */
    166        private static final double INV_GAMMA1P_M1_Q3 = .4956830093825887312020E-02;
    167
    168        /** The constant {@code Q4} defined in {@code DGAM1}. */
    169        private static final double INV_GAMMA1P_M1_Q4 = .2692369466186361192876E-03;
    170
    171        /** The constant {@code C} defined in {@code DGAM1}. */
    172        private static final double INV_GAMMA1P_M1_C = -.422784335098467139393487909917598E+00;
    173
    174        /** The constant {@code C0} defined in {@code DGAM1}. */
    175        private static final double INV_GAMMA1P_M1_C0 = .577215664901532860606512090082402E+00;
    176
    177        /** The constant {@code C1} defined in {@code DGAM1}. */
    178        private static final double INV_GAMMA1P_M1_C1 = -.655878071520253881077019515145390E+00;
    179
    180        /** The constant {@code C2} defined in {@code DGAM1}. */
    181        private static final double INV_GAMMA1P_M1_C2 = -.420026350340952355290039348754298E-01;
    182
    183        /** The constant {@code C3} defined in {@code DGAM1}. */
    184        private static final double INV_GAMMA1P_M1_C3 = .166538611382291489501700795102105E+00;
    185
    186        /** The constant {@code C4} defined in {@code DGAM1}. */
    187        private static final double INV_GAMMA1P_M1_C4 = -.421977345555443367482083012891874E-01;
    188
    189        /** The constant {@code C5} defined in {@code DGAM1}. */
    190        private static final double INV_GAMMA1P_M1_C5 = -.962197152787697356211492167234820E-02;
    191
    192        /** The constant {@code C6} defined in {@code DGAM1}. */
    193        private static final double INV_GAMMA1P_M1_C6 = .721894324666309954239501034044657E-02;
    194
    195        /** The constant {@code C7} defined in {@code DGAM1}. */
    196        private static final double INV_GAMMA1P_M1_C7 = -.116516759185906511211397108401839E-02;
    197
    198        /** The constant {@code C8} defined in {@code DGAM1}. */
    199        private static final double INV_GAMMA1P_M1_C8 = -.215241674114950972815729963053648E-03;
    200
    201        /** The constant {@code C9} defined in {@code DGAM1}. */
    202        private static final double INV_GAMMA1P_M1_C9 = .128050282388116186153198626328164E-03;
    203
    204        /** The constant {@code C10} defined in {@code DGAM1}. */
    205        private static final double INV_GAMMA1P_M1_C10 = -.201348547807882386556893914210218E-04;
    206
    207        /** The constant {@code C11} defined in {@code DGAM1}. */
    208        private static final double INV_GAMMA1P_M1_C11 = -.125049348214267065734535947383309E-05;
    209
    210        /** The constant {@code C12} defined in {@code DGAM1}. */
    211        private static final double INV_GAMMA1P_M1_C12 = .113302723198169588237412962033074E-05;
    212
    213        /** The constant {@code C13} defined in {@code DGAM1}. */
    214        private static final double INV_GAMMA1P_M1_C13 = -.205633841697760710345015413002057E-06;
    215
    216        /**
    217         * Default constructor.  Prohibit instantiation.
    218         */
    219        private Gamma() {}
    220
    221        /**
    222         * <p>
    223         * Returns the value of log&nbsp;&Gamma;(x) for x&nbsp;&gt;&nbsp;0.
    224         * </p>
    225         * <p>
    226         * For x &le; 8, the implementation is based on the double precision
    227         * implementation in the <em>NSWC Library of Mathematics Subroutines</em>,
    228         * {@code DGAMLN}. For x &gt; 8, the implementation is based on
    229         * </p>
    230         * <ul>
    231         * <li><a href="http://mathworld.wolfram.com/GammaFunction.html">Gamma
    232         *     Function</a>, equation (28).</li>
    233         * <li><a href="http://mathworld.wolfram.com/LanczosApproximation.html">
    234         *     Lanczos Approximation</a>, equations (1) through (5).</li>
    235         * <li><a href="http://my.fit.edu/~gabdo/gamma.txt">Paul Godfrey, A note on
    236         *     the computation of the convergent Lanczos complex Gamma
    237         *     approximation</a></li>
    238         * </ul>
    239         *
    240         * @param x Argument.
    241         * @return the value of {@code log(Gamma(x))}, {@code Double.NaN} if
    242         * {@code x <= 0.0}.
    243         */
    244        public static double logGamma(double x) {
    245            double ret;
    246
    247            if (Double.isNaN(x) || (x <= 0.0)) {
    248                ret = Double.NaN;
    249            } else if (x < 0.5) {
    250                return logGamma1p(x) - FastMath.log(x);
    251            } else if (x <= 2.5) {
    252                return logGamma1p((x - 0.5) - 0.5);
    253            } else if (x <= 8.0) {
    254                final int n = (int) FastMath.floor(x - 1.5);
    255                double prod = 1.0;
    256                for (int i = 1; i <= n; i++) {
    257                    prod *= x - i;
    258                }
    259                return logGamma1p(x - (n + 1)) + FastMath.log(prod);
    260            } else {
    261                double sum = lanczos(x);
    262                double tmp = x + LANCZOS_G + .5;
    263                ret = ((x + .5) * FastMath.log(tmp)) - tmp +
    264                    HALF_LOG_2_PI + FastMath.log(sum / x);
    265            }
    266
    267            return ret;
    268        }
    269
    270        /**
    271         * Returns the regularized gamma function P(a, x).
    272         *
    273         * @param a Parameter.
    274         * @param x Value.
    275         * @return the regularized gamma function P(a, x).
    276         * @throws MaxCountExceededException if the algorithm fails to converge.
    277         */
    278        public static double regularizedGammaP(double a, double x) {
    279            return regularizedGammaP(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE);
    280        }
    281
    282        /**
    283         * Returns the regularized gamma function P(a, x).
    284         *
    285         * The implementation of this method is based on:
    286         * <ul>
    287         *  <li>
    288         *   <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html">
    289         *   Regularized Gamma Function</a>, equation (1)
    290         *  </li>
    291         *  <li>
    292         *   <a href="http://mathworld.wolfram.com/IncompleteGammaFunction.html">
    293         *   Incomplete Gamma Function</a>, equation (4).
    294         *  </li>
    295         *  <li>
    296         *   <a href="http://mathworld.wolfram.com/ConfluentHypergeometricFunctionoftheFirstKind.html">
    297         *   Confluent Hypergeometric Function of the First Kind</a>, equation (1).
    298         *  </li>
    299         * </ul>
    300         *
    301         * @param a the a parameter.
    302         * @param x the value.
    303         * @param epsilon When the absolute value of the nth item in the
    304         * series is less than epsilon the approximation ceases to calculate
    305         * further elements in the series.
    306         * @param maxIterations Maximum number of "iterations" to complete.
    307         * @return the regularized gamma function P(a, x)
    308         * @throws MaxCountExceededException if the algorithm fails to converge.
    309         */
    310        public static double regularizedGammaP(double a,
    311                                               double x,
    312                                               double epsilon,
    313                                               int maxIterations) {
    314            double ret;
    315
    316            if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) {
    317                ret = Double.NaN;
    318            } else if (x == 0.0) {
    319                ret = 0.0;
    320            } else if (x >= a + 1) {
    321                // use regularizedGammaQ because it should converge faster in this
    322                // case.
    323                ret = 1.0 - regularizedGammaQ(a, x, epsilon, maxIterations);
    324            } else {
    325                // calculate series
    326                double n = 0.0; // current element index
    327                double an = 1.0 / a; // n-th element in the series
    328                double sum = an; // partial sum
    329                while (FastMath.abs(an/sum) > epsilon &&
    330                       n < maxIterations &&
    331                       sum < Double.POSITIVE_INFINITY) {
    332                    // compute next element in the series
    333                    n = n + 1.0;
    334                    an = an * (x / (a + n));
    335
    336                    // update partial sum
    337                    sum = sum + an;
    338                }
    339                if (n >= maxIterations) {
    340                    throw new MaxCountExceededException(maxIterations);
    341                } else if (Double.isInfinite(sum)) {
    342                    ret = 1.0;
    343                } else {
    344                    ret = FastMath.exp(-x + (a * FastMath.log(x)) - logGamma(a)) * sum;
    345                }
    346            }
    347
    348            return ret;
    349        }
    350
    351        /**
    352         * Returns the regularized gamma function Q(a, x) = 1 - P(a, x).
    353         *
    354         * @param a the a parameter.
    355         * @param x the value.
    356         * @return the regularized gamma function Q(a, x)
    357         * @throws MaxCountExceededException if the algorithm fails to converge.
    358         */
    359        public static double regularizedGammaQ(double a, double x) {
    360            return regularizedGammaQ(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE);
    361        }
    362
    363        /**
    364         * Returns the regularized gamma function Q(a, x) = 1 - P(a, x).
    365         *
    366         * The implementation of this method is based on:
    367         * <ul>
    368         *  <li>
    369         *   <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html">
    370         *   Regularized Gamma Function</a>, equation (1).
    371         *  </li>
    372         *  <li>
    373         *   <a href="http://functions.wolfram.com/GammaBetaErf/GammaRegularized/10/0003/">
    374         *   Regularized incomplete gamma function: Continued fraction representations
    375         *   (formula 06.08.10.0003)</a>
    376         *  </li>
    377         * </ul>
    378         *
    379         * @param a the a parameter.
    380         * @param x the value.
    381         * @param epsilon When the absolute value of the nth item in the
    382         * series is less than epsilon the approximation ceases to calculate
    383         * further elements in the series.
    384         * @param maxIterations Maximum number of "iterations" to complete.
    385         * @return the regularized gamma function P(a, x)
    386         * @throws MaxCountExceededException if the algorithm fails to converge.
    387         */
    388        public static double regularizedGammaQ(final double a,
    389                                               double x,
    390                                               double epsilon,
    391                                               int maxIterations) {
    392            double ret;
    393
    394            if (Double.isNaN(a) || Double.isNaN(x) || (a <= 0.0) || (x < 0.0)) {
    395                ret = Double.NaN;
    396            } else if (x == 0.0) {
    397                ret = 1.0;
    398            } else if (x < a + 1.0) {
    399                // use regularizedGammaP because it should converge faster in this
    400                // case.
    401                ret = 1.0 - regularizedGammaP(a, x, epsilon, maxIterations);
    402            } else {
    403                // create continued fraction
    404                ContinuedFraction cf = new ContinuedFraction() {
    405
    406                    @Override
    407                    protected double getA(int n, double x) {
    408                        return ((2.0 * n) + 1.0) - a + x;
    409                    }
    410
    411                    @Override
    412                    protected double getB(int n, double x) {
    413                        return n * (a - n);
    414                    }
    415                };
    416
    417                ret = 1.0 / cf.evaluate(x, epsilon, maxIterations);
    418                ret = FastMath.exp(-x + (a * FastMath.log(x)) - logGamma(a)) * ret;
    419            }
    420
    421            return ret;
    422        }
    423
    424
    425        /**
    426         * <p>Computes the digamma function of x.</p>
    427         *
    428         * <p>This is an independently written implementation of the algorithm described in
    429         * Jose Bernardo, Algorithm AS 103: Psi (Digamma) Function, Applied Statistics, 1976.</p>
    430         *
    431         * <p>Some of the constants have been changed to increase accuracy at the moderate expense
    432         * of run-time.  The result should be accurate to within 10^-8 absolute tolerance for
    433         * x >= 10^-5 and within 10^-8 relative tolerance for x > 0.</p>
    434         *
    435         * <p>Performance for large negative values of x will be quite expensive (proportional to
    436         * |x|).  Accuracy for negative values of x should be about 10^-8 absolute for results
    437         * less than 10^5 and 10^-8 relative for results larger than that.</p>
    438         *
    439         * @param x Argument.
    440         * @return digamma(x) to within 10-8 relative or absolute error whichever is smaller.
    441         * @see <a href="http://en.wikipedia.org/wiki/Digamma_function">Digamma</a>
    442         * @see <a href="http://www.uv.es/~bernardo/1976AppStatist.pdf">Bernardo&apos;s original article </a>
    443         * @since 2.0
    444         */
    445        public static double digamma(double x) {
    446            if (x > 0 && x <= S_LIMIT) {
    447                // use method 5 from Bernardo AS103
    448                // accurate to O(x)
    449                return -GAMMA - 1 / x;
    450            }
    451
    452            if (x >= C_LIMIT) {
    453                // use method 4 (accurate to O(1/x^8)
    454                double inv = 1 / (x * x);
    455                //            1       1        1         1
    456                // log(x) -  --- - ------ + ------- - -------
    457                //           2 x   12 x^2   120 x^4   252 x^6
    458                return FastMath.log(x) - 0.5 / x - inv * ((1.0 / 12) + inv * (1.0 / 120 - inv / 252));
    459            }
    460
    461            return digamma(x + 1) - 1 / x;
    462        }
    463
    464        /**
    465         * Computes the trigamma function of x.
    466         * This function is derived by taking the derivative of the implementation
    467         * of digamma.
    468         *
    469         * @param x Argument.
    470         * @return trigamma(x) to within 10-8 relative or absolute error whichever is smaller
    471         * @see <a href="http://en.wikipedia.org/wiki/Trigamma_function">Trigamma</a>
    472         * @see Gamma#digamma(double)
    473         * @since 2.0
    474         */
    475        public static double trigamma(double x) {
    476            if (x > 0 && x <= S_LIMIT) {
    477                return 1 / (x * x);
    478            }
    479
    480            if (x >= C_LIMIT) {
    481                double inv = 1 / (x * x);
    482                //  1    1      1       1       1
    483                //  - + ---- + ---- - ----- + -----
    484                //  x      2      3       5       7
    485                //      2 x    6 x    30 x    42 x
    486                return 1 / x + inv / 2 + inv / x * (1.0 / 6 - inv * (1.0 / 30 + inv / 42));
    487            }
    488
    489            return trigamma(x + 1) + 1 / (x * x);
    490        }
    491
    492        /**
    493         * <p>
    494         * Returns the Lanczos approximation used to compute the gamma function.
    495         * The Lanczos approximation is related to the Gamma function by the
    496         * following equation
    497         * <center>
    498         * {@code gamma(x) = sqrt(2 * pi) / x * (x + g + 0.5) ^ (x + 0.5)
    499         *                   * exp(-x - g - 0.5) * lanczos(x)},
    500         * </center>
    501         * where {@code g} is the Lanczos constant.
    502         * </p>
    503         *
    504         * @param x Argument.
    505         * @return The Lanczos approximation.
    506         * @see <a href="http://mathworld.wolfram.com/LanczosApproximation.html">Lanczos Approximation</a>
    507         * equations (1) through (5), and Paul Godfrey's
    508         * <a href="http://my.fit.edu/~gabdo/gamma.txt">Note on the computation
    509         * of the convergent Lanczos complex Gamma approximation</a>
    510         * @since 3.1
    511         */
    512        public static double lanczos(final double x) {
    513            double sum = 0.0;
    514            for (int i = LANCZOS.length - 1; i > 0; --i) {
    515                sum = sum + (LANCZOS[i] / (x + i));
    516            }
    517            return sum + LANCZOS[0];
    518        }
    519
    520        /**
    521         * Returns the value of 1 / &Gamma;(1 + x) - 1 for -0&#46;5 &le; x &le;
    522         * 1&#46;5. This implementation is based on the double precision
    523         * implementation in the <em>NSWC Library of Mathematics Subroutines</em>,
    524         * {@code DGAM1}.
    525         *
    526         * @param x Argument.
    527         * @return The value of {@code 1.0 / Gamma(1.0 + x) - 1.0}.
    528         * @throws NumberIsTooSmallException if {@code x < -0.5}
    529         * @throws NumberIsTooLargeException if {@code x > 1.5}
    530         * @since 3.1
    531         */
    532        public static double invGamma1pm1(final double x) {
    533
    534            if (x < -0.5) {
    535                throw new NumberIsTooSmallException(x, -0.5, true);
    536            }
    537            if (x > 1.5) {
    538                throw new NumberIsTooLargeException(x, 1.5, true);
    539            }
    540
    541            final double ret;
    542            final double t = x <= 0.5 ? x : (x - 0.5) - 0.5;
    543            if (t < 0.0) {
    544                final double a = INV_GAMMA1P_M1_A0 + t * INV_GAMMA1P_M1_A1;
    545                double b = INV_GAMMA1P_M1_B8;
    546                b = INV_GAMMA1P_M1_B7 + t * b;
    547                b = INV_GAMMA1P_M1_B6 + t * b;
    548                b = INV_GAMMA1P_M1_B5 + t * b;
    549                b = INV_GAMMA1P_M1_B4 + t * b;
    550                b = INV_GAMMA1P_M1_B3 + t * b;
    551                b = INV_GAMMA1P_M1_B2 + t * b;
    552                b = INV_GAMMA1P_M1_B1 + t * b;
    553                b = 1.0 + t * b;
    554
    555                double c = INV_GAMMA1P_M1_C13 + t * (a / b);
    556                c = INV_GAMMA1P_M1_C12 + t * c;
    557                c = INV_GAMMA1P_M1_C11 + t * c;
    558                c = INV_GAMMA1P_M1_C10 + t * c;
    559                c = INV_GAMMA1P_M1_C9 + t * c;
    560                c = INV_GAMMA1P_M1_C8 + t * c;
    561                c = INV_GAMMA1P_M1_C7 + t * c;
    562                c = INV_GAMMA1P_M1_C6 + t * c;
    563                c = INV_GAMMA1P_M1_C5 + t * c;
    564                c = INV_GAMMA1P_M1_C4 + t * c;
    565                c = INV_GAMMA1P_M1_C3 + t * c;
    566                c = INV_GAMMA1P_M1_C2 + t * c;
    567                c = INV_GAMMA1P_M1_C1 + t * c;
    568                c = INV_GAMMA1P_M1_C + t * c;
    569                if (x > 0.5) {
    570                    ret = t * c / x;
    571                } else {
    572                    ret = x * ((c + 0.5) + 0.5);
    573                }
    574            } else {
    575                double p = INV_GAMMA1P_M1_P6;
    576                p = INV_GAMMA1P_M1_P5 + t * p;
    577                p = INV_GAMMA1P_M1_P4 + t * p;
    578                p = INV_GAMMA1P_M1_P3 + t * p;
    579                p = INV_GAMMA1P_M1_P2 + t * p;
    580                p = INV_GAMMA1P_M1_P1 + t * p;
    581                p = INV_GAMMA1P_M1_P0 + t * p;
    582
    583                double q = INV_GAMMA1P_M1_Q4;
    584                q = INV_GAMMA1P_M1_Q3 + t * q;
    585                q = INV_GAMMA1P_M1_Q2 + t * q;
    586                q = INV_GAMMA1P_M1_Q1 + t * q;
    587                q = 1.0 + t * q;
    588
    589                double c = INV_GAMMA1P_M1_C13 + (p / q) * t;
    590                c = INV_GAMMA1P_M1_C12 + t * c;
    591                c = INV_GAMMA1P_M1_C11 + t * c;
    592                c = INV_GAMMA1P_M1_C10 + t * c;
    593                c = INV_GAMMA1P_M1_C9 + t * c;
    594                c = INV_GAMMA1P_M1_C8 + t * c;
    595                c = INV_GAMMA1P_M1_C7 + t * c;
    596                c = INV_GAMMA1P_M1_C6 + t * c;
    597                c = INV_GAMMA1P_M1_C5 + t * c;
    598                c = INV_GAMMA1P_M1_C4 + t * c;
    599                c = INV_GAMMA1P_M1_C3 + t * c;
    600                c = INV_GAMMA1P_M1_C2 + t * c;
    601                c = INV_GAMMA1P_M1_C1 + t * c;
    602                c = INV_GAMMA1P_M1_C0 + t * c;
    603
    604                if (x > 0.5) {
    605                    ret = (t / x) * ((c - 0.5) - 0.5);
    606                } else {
    607                    ret = x * c;
    608                }
    609            }
    610
    611            return ret;
    612        }
    613
    614        /**
    615         * Returns the value of log &Gamma;(1 + x) for -0&#46;5 &le; x &le; 1&#46;5.
    616         * This implementation is based on the double precision implementation in
    617         * the <em>NSWC Library of Mathematics Subroutines</em>, {@code DGMLN1}.
    618         *
    619         * @param x Argument.
    620         * @return The value of {@code log(Gamma(1 + x))}.
    621         * @throws NumberIsTooSmallException if {@code x < -0.5}.
    622         * @throws NumberIsTooLargeException if {@code x > 1.5}.
    623         * @since 3.1
    624         */
    625        public static double logGamma1p(final double x)
    626            throws NumberIsTooSmallException, NumberIsTooLargeException {
    627
    628            if (x < -0.5) {
    629                throw new NumberIsTooSmallException(x, -0.5, true);
    630            }
    631            if (x > 1.5) {
    632                throw new NumberIsTooLargeException(x, 1.5, true);
    633            }
    634
    635            return -FastMath.log1p(invGamma1pm1(x));
    636        }
    637
    638
    639        /**
    640         * Returns the value of Γ(x). Based on the <em>NSWC Library of
    641         * Mathematics Subroutines</em> double precision implementation,
    642         * {@code DGAMMA}.
    643         *
    644         * @param x Argument.
    645         * @return the value of {@code Gamma(x)}.
    646         * @since 3.1
    647         */
    648        public static double gamma(final double x) {
    649
    650            if ((x == FastMath.rint(x)) && (x <= 0.0)) {
    651                return Double.NaN;
    652            }
    653
    654            final double ret;
    655            final double absX = FastMath.abs(x);
    656            if (absX <= 20.0) {
    657                if (x >= 1.0) {
    658                    /*
    659                     * From the recurrence relation
    660                     * Gamma(x) = (x - 1) * ... * (x - n) * Gamma(x - n),
    661                     * then
    662                     * Gamma(t) = 1 / [1 + invGamma1pm1(t - 1)],
    663                     * where t = x - n. This means that t must satisfy
    664                     * -0.5 <= t - 1 <= 1.5.
    665                     */
    666                    double prod = 1.0;
    667                    double t = x;
    668                    while (t > 2.5) {
    669                        t = t - 1.0;
    670                        prod *= t;
    671                    }
    672                    ret = prod / (1.0 + invGamma1pm1(t - 1.0));
    673                } else {
    674                    /*
    675                     * From the recurrence relation
    676                     * Gamma(x) = Gamma(x + n + 1) / [x * (x + 1) * ... * (x + n)]
    677                     * then
    678                     * Gamma(x + n + 1) = 1 / [1 + invGamma1pm1(x + n)],
    679                     * which requires -0.5 <= x + n <= 1.5.
    680                     */
    681                    double prod = x;
    682                    double t = x;
    683                    while (t < -0.5) {
    684                        t = t + 1.0;
    685                        prod *= t;
    686                    }
    687                    ret = 1.0 / (prod * (1.0 + invGamma1pm1(t)));
    688                }
    689            } else {
    690                final double y = absX + LANCZOS_G + 0.5;
    691                final double gammaAbs = SQRT_TWO_PI / x *
    692                                        FastMath.pow(y, absX + 0.5) *
    693                                        FastMath.exp(-y) * lanczos(absX);
    694                if (x > 0.0) {
    695                    ret = gammaAbs;
    696                } else {
    697                    /*
    698                     * From the reflection formula
    699                     * Gamma(x) * Gamma(1 - x) * sin(pi * x) = pi,
    700                     * and the recurrence relation
    701                     * Gamma(1 - x) = -x * Gamma(-x),
    702                     * it is found
    703                     * Gamma(x) = -pi / [x * sin(pi * x) * Gamma(-x)].
    704                     */
    705                    ret = -FastMath.PI /
    706                          (x * FastMath.sin(FastMath.PI * x) * gammaAbs);
    707                }
    708            }
    709            return ret;
    710        }
    711    }