Trigamma.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.numbers.gamma;

  18. /**
  19.  * <a href="http://en.wikipedia.org/wiki/Trigamma_function">Trigamma function</a>.
  20.  *
  21.  * It is the derivative of the {@link Digamma digamma function}:
  22.  * \( \psi_1(x) = \frac{d^2}{dx^2} (\ln \Gamma(x)) \).
  23.  */
  24. public final class Trigamma {
  25.     /** C limit. */
  26.     private static final double C_LIMIT = 49;

  27.     /** S limit. */
  28.     private static final double S_LIMIT = 1e-5;
  29.     /** Fraction. */
  30.     private static final double F_1_6 = 1d / 6;
  31.     /** Fraction. */
  32.     private static final double F_1_30 = 1d / 30;
  33.     /** Fraction. */
  34.     private static final double F_1_42 = 1d / 42;

  35.     /** Private constructor. */
  36.     private Trigamma() {
  37.         // intentionally empty.
  38.     }

  39.     /**
  40.      * Computes the trigamma function.
  41.      *
  42.      * @param x Argument.
  43.      * @return trigamma(x) to within {@code 1e-8} relative or absolute error whichever is larger.
  44.      */
  45.     public static double value(double x) {
  46.         if (!Double.isFinite(x)) {
  47.             return x;
  48.         }

  49.         if (x > 0 && x <= S_LIMIT) {
  50.             return 1 / (x * x);
  51.         }

  52.         double trigamma = 0;
  53.         while (x < C_LIMIT) {
  54.             trigamma += 1 / (x * x);
  55.             x += 1;
  56.         }

  57.         final double inv = 1 / (x * x);
  58.         //  1    1      1       1       1
  59.         //  - + ---- + ---- - ----- + -----
  60.         //  x      2      3       5       7
  61.         //      2 x    6 x    30 x    42 x
  62.         trigamma += 1 / x + inv / 2 + inv / x * (F_1_6 - inv * (F_1_30 + F_1_42 * inv));

  63.         return trigamma;
  64.     }
  65. }