abs(double ) is wrong
/**
* Returns the absolute value of a <code>double</code> value.
* If the argument is not negative, the argument is returned.
* If the argument is negative, the negation of the argument is returned.
*
* @param a a <code>double</code> value.
* @return the absolute value of the argument.
* @since JDK1.0
*/
public static double abs(double a)
{
return (a < 0 || a == -0.0D) ? -a :a;
}
In floating point, 0.0 == -0.0, so abs(+0.0) will return -0.0.
The best thing is to recode this as:
return a <= 0.0 ? 0.0 - a :a;
because 0.0 - 0.0 = 0.0, 0.0 - (-0.0) = 0.0
This is probably more efficient than coding an extra comparison, or
a doubleToLongBits operation.
/**
* Returns the absolute value of a <code>double</code> value.
* If the argument is not negative, the argument is returned.
* If the argument is negative, the negation of the argument is returned.
*
* @param a a <code>double</code> value.
* @return the absolute value of the argument.
* @since JDK1.0
*/
public static double abs(double a)
{
return (a < 0 || a == -0.0D) ? -a :a;
}
In floating point, 0.0 == -0.0, so abs(+0.0) will return -0.0.
The best thing is to recode this as:
return a <= 0.0 ? 0.0 - a :a;
because 0.0 - 0.0 = 0.0, 0.0 - (-0.0) = 0.0
This is probably more efficient than coding an extra comparison, or
a doubleToLongBits operation.
- duplicates
-
JDK-4096278 java.lang.Math.abs(float) works wrong with pozitive zero parameter
- Closed