NUMBERS-33: "Gamma" family of functions (port from "Commons Math").
Code in module "commons-numbers-gamma" is a refactoring of the utilities contained in the "o.a.c.math4.special.Gamma" class. Project: http://git-wip-us.apache.org/repos/asf/commons-numbers/repo Commit: http://git-wip-us.apache.org/repos/asf/commons-numbers/commit/0c9f1cde Tree: http://git-wip-us.apache.org/repos/asf/commons-numbers/tree/0c9f1cde Diff: http://git-wip-us.apache.org/repos/asf/commons-numbers/diff/0c9f1cde Branch: refs/heads/master Commit: 0c9f1cde2f639d537306e8cbe6d8dd54d0374720 Parents: 3540a23 Author: Gilles Sadowski <gil...@harfang.homelinux.org> Authored: Mon May 8 01:48:52 2017 +0200 Committer: Gilles Sadowski <gil...@harfang.homelinux.org> Committed: Mon May 8 01:48:52 2017 +0200 ---------------------------------------------------------------------- commons-numbers-gamma/LICENSE.txt | 201 +++++++ commons-numbers-gamma/NOTICE.txt | 6 + commons-numbers-gamma/README.md | 98 ++++ commons-numbers-gamma/pom.xml | 69 +++ .../apache/commons/numbers/gamma/Digamma.java | 90 +++ .../org/apache/commons/numbers/gamma/Gamma.java | 107 ++++ .../commons/numbers/gamma/GammaException.java | 52 ++ .../commons/numbers/gamma/InvGamma1pm1.java | 187 +++++++ .../numbers/gamma/LanczosApproximation.java | 69 +++ .../apache/commons/numbers/gamma/LogGamma.java | 77 +++ .../commons/numbers/gamma/LogGamma1p.java | 47 ++ .../commons/numbers/gamma/RegularizedGamma.java | 214 +++++++ .../apache/commons/numbers/gamma/Trigamma.java | 66 +++ .../commons/numbers/gamma/package-info.java | 39 ++ commons-numbers-gamma/src/site/site.xml | 35 ++ commons-numbers-gamma/src/site/xdoc/index.xml | 40 ++ .../commons/numbers/gamma/DigammaTest.java | 72 +++ .../apache/commons/numbers/gamma/GammaTest.java | 557 +++++++++++++++++++ .../commons/numbers/gamma/InvGamma1pm1Test.java | 91 +++ .../commons/numbers/gamma/LogGamma1pTest.java | 70 +++ .../commons/numbers/gamma/LogGammaTest.java | 232 ++++++++ .../numbers/gamma/RegularizedGammaTest.java | 67 +++ .../commons/numbers/gamma/TrigammaTest.java | 59 ++ pom.xml | 2 +- 24 files changed, 2546 insertions(+), 1 deletion(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/LICENSE.txt ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/LICENSE.txt b/commons-numbers-gamma/LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/commons-numbers-gamma/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/NOTICE.txt ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/NOTICE.txt b/commons-numbers-gamma/NOTICE.txt new file mode 100644 index 0000000..9091baa --- /dev/null +++ b/commons-numbers-gamma/NOTICE.txt @@ -0,0 +1,6 @@ +Apache Commons Numbers +Copyright 2001-2017 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/README.md ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/README.md b/commons-numbers-gamma/README.md new file mode 100644 index 0000000..0701bed --- /dev/null +++ b/commons-numbers-gamma/README.md @@ -0,0 +1,98 @@ +<!--- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!--- + +======================================================================+ + |**** ****| + |**** THIS FILE IS GENERATED BY THE COMMONS BUILD PLUGIN ****| + |**** DO NOT EDIT DIRECTLY ****| + |**** ****| + +======================================================================+ + | TEMPLATE FILE: readme-md-template.md | + | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates | + +======================================================================+ + | | + | 1) Re-generate using: mvn commons:readme-md | + | | + | 2) Set the following properties in the component's pom: | + | - commons.componentid (required, alphabetic, lower case) | + | - commons.release.version (required) | + | | + | 3) Example Properties | + | | + | <properties> | + | <commons.componentid>math</commons.componentid> | + | <commons.release.version>1.2</commons.release.version> | + | </properties> | + | | + +======================================================================+ +---> +Apache Commons Numbers Core +=================== + +Basic utilities. + +Documentation +------------- + +More information can be found on the [homepage](https://commons.apache.org/proper/commons-numbers). +The [JavaDoc](https://commons.apache.org/proper/commons-numbers/javadocs/api-release) can be browsed. +Questions related to the usage of Apache Commons Numbers Core should be posted to the [user mailing list][ml]. + +Where can I get the latest release? +----------------------------------- +You can download source and binaries from our [download page](https://commons.apache.org/proper/commons-numbers/download_numbers.cgi). + +Alternatively you can pull it from the central Maven repositories: + +```xml +<dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-numbers-core</artifactId> + <version>1.0</version> +</dependency> +``` + +Contributing +------------ + +We accept PRs via github. The [developer mailing list][ml] is the main channel of communication for contributors. +There are some guidelines which will make applying PRs easier for us: ++ No tabs! Please use spaces for indentation. ++ Respect the code style. ++ Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. ++ Provide JUnit tests for your changes and make sure your changes don't break any existing tests by running ```mvn clean test```. + +If you plan to contribute on a regular basis, please consider filing a [contributor license agreement](https://www.apache.org/licenses/#clas). +You can learn more about contributing via GitHub in our [contribution guidelines](CONTRIBUTING.md). + +License +------- +Code is under the [Apache Licence v2](https://www.apache.org/licenses/LICENSE-2.0.txt). + +Donations +--------- +You like Apache Commons Numbers Core? Then [donate back to the ASF](https://www.apache.org/foundation/contributing.html) to support the development. + +Additional Resources +-------------------- + ++ [Apache Commons Homepage](https://commons.apache.org/) ++ [Apache Bugtracker (JIRA)](https://issues.apache.org/jira/) ++ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons) ++ #apachecommons IRC channel on freenode.org + +[ml]:https://commons.apache.org/mail-lists.html http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/pom.xml ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/pom.xml b/commons-numbers-gamma/pom.xml new file mode 100644 index 0000000..af530fe --- /dev/null +++ b/commons-numbers-gamma/pom.xml @@ -0,0 +1,69 @@ +<?xml version="1.0"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.commons</groupId> + <artifactId>commons-numbers-parent</artifactId> + <version>1.0-SNAPSHOT</version> + </parent> + + <groupId>org.apache.commons</groupId> + <artifactId>commons-numbers-gamma</artifactId> + <version>1.0-SNAPSHOT</version> + <name>Apache Commons Numbers Gamma</name> + + <description>Gamma family of functions.</description> + + <properties> + <!-- This value must reflect the current name of the base package. --> + <commons.osgi.symbolicName>org.apache.commons.numbers.gamma</commons.osgi.symbolicName> + <!-- OSGi --> + <commons.osgi.export>org.apache.commons.numbers.gamma</commons.osgi.export> + <!-- Workaround to avoid duplicating config files. --> + <numbers.parent.dir>${basedir}/..</numbers.parent.dir> + </properties> + + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jar-plugin</artifactId> + <executions> + <execution> + <goals> + <goal>test-jar</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + + <dependencies> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-numbers-fraction</artifactId> + <version>1.0-SNAPSHOT</version> + </dependency> + </dependencies> + +</project> http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Digamma.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Digamma.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Digamma.java new file mode 100644 index 0000000..8b096d5 --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Digamma.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +/** + * <a href="http://en.wikipedia.org/wiki/Digamma_function">Digamma function</a>. + * + * It is defined as the logarithmic derivative of the \( \Gamma \) function: + * \( \frac{d}{dx}(\ln \Gamma(x)) = \frac{\Gamma^\prime(x)}{\Gamma(x)} \). + */ +public class Digamma { + /** <a href="http://en.wikipedia.org/wiki/Euler-Mascheroni_constant">Euler-Mascheroni constant</a>. */ + private static final double GAMMA = 0.577215664901532860606512090082; + /** C limit. */ + private static final double C_LIMIT = 49; + /** S limit. */ + private static final double S_LIMIT = 1e-5; + /** Fraction. */ + private static final double F_1_12 = 1d / 12; + /** Fraction. */ + private static final double F_1_120 = 1d / 120; + /** Fraction. */ + private static final double F_1_252 = 1d / 252; + + /** Class only contains a static method. */ + private Digamma() {} + + /** + * Computes the digamma function. + * + * This is an independently written implementation of the algorithm described in + * <a href="http://www.uv.es/~bernardo/1976AppStatist.pdf">Jose Bernardo, + * Algorithm AS 103: Psi (Digamma) Function, Applied Statistics, 1976</a>. + * A <a href="https://en.wikipedia.org/wiki/Digamma_function#Reflection_formula"> + * reflection formula</a> is incorporated to improve performance on negative values. + * + * Some of the constants have been changed to increase accuracy at the moderate + * expense of run-time. The result should be accurate to within \( 10^{-8} \) + * relative tolerance for \( 0 < x < 10^{-5} \) and within \( 10^{-8} \) absolute + * tolerance otherwise. + * + * @param x Argument. + * @return digamma(x) to within \( 10^{-8} \) relative or absolute error whichever is larger. + */ + public static double value(double x) { + if (Double.isNaN(x) || Double.isInfinite(x)) { + return x; + } + + double digamma = 0; + if (x < 0) { + // Use reflection formula to fall back into positive values. + digamma -= Math.PI / Math.tan(Math.PI * x); + x = 1 - x; + } + + if (x > 0 && x <= S_LIMIT) { + // Use method 5 from Bernardo AS103, accurate to O(x). + return digamma - GAMMA - 1 / x; + } + + while (x < C_LIMIT) { + digamma -= 1 / x; + x += 1; + } + + // Use method 4, accurate to O(1/x^8) + final double inv = 1 / (x * x); + // 1 1 1 1 + // log(x) - --- - ------ + ------- - ------- + // 2 x 12 x^2 120 x^4 252 x^6 + digamma += Math.log(x) - 0.5 / x - inv * (F_1_12 + inv * (F_1_120 - F_1_252 * inv)); + + return digamma; + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Gamma.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Gamma.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Gamma.java new file mode 100644 index 0000000..797c93a --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Gamma.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + + +/** + * <a href="http://mathworld.wolfram.com/GammaFunction.html">Gamma function</a>. + * + * Class is immutable. + */ +public class Gamma { + /** \( g = \frac{607}{128} \). */ + private static final double LANCZOS_G = 607d / 128d; + /** Helper. */ + private static final LanczosApproximation LANCZOS_APPROXIMATION = LanczosApproximation.instance; + /** Helper. */ + private static final InvGamma1pm1 INV_GAMMA_1P_M1 = InvGamma1pm1.instance; + /** √(2π). */ + private static final double SQRT_TWO_PI = 2.506628274631000502; + + /** + * Computes the value of \( \Gamma(x) \). + * + * Based on the <em>NSWC Library of Mathematics Subroutines</em> double + * precision implementation, {@code DGAMMA}. + * + * @param x Argument. + * @return \( \Gamma(x) \) + */ + public double value(final double x) { + + if ((x == Math.rint(x)) && (x <= 0.0)) { + return Double.NaN; + } + + final double ret; + final double absX = Math.abs(x); + if (absX <= 20) { + if (x >= 1) { + /* + * From the recurrence relation + * Gamma(x) = (x - 1) * ... * (x - n) * Gamma(x - n), + * then + * Gamma(t) = 1 / [1 + InvGamma1pm1.value(t - 1)], + * where t = x - n. This means that t must satisfy + * -0.5 <= t - 1 <= 1.5. + */ + double prod = 1; + double t = x; + while (t > 2.5) { + t -= 1; + prod *= t; + } + ret = prod / (1 + INV_GAMMA_1P_M1.value(t - 1)); + } else { + /* + * From the recurrence relation + * Gamma(x) = Gamma(x + n + 1) / [x * (x + 1) * ... * (x + n)] + * then + * Gamma(x + n + 1) = 1 / [1 + InvGamma1pm1.value(x + n)], + * which requires -0.5 <= x + n <= 1.5. + */ + double prod = x; + double t = x; + while (t < -0.5) { + t += 1; + prod *= t; + } + ret = 1 / (prod * (1 + INV_GAMMA_1P_M1.value(t))); + } + } else { + final double y = absX + LANCZOS_G + 0.5; + final double gammaAbs = SQRT_TWO_PI / absX * + Math.pow(y, absX + 0.5) * + Math.exp(-y) * LANCZOS_APPROXIMATION.value(absX); + if (x > 0) { + ret = gammaAbs; + } else { + /* + * From the reflection formula + * Gamma(x) * Gamma(1 - x) * sin(pi * x) = pi, + * and the recurrence relation + * Gamma(1 - x) = -x * Gamma(-x), + * it is found + * Gamma(x) = -pi / [x * sin(pi * x) * Gamma(-x)]. + */ + ret = -Math.PI / (x * Math.sin(Math.PI * x) * gammaAbs); + } + } + + return ret; + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/GammaException.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/GammaException.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/GammaException.java new file mode 100644 index 0000000..7122f2e --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/GammaException.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +import java.text.MessageFormat; + +/** + * Package private exception class with constants for frequently used messages. + */ +class GammaException extends IllegalArgumentException { + /** Error message for "out of range" condition. */ + static final String OUT_OF_RANGE = "Number {0} is out of range [{1}, {2}]"; + /** Error message for convergence failure. */ + static final String CONVERGENCE = "Failed to converge within {0} iterations"; + + /** Serializable version identifier. */ + private static final long serialVersionUID = 20170505L; + + /** Arguments for formatting the message. */ + protected Object[] formatArguments; + + /** + * Create an exception where the message is constructed by applying + * the {@code format()} method from {@code java.text.MessageFormat}. + * + * @param message the exception message with replaceable parameters + * @param formatArguments the arguments for formatting the message + */ + GammaException(String message, Object... formatArguments) { + super(message); + this.formatArguments = formatArguments; + } + + @Override + public String getMessage() { + return MessageFormat.format(super.getMessage(), formatArguments); + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/InvGamma1pm1.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/InvGamma1pm1.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/InvGamma1pm1.java new file mode 100644 index 0000000..77203a0 --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/InvGamma1pm1.java @@ -0,0 +1,187 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +/** + * Function \( \frac{1}{\Gamma(1 + x)} - 1 \). + * + * Class is immutable. + */ +class InvGamma1pm1 { + /** Singleton. */ + static final InvGamma1pm1 instance = new InvGamma1pm1(); + /* + * Constants copied from DGAM1 in the NSWC library. + */ + /** The constant {@code A0} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_A0 = .611609510448141581788E-08; + /** The constant {@code A1} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_A1 = .624730830116465516210E-08; + /** The constant {@code B1} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_B1 = .203610414066806987300E+00; + /** The constant {@code B2} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_B2 = .266205348428949217746E-01; + /** The constant {@code B3} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_B3 = .493944979382446875238E-03; + /** The constant {@code B4} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_B4 = -.851419432440314906588E-05; + /** The constant {@code B5} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_B5 = -.643045481779353022248E-05; + /** The constant {@code B6} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_B6 = .992641840672773722196E-06; + /** The constant {@code B7} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_B7 = -.607761895722825260739E-07; + /** The constant {@code B8} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_B8 = .195755836614639731882E-09; + /** The constant {@code P0} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_P0 = .6116095104481415817861E-08; + /** The constant {@code P1} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_P1 = .6871674113067198736152E-08; + /** The constant {@code P2} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_P2 = .6820161668496170657918E-09; + /** The constant {@code P3} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_P3 = .4686843322948848031080E-10; + /** The constant {@code P4} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_P4 = .1572833027710446286995E-11; + /** The constant {@code P5} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_P5 = -.1249441572276366213222E-12; + /** The constant {@code P6} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_P6 = .4343529937408594255178E-14; + /** The constant {@code Q1} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_Q1 = .3056961078365221025009E+00; + /** The constant {@code Q2} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_Q2 = .5464213086042296536016E-01; + /** The constant {@code Q3} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_Q3 = .4956830093825887312020E-02; + /** The constant {@code Q4} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_Q4 = .2692369466186361192876E-03; + /** The constant {@code C} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C = -.422784335098467139393487909917598E+00; + /** The constant {@code C0} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C0 = .577215664901532860606512090082402E+00; + /** The constant {@code C1} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C1 = -.655878071520253881077019515145390E+00; + /** The constant {@code C2} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C2 = -.420026350340952355290039348754298E-01; + /** The constant {@code C3} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C3 = .166538611382291489501700795102105E+00; + /** The constant {@code C4} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C4 = -.421977345555443367482083012891874E-01; + /** The constant {@code C5} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C5 = -.962197152787697356211492167234820E-02; + /** The constant {@code C6} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C6 = .721894324666309954239501034044657E-02; + /** The constant {@code C7} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C7 = -.116516759185906511211397108401839E-02; + /** The constant {@code C8} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C8 = -.215241674114950972815729963053648E-03; + /** The constant {@code C9} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C9 = .128050282388116186153198626328164E-03; + /** The constant {@code C10} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C10 = -.201348547807882386556893914210218E-04; + /** The constant {@code C11} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C11 = -.125049348214267065734535947383309E-05; + /** The constant {@code C12} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C12 = .113302723198169588237412962033074E-05; + /** The constant {@code C13} defined in {@code DGAM1}. */ + private static final double INV_GAMMA1P_M1_C13 = -.205633841697760710345015413002057E-06; + + /** + * Computes the function \( \frac{1}{\Gamma(1 + x)} - 1 \) for \( -0.5 \leq x \leq 1.5 \). + * + * This implementation is based on the double precision implementation in + * the <em>NSWC Library of Mathematics Subroutines</em>, {@code DGAM1}. + * + * @param x Argument. + * @return \( \frac{1}{\Gamma(1 + x)} - 1 \) + * @throws IllegalArgumentException if {@code x < -0.5} or {@code x > 1.5} + */ + public double value(final double x) { + if (x < -0.5 || x > 1.5) { + throw new GammaException(GammaException.OUT_OF_RANGE, x, -0.5, 1.5); + } + + final double t = x <= 0.5 ? x : (x - 0.5) - 0.5; + if (t < 0) { + final double a = INV_GAMMA1P_M1_A0 + t * INV_GAMMA1P_M1_A1; + double b = INV_GAMMA1P_M1_B8; + b = INV_GAMMA1P_M1_B7 + t * b; + b = INV_GAMMA1P_M1_B6 + t * b; + b = INV_GAMMA1P_M1_B5 + t * b; + b = INV_GAMMA1P_M1_B4 + t * b; + b = INV_GAMMA1P_M1_B3 + t * b; + b = INV_GAMMA1P_M1_B2 + t * b; + b = INV_GAMMA1P_M1_B1 + t * b; + b = 1.0 + t * b; + + double c = INV_GAMMA1P_M1_C13 + t * (a / b); + c = INV_GAMMA1P_M1_C12 + t * c; + c = INV_GAMMA1P_M1_C11 + t * c; + c = INV_GAMMA1P_M1_C10 + t * c; + c = INV_GAMMA1P_M1_C9 + t * c; + c = INV_GAMMA1P_M1_C8 + t * c; + c = INV_GAMMA1P_M1_C7 + t * c; + c = INV_GAMMA1P_M1_C6 + t * c; + c = INV_GAMMA1P_M1_C5 + t * c; + c = INV_GAMMA1P_M1_C4 + t * c; + c = INV_GAMMA1P_M1_C3 + t * c; + c = INV_GAMMA1P_M1_C2 + t * c; + c = INV_GAMMA1P_M1_C1 + t * c; + c = INV_GAMMA1P_M1_C + t * c; + if (x > 0.5) { + return t * c / x; + } else { + return x * ((c + 0.5) + 0.5); + } + } else { + double p = INV_GAMMA1P_M1_P6; + p = INV_GAMMA1P_M1_P5 + t * p; + p = INV_GAMMA1P_M1_P4 + t * p; + p = INV_GAMMA1P_M1_P3 + t * p; + p = INV_GAMMA1P_M1_P2 + t * p; + p = INV_GAMMA1P_M1_P1 + t * p; + p = INV_GAMMA1P_M1_P0 + t * p; + + double q = INV_GAMMA1P_M1_Q4; + q = INV_GAMMA1P_M1_Q3 + t * q; + q = INV_GAMMA1P_M1_Q2 + t * q; + q = INV_GAMMA1P_M1_Q1 + t * q; + q = 1.0 + t * q; + + double c = INV_GAMMA1P_M1_C13 + (p / q) * t; + c = INV_GAMMA1P_M1_C12 + t * c; + c = INV_GAMMA1P_M1_C11 + t * c; + c = INV_GAMMA1P_M1_C10 + t * c; + c = INV_GAMMA1P_M1_C9 + t * c; + c = INV_GAMMA1P_M1_C8 + t * c; + c = INV_GAMMA1P_M1_C7 + t * c; + c = INV_GAMMA1P_M1_C6 + t * c; + c = INV_GAMMA1P_M1_C5 + t * c; + c = INV_GAMMA1P_M1_C4 + t * c; + c = INV_GAMMA1P_M1_C3 + t * c; + c = INV_GAMMA1P_M1_C2 + t * c; + c = INV_GAMMA1P_M1_C1 + t * c; + c = INV_GAMMA1P_M1_C0 + t * c; + + if (x > 0.5) { + return (t / x) * ((c - 0.5) - 0.5); + } else { + return x * c; + } + } + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LanczosApproximation.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LanczosApproximation.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LanczosApproximation.java new file mode 100644 index 0000000..e21bc54 --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LanczosApproximation.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +/** + * <a href="http://mathworld.wolfram.com/LanczosApproximation.html"> + * Lanczos approximation</a> to the Gamma function. + * + * It is related to the Gamma function by the following equation + * \[ + * \Gamma(x) = \sqrt{2\pi} \, \frac{(g + x + \frac{1}{2})^{x + \frac{1}{2}} \, e^{-(g + x + \frac{1}{2})} \, \mathrm{lanczos}(x)} + * {x} + * \] + * where \(g\) is the Lanczos constant. + * + * @see equations (1) through (5), and Paul Godfrey's + * <a href="http://my.fit.edu/~gabdo/gamma.txt">Note on the computation + * of the convergent Lanczos complex Gamma approximation</a>. + */ +class LanczosApproximation { + /** Singleton. */ + static final LanczosApproximation instance = new LanczosApproximation(); + /** Lanczos coefficients. */ + private static final double[] LANCZOS = { + 0.99999999999999709182, + 57.156235665862923517, + -59.597960355475491248, + 14.136097974741747174, + -0.49191381609762019978, + .33994649984811888699e-4, + .46523628927048575665e-4, + -.98374475304879564677e-4, + .15808870322491248884e-3, + -.21026444172410488319e-3, + .21743961811521264320e-3, + -.16431810653676389022e-3, + .84418223983852743293e-4, + -.26190838401581408670e-4, + .36899182659531622704e-5, + }; + + /** + * Computes the Lanczos approximation. + * + * @param x Argument. + * @return the Lanczos approximation. + */ + public double value(final double x) { + double sum = 0; + for (int i = LANCZOS.length - 1; i > 0; i--) { + sum += LANCZOS[i] / (x + i); + } + return sum + LANCZOS[0]; + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LogGamma.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LogGamma.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LogGamma.java new file mode 100644 index 0000000..57146a2 --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LogGamma.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +/** + * Function \( \ln \Gamma(x) \). + * + * Class is immutable. + */ +public class LogGamma { + /** Singleton. */ + static final LogGamma instance = new LogGamma(); + /** \( g = \frac{607}{128} \). */ + private static final double LANCZOS_G = 607d / 128d; + /** Performance. */ + private static final double HALF_LOG_2_PI = 0.5 * Math.log(2.0 * Math.PI); + /** Helper. */ + private static final LanczosApproximation LANCZOS_APPROXIMATION = LanczosApproximation.instance; + /** Helper. */ + private static final LogGamma1p LOG_GAMMA_1P = LogGamma1p.instance; + + /** + * Computes the function \( \ln \Gamma(x) \) for \( x > 0 \). + * + * For \( x \leq 8 \), the implementation is based on the double precision + * implementation in the <em>NSWC Library of Mathematics Subroutines</em>, + * {@code DGAMLN}. For \( x \geq 8 \), the implementation is based on + * + * <ul> + * <li><a href="http://mathworld.wolfram.com/GammaFunction.html">Gamma + * Function</a>, equation (28).</li> + * <li><a href="http://mathworld.wolfram.com/LanczosApproximation.html"> + * Lanczos Approximation</a>, equations (1) through (5).</li> + * <li><a href="http://my.fit.edu/~gabdo/gamma.txt">Paul Godfrey, A note on + * the computation of the convergent Lanczos complex Gamma + * approximation</a></li> + * </ul> + * + * @param x Argument. + * @return \( \ln \Gamma(x) \), or {@code NaN} if {@code x <= 0}. + */ + public double value(double x) { + if (Double.isNaN(x) || (x <= 0.0)) { + return Double.NaN; + } else if (x < 0.5) { + return LOG_GAMMA_1P.value(x) - Math.log(x); + } else if (x <= 2.5) { + return LOG_GAMMA_1P.value((x - 0.5) - 0.5); + } else if (x <= 8.0) { + final int n = (int) Math.floor(x - 1.5); + double prod = 1.0; + for (int i = 1; i <= n; i++) { + prod *= x - i; + } + return LOG_GAMMA_1P.value(x - (n + 1)) + Math.log(prod); + } else { + final double sum = LANCZOS_APPROXIMATION.value(x); + final double tmp = x + LANCZOS_G + .5; + return ((x + .5) * Math.log(tmp)) - tmp + + HALF_LOG_2_PI + Math.log(sum / x); + } + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LogGamma1p.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LogGamma1p.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LogGamma1p.java new file mode 100644 index 0000000..2f26fcc --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/LogGamma1p.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +/** + * Function \( \ln \Gamma(1 + x) \). + * + * Class is immutable. + */ +class LogGamma1p { + /** Singleton. */ + static final LogGamma1p instance = new LogGamma1p(); + /** Helper. */ + private static final InvGamma1pm1 invGamma1pm1 = InvGamma1pm1.instance; + + /** + * Computes the function \( \ln \Gamma(1 + x) \) for \( -0.5 \leq x \leq 1.5 \). + * + * This implementation is based on the double precision implementation in + * the <em>NSWC Library of Mathematics Subroutines</em>, {@code DGMLN1}. + * + * @param x Argument. + * @return \( \ln \Gamma(1 + x) \) + * @throws IllegalArgumentException if {@code x < -0.5} or {@code x > 1.5}. + */ + public double value(final double x) { + if (x < -0.5 || x > 1.5) { + throw new GammaException(GammaException.OUT_OF_RANGE, x, -0.5, 1.5); + } + + return -Math.log1p(invGamma1pm1.value(x)); + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java new file mode 100644 index 0000000..7f39690 --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/RegularizedGamma.java @@ -0,0 +1,214 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +import org.apache.commons.numbers.fraction.ContinuedFraction; + +/** + * <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html"> + * Regularized Gamma functions</a>. + * + * Class is immutable. + */ +public abstract class RegularizedGamma { + /** Helper. */ + private static final LogGamma LOG_GAMMA = LogGamma.instance; + /** Maximum allowed numerical error. */ + private static final double DEFAULT_EPSILON = 10e-15; // XXX + + /** + * @param a Parameter. + * @param x Argument. + * @param epsilon When the absolute value of the n-th element in the + * series is less than epsilon the approximation ceases to calculate + * further elements in the series. + * @param maxIterations Maximum number of iterations. + * @return the value of the function. + * @throws IllegalArgumentException if the algorithm fails to converge. + */ + public abstract double value(double a, + double x, + double epsilon, + int maxIterations); + + /** + * @param a Parameter. + * @param x Argument. + * @return the value of the function. + * @throws IllegalArgumentException if the algorithm fails to converge. + */ + public abstract double value(double a, + double x); + + /** + * \( P(a, x) \) <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html"> + * regularized Gamma function</a>. + * + * Class is immutable. + */ + public static class P { + /** + * Computes the regularized gamma function \( P(a, x) \). + * + * {@inheritDoc} + */ + public double value(double a, + double x) { + return value(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE); + } + + /** + * Computes the regularized gamma function \( P(a, x) \). + * + * The implementation of this method is based on: + * <ul> + * <li> + * <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html"> + * Regularized Gamma Function</a>, equation (1) + * </li> + * <li> + * <a href="http://mathworld.wolfram.com/IncompleteGammaFunction.html"> + * Incomplete Gamma Function</a>, equation (4). + * </li> + * <li> + * <a href="http://mathworld.wolfram.com/ConfluentHypergeometricFunctionoftheFirstKind.html"> + * Confluent Hypergeometric Function of the First Kind</a>, equation (1). + * </li> + * </ul> + * + * {@inheritDoc} + */ + public double value(double a, + double x, + double epsilon, + int maxIterations) { + double ret; + + if (Double.isNaN(a) || + Double.isNaN(x) || + a <= 0 || + x < 0) { + ret = Double.NaN; + } else if (x == 0) { + ret = 0; + } else if (x >= a + 1) { + // Q should converge faster in this case. + final RegularizedGamma.Q q = new RegularizedGamma.Q(); + ret = 1 - q.value(a, x, epsilon, maxIterations); + } else { + // Series. + double n = 0; // current element index + double an = 1 / a; // n-th element in the series + double sum = an; // partial sum + while (Math.abs(an / sum) > epsilon && + n < maxIterations && + sum < Double.POSITIVE_INFINITY) { + // compute next element in the series + n += 1; + an *= x / (a + n); + + // update partial sum + sum += an; + } + if (n >= maxIterations) { + throw new GammaException(GammaException.CONVERGENCE, maxIterations); + } else if (Double.isInfinite(sum)) { + ret = 1; + } else { + ret = Math.exp(-x + (a * Math.log(x)) - LOG_GAMMA.value(a)) * sum; + } + } + + return ret; + } + } + + /** + * Creates the \( Q(a, x) \equiv 1 - P(a, x) \) \) <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html"> + * regularized Gamma function</a>. + * + * Class is immutable. + */ + public static class Q { + /** + * Computes the regularized gamma function \( Q(a, x) = 1 - P(a, x) \). + * + * {@inheritDoc} + */ + public double value(double a, + double x) { + return value(a, x, DEFAULT_EPSILON, Integer.MAX_VALUE); + } + + /** + * Computes the regularized gamma function \( Q(a, x) = 1 - P(a, x) \). + * + * The implementation of this method is based on: + * <ul> + * <li> + * <a href="http://mathworld.wolfram.com/RegularizedGammaFunction.html"> + * Regularized Gamma Function</a>, equation (1). + * </li> + * <li> + * <a href="http://functions.wolfram.com/GammaBetaErf/GammaRegularized/10/0003/"> + * Regularized incomplete gamma function: Continued fraction representations + * (formula 06.08.10.0003)</a> + * </li> + * </ul> + * + * {@inheritDoc} + */ + public double value(final double a, + double x, + double epsilon, + int maxIterations) { + double ret; + + if (Double.isNaN(a) || + Double.isNaN(x) || + a <= 0 || + x < 0) { + ret = Double.NaN; + } else if (x == 0) { + ret = 1; + } else if (x < a + 1) { + // P should converge faster in this case. + final RegularizedGamma.P p = new RegularizedGamma.P(); + ret = 1 - p.value(a, x, epsilon, maxIterations); + } else { + final ContinuedFraction cf = new ContinuedFraction() { + /** {@inheritDoc} */ + @Override + protected double getA(int n, double x) { + return ((2 * n) + 1) - a + x; + } + + /** {@inheritDoc} */ + @Override + protected double getB(int n, double x) { + return n * (a - n); + } + }; + + ret = 1 / cf.evaluate(x, epsilon, maxIterations); + ret = Math.exp(-x + (a * Math.log(x)) - LOG_GAMMA.value(a)) * ret; + } + + return ret; + } + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Trigamma.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Trigamma.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Trigamma.java new file mode 100644 index 0000000..9e45601 --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/Trigamma.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +/** + * <a href="http://en.wikipedia.org/wiki/Trigamma_function">Trigamma function</a>. + * + * It is the derivative of the {@link Digamma digamma function}: + * \( \psi_1(x) = \frac{d^2}{dx^2} (\ln \Gamma(x)) \). + */ +public class Trigamma { + /** C limit. */ + private static final double C_LIMIT = 49; + /** S limit. */ + private static final double S_LIMIT = 1e-5; + /** Fraction. */ + private static final double F_1_6 = 1d / 6; + /** Fraction. */ + private static final double F_1_30 = 1d / 30; + /** Fraction. */ + private static final double F_1_42 = 1d / 42; + + /** Class only contains a static method. */ + private Trigamma() {} + + /** + * Computes the trigamma function. + * + * @param x Argument. + * @return trigamma(x) to within \( 10^{-8} \) relative or absolute error whichever is larger. + */ + public static double value(double x) { + if (Double.isNaN(x) || Double.isInfinite(x)) { + return x; + } + + if (x > 0 && x <= S_LIMIT) { + return 1 / (x * x); + } + + if (x >= C_LIMIT) { + final double inv = 1 / (x * x); + // 1 1 1 1 1 + // - + ---- + ---- - ----- + ----- + // x 2 3 5 7 + // 2 x 6 x 30 x 42 x + return 1 / x + inv / 2 + inv / x * (F_1_6 - inv * (F_1_30 + F_1_42 * inv)); + } + + return value(x + 1) + 1 / (x * x); + } +} http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/package-info.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/package-info.java b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/package-info.java new file mode 100644 index 0000000..b44caa1 --- /dev/null +++ b/commons-numbers-gamma/src/main/java/org/apache/commons/numbers/gamma/package-info.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Γ (Gamma) family of functions. + * + * Implementation of {@link org.apache.commons.numbers.gamma.InvGamma1pm1 InvGamma1pm1} + * and {@link org.apache.commons.numbers.gamma.LogGamma1p LogGamma1p} is based on the + * algorithms described in + * <ul> + * <li> + * <a href="http://dx.doi.org/10.1145/22721.23109">Didonato and Morris (1986)</a>, + * <em>Computation of the Incomplete Gamma Function Ratios and their Inverse</em>, + * TOMS 12(4), 377-393, + * </li> + * <li> + * <a href="http://dx.doi.org/10.1145/131766.131776">Didonato and Morris (1992)</a>, + * <em>Algorithm 708: Significant Digit Computation of the Incomplete Beta Function + * Ratios</em>, TOMS 18(3), 360-373, + * </li> + * </ul> + * and implemented in the + * <a href="http://www.dtic.mil/docs/citations/ADA476840">NSWC Library of Mathematical Functions</a>. + */ +package org.apache.commons.numbers.gamma; http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/site/site.xml ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/site/site.xml b/commons-numbers-gamma/src/site/site.xml new file mode 100644 index 0000000..ba0a795 --- /dev/null +++ b/commons-numbers-gamma/src/site/site.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="ISO-8859-1"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project name="Numbers"> + <bannerRight> + <name>Apache Commons Numbers</name> + <src>/images/commons_numbers.small.png</src> + <href>/index.html</href> + </bannerRight> + + <body> + <menu name="Numbers Gamma"> + <item name="Overview" href="index.html"/> + <item name="Latest API docs (development)" + href="apidocs/index.html"/> + <!--item name="Javadoc (1.0 release)" + href="http://commons.apache.org/rng/commons-numbers-gamma/javadocs/api-1.0/index.html"/--> + </menu> + + </body> +</project> http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/site/xdoc/index.xml ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/site/xdoc/index.xml b/commons-numbers-gamma/src/site/xdoc/index.xml new file mode 100644 index 0000000..29bb57f --- /dev/null +++ b/commons-numbers-gamma/src/site/xdoc/index.xml @@ -0,0 +1,40 @@ +<?xml version="1.0"?> + +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> + +<document> + + <properties> + <title>Commons Numbers Core</title> + </properties> + + <body> + + <section name="Apache Commons Numbers: Number types" href="summary"> + <p> + Commons Numbers provides utilities such as complex numbers and fractions. + </p> + + <p> + The "gamma" module contains utilities related to the "Gamma" function. + </p> + </section> + + </body> + +</document> http://git-wip-us.apache.org/repos/asf/commons-numbers/blob/0c9f1cde/commons-numbers-gamma/src/test/java/org/apache/commons/numbers/gamma/DigammaTest.java ---------------------------------------------------------------------- diff --git a/commons-numbers-gamma/src/test/java/org/apache/commons/numbers/gamma/DigammaTest.java b/commons-numbers-gamma/src/test/java/org/apache/commons/numbers/gamma/DigammaTest.java new file mode 100644 index 0000000..17b459a --- /dev/null +++ b/commons-numbers-gamma/src/test/java/org/apache/commons/numbers/gamma/DigammaTest.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.gamma; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests for {@link Digamma}. + */ +public class DigammaTest { + @Test + public void testDigammaLargeArgs() { + double eps = 1e-8; + Assert.assertEquals(4.6001618527380874002, Digamma.value(100), eps); + Assert.assertEquals(3.9019896734278921970, Digamma.value(50), eps); + Assert.assertEquals(2.9705239922421490509, Digamma.value(20), eps); + Assert.assertEquals(2.9958363947076465821, Digamma.value(20.5), eps); + Assert.assertEquals(2.2622143570941481605, Digamma.value(10.1), eps); + Assert.assertEquals(2.1168588189004379233, Digamma.value(8.8), eps); + Assert.assertEquals(1.8727843350984671394, Digamma.value(7), eps); + Assert.assertEquals(0.42278433509846713939, Digamma.value(2), eps); + Assert.assertEquals(-100.56088545786867450, Digamma.value(0.01), eps); + Assert.assertEquals(-4.0390398965921882955, Digamma.value(-0.8), eps); + Assert.assertEquals(4.2003210041401844726, Digamma.value(-6.3), eps); + Assert.assertEquals(-3.110625123035E-5, Digamma.value(1.4616), eps); + } + + @Test + public void testDigammaSmallArgs() { + // values for negative powers of 10 from 1 to 30 as computed by webMathematica with 20 digits + // see functions.wolfram.com + double[] expected = {-10.423754940411076795, -100.56088545786867450, -1000.5755719318103005, + -10000.577051183514335, -100000.57719921568107, -1.0000005772140199687e6, -1.0000000577215500408e7, + -1.0000000057721564845e8, -1.0000000005772156633e9, -1.0000000000577215665e10, -1.0000000000057721566e11, + -1.0000000000005772157e12, -1.0000000000000577216e13, -1.0000000000000057722e14, -1.0000000000000005772e15, -1e+16, + -1e+17, -1e+18, -1e+19, -1e+20, -1e+21, -1e+22, -1e+23, -1e+24, -1e+25, -1e+26, + -1e+27, -1e+28, -1e+29, -1e+30}; + for (double n = 1; n < 30; n++) { + checkRelativeError(String.format("Test %.0f: ", n), expected[(int) (n - 1)], Digamma.value(Math.pow(10.0, -n)), 1e-8); + } + } + + @Test + public void testDigammaNonRealArgs() { + Assert.assertTrue(Double.isNaN(Digamma.value(Double.NaN))); + Assert.assertTrue(Double.isInfinite(Digamma.value(Double.POSITIVE_INFINITY))); + Assert.assertTrue(Double.isInfinite(Digamma.value(Double.NEGATIVE_INFINITY))); + } + + private void checkRelativeError(String msg, + double expected, + double actual, + double tolerance) { + Assert.assertEquals(msg, expected, actual, Math.abs(tolerance * actual)); + } +} +