Added copySign to DerivativeStructure.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1373777 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Luc Maisonobe 2012-08-16 10:06:50 +00:00
parent 70ea046932
commit 68c813c945
2 changed files with 31 additions and 0 deletions

View File

@ -386,6 +386,22 @@ public class DerivativeStructure implements FieldElement<DerivativeStructure>, S
FastMath.floor(data[0])); FastMath.floor(data[0]));
} }
/**
* Returns the instance with the sign of the argument.
* A NaN {@code sign} argument is treated as positive.
*
* @param sign the sign for the returned value
* @return the instance with the same sign as the {@code sign} argument
*/
public DerivativeStructure copySign(final double sign){
long m = Double.doubleToLongBits(data[0]);
long s = Double.doubleToLongBits(sign);
if ((m >= 0 && s >= 0) || (m < 0 && s < 0)) { // Sign is currently OK
return this;
}
return negate(); // flip sign
}
/** {@inheritDoc} */ /** {@inheritDoc} */
public DerivativeStructure reciprocal() { public DerivativeStructure reciprocal() {
final DerivativeStructure result = new DerivativeStructure(compiler); final DerivativeStructure result = new DerivativeStructure(compiler);

View File

@ -765,6 +765,21 @@ public class DerivativeStructureTest {
} }
@Test
public void testCopySign() {
DerivativeStructure minusOne = new DerivativeStructure(1, 1, 0, -1.0);
Assert.assertEquals(+1.0, minusOne.copySign(+1.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(+1.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(-1.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(-1.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(+0.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(+0.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(-0.0).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(-0.0).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(+1.0, minusOne.copySign(Double.NaN).getPartialDerivative(0), 1.0e-15);
Assert.assertEquals(-1.0, minusOne.copySign(Double.NaN).getPartialDerivative(1), 1.0e-15);
}
@Test @Test
public void testField() { public void testField() {
for (int maxOrder = 1; maxOrder < 5; ++maxOrder) { for (int maxOrder = 1; maxOrder < 5; ++maxOrder) {