Fixed DerivativeStructure.pow(0.0).

x^0 is always 1.0, regardless of x (even if x is NaN in fact).
This commit is contained in:
Luc Maisonobe 2016-08-05 15:00:08 +02:00 committed by Emmanuel Bourg
parent 5c341d9ded
commit c64856ff7f
2 changed files with 29 additions and 0 deletions

View File

@ -886,6 +886,13 @@ public class DSCompiler {
public void pow(final double[] operand, final int operandOffset, final double p,
final double[] result, final int resultOffset) {
if (p == 0) {
// special case, x^0 = 1 for all x
result[resultOffset] = 1.0;
Arrays.fill(result, resultOffset + 1, resultOffset + getSize(), 0);
return;
}
// create the function value and derivatives
// [x^p, px^(p-1), p(p-1)x^(p-2), ... ]
double[] function = new double[1 + order];

View File

@ -31,6 +31,7 @@ import org.apache.commons.math4.rng.RandomSource;
import org.apache.commons.math4.util.ArithmeticUtils;
import org.apache.commons.math4.util.CombinatoricsUtils;
import org.apache.commons.math4.util.FastMath;
import org.apache.commons.math4.util.Precision;
import org.junit.Assert;
import org.junit.Test;
@ -323,6 +324,27 @@ public class DerivativeStructureTest extends ExtendedFieldElementAbstractTest<De
Assert.assertTrue(Double.isNaN(zeroZero.getPartialDerivative(1, 1, 0)));
}
// very special case: 0^0 where the power is a primitive
DerivativeStructure zeroDsZeroDouble = new DerivativeStructure(3, maxOrder, 0, 0.0).pow(0.0);
boolean first = true;
for (final double d : zeroDsZeroDouble.getAllDerivatives()) {
if (first) {
Assert.assertEquals(1.0, d, Precision.EPSILON);
first = false;
} else {
Assert.assertEquals(0.0, d, Precision.SAFE_MIN);
}
}
DerivativeStructure zeroDsZeroInt = new DerivativeStructure(3, maxOrder, 0, 0.0).pow(0);
first = true;
for (final double d : zeroDsZeroInt.getAllDerivatives()) {
if (first) {
Assert.assertEquals(1.0, d, Precision.EPSILON);
first = false;
} else {
Assert.assertEquals(0.0, d, Precision.SAFE_MIN);
}
}
}
}