Reputation: 1551
The following code is from the Math.java
of java standard library:
public static double abs(double a) {
return (a <= 0.0D) ? 0.0D - a : a;
}
I have questions that:
return (a <= 0) ? 0.0D - a : a;
return (a <= 0) ? - a : a;
Thanks for any help!
Upvotes: 6
Views: 535
Reputation: 393966
a <= 0
when a
is double converts 0
to double
(due to binary numeric promotion), which means it's equivalent to a <= 0.0D
.
a <= 0.0D
might be more efficient, since it saves the conversion, but I wouldn't be surprised if the compiler converts a <= 0
to a <= 0.0D
in order to save that type conversion.
Relevant JLS quotes:
15.20.1. Numerical Comparison Operators <, <=, >, and >=
Binary numeric promotion is performed on the operands (§5.6.2).
5.6.2. Binary Numeric Promotion
If either operand is of type double, the other is converted to double.
As for your second question, the code that uses unary negation operator is not equivalent to the code of the abs
method, since:
For floating-point values, negation is not the same as subtraction from zero, because if x is +0.0, then 0.0-x is +0.0, but -x is -0.0. Unary minus merely inverts the sign of a floating-point number.
(15.15.4. Unary Minus Operator -)
BTW, the case of positive zero or negative zero is mentioned as a special case in the Javadoc of the abs
method:
Special cases:
• If the argument is positive zero or negative zero, the result is positive zero.
• If the argument is infinite, the result is positive infinity.
• If the argument is NaN, the result is NaN.
The first two special cases are the cases in which -a
differs from 0.0D - a
.
Upvotes: 8