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 */
017package org.apache.commons.numbers.gamma;
018
019/**
020 * <a href="http://en.wikipedia.org/wiki/Digamma_function">Digamma function</a>.
021 * <p>
022 * It is defined as the logarithmic derivative of the \( \Gamma \)
023 * ({@link Gamma}) function:
024 * \( \frac{d}{dx}(\ln \Gamma(x)) = \frac{\Gamma^\prime(x)}{\Gamma(x)} \).
025 * </p>
026 *
027 * @see Gamma
028 */
029public final class Digamma {
030    /** <a href="http://en.wikipedia.org/wiki/Euler-Mascheroni_constant">Euler-Mascheroni constant</a>. */
031    private static final double GAMMA = 0.577215664901532860606512090082;
032
033    /** C limit. */
034    private static final double C_LIMIT = 49;
035    /** S limit. */
036    private static final double S_LIMIT = 1e-5;
037    /** Fraction. */
038    private static final double F_M1_12 = -1d / 12;
039    /** Fraction. */
040    private static final double F_1_120 = 1d / 120;
041    /** Fraction. */
042    private static final double F_M1_252 = -1d / 252;
043
044    /** Private constructor. */
045    private Digamma() {
046        // intentionally empty.
047    }
048
049    /**
050     * Computes the digamma function.
051     *
052     * This is an independently written implementation of the algorithm described in
053     * <a href="http://www.uv.es/~bernardo/1976AppStatist.pdf">Jose Bernardo,
054     * Algorithm AS 103: Psi (Digamma) Function, Applied Statistics, 1976</a>.
055     * A <a href="https://en.wikipedia.org/wiki/Digamma_function#Reflection_formula">
056     * reflection formula</a> is incorporated to improve performance on negative values.
057     *
058     * Some of the constants have been changed to increase accuracy at the moderate
059     * expense of run-time.  The result should be accurate to within {@code 1e-8}.
060     * relative tolerance for {@code 0 < x < 1e-5}  and within {@code 1e-8} absolute
061     * tolerance otherwise.
062     *
063     * @param x Argument.
064     * @return digamma(x) to within {@code 1e-8} relative or absolute error whichever
065     * is larger.
066     */
067    public static double value(double x) {
068        if (!Double.isFinite(x)) {
069            return x;
070        }
071
072        double digamma = 0;
073        if (x < 0) {
074            // Use reflection formula to fall back into positive values.
075            digamma -= Math.PI / Math.tan(Math.PI * x);
076            x = 1 - x;
077        }
078
079        if (x > 0 && x <= S_LIMIT) {
080            // Use method 5 from Bernardo AS103, accurate to O(x).
081            return digamma - GAMMA - 1 / x;
082        }
083
084        while (x < C_LIMIT) {
085            digamma -= 1 / x;
086            x += 1;
087        }
088
089        // Use method 4, accurate to O(1/x^8)
090        final double inv = 1 / (x * x);
091        //            1       1        1         1
092        // log(x) -  --- - ------ + ------- - -------
093        //           2 x   12 x^2   120 x^4   252 x^6
094        digamma += Math.log(x) - 0.5 / x + inv * (F_M1_12 + inv * (F_1_120 + F_M1_252 * inv));
095
096        return digamma;
097    }
098}