Added abs to DerivativeStructure.

We handle +0.0/-0.0 correctly, i.e. we flip derivatives sign when value
is negative zero.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1373775 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Luc Maisonobe 2012-08-16 10:06:16 +00:00
parent 4e72620a37
commit 09b90da825
2 changed files with 33 additions and 0 deletions

View File

@ -355,6 +355,18 @@ public class DerivativeStructure implements FieldElement<DerivativeStructure>, S
return ds;
}
/** absolute value.
* @return abs(this)
*/
public DerivativeStructure abs() {
if (Double.doubleToLongBits(data[0]) < 0) {
// we use the bits representation to also handle -0.0
return negate();
} else {
return this;
}
}
/** {@inheritDoc} */
public DerivativeStructure reciprocal() {
final DerivativeStructure result = new DerivativeStructure(compiler);

View File

@ -731,6 +731,27 @@ public class DerivativeStructureTest {
}
}
@Test
public void testAbs() {
DerivativeStructure minusOne = new DerivativeStructure(1, 1, 0, -1.0);
Assert.assertEquals(+1.0, minusOne.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusOne = new DerivativeStructure(1, 1, 0, +1.0);
Assert.assertEquals(+1.0, plusOne.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, plusOne.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure minusZero = new DerivativeStructure(1, 1, 0, -0.0);
Assert.assertEquals(+0.0, minusZero.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusZero.abs().getPartialDerivative(1), 1.0e-15);
DerivativeStructure plusZero = new DerivativeStructure(1, 1, 0, +0.0);
Assert.assertEquals(+0.0, plusZero.abs().getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, plusZero.abs().getPartialDerivative(1), 1.0e-15);
}
@Test
public void testField() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {