diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 167f79fa2..7a019df8e 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -51,6 +51,9 @@ If the output is not quite correct, check for invisible trailing spaces!
+
+ Fixed "Gamma#gamma(double)" for negative values smaller than -20.
+
Fixed javadoc of methods {floorDiv,floorMod} in class "FastMath".
diff --git a/src/main/java/org/apache/commons/math3/special/Gamma.java b/src/main/java/org/apache/commons/math3/special/Gamma.java
index 47bf8aa20..aaa561ba4 100644
--- a/src/main/java/org/apache/commons/math3/special/Gamma.java
+++ b/src/main/java/org/apache/commons/math3/special/Gamma.java
@@ -695,7 +695,7 @@ public class Gamma {
}
} else {
final double y = absX + LANCZOS_G + 0.5;
- final double gammaAbs = SQRT_TWO_PI / x *
+ final double gammaAbs = SQRT_TWO_PI / absX *
FastMath.pow(y, absX + 0.5) *
FastMath.exp(-y) * lanczos(absX);
if (x > 0.0) {
diff --git a/src/test/java/org/apache/commons/math3/special/GammaTest.java b/src/test/java/org/apache/commons/math3/special/GammaTest.java
index 54691fd81..db4be4677 100644
--- a/src/test/java/org/apache/commons/math3/special/GammaTest.java
+++ b/src/test/java/org/apache/commons/math3/special/GammaTest.java
@@ -974,6 +974,21 @@ public class GammaTest {
}
}
+ @Test
+ public void testGammaNegativeDouble() {
+ // check that the gamma function properly switches sign
+ // see: https://en.wikipedia.org/wiki/Gamma_function
+
+ double previousGamma = Gamma.gamma(-18.5);
+ for (double x = -19.5; x > -25; x -= 1.0) {
+ double gamma = Gamma.gamma(x);
+ Assert.assertEquals( (int) FastMath.signum(previousGamma),
+ - (int) FastMath.signum(gamma));
+
+ previousGamma = gamma;
+ }
+ }
+
private void checkRelativeError(String msg, double expected, double actual,
double tolerance) {