简体   繁体   中英

Is there any difference between `x > 0` and `x > 0.0D` in Java?

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:

  1. Is the code equal to return (a <= 0)? 0.0D - a: a; return (a <= 0)? 0.0D - a: a;
  2. Furthermore, is the code euqal to return (a <= 0)? - a: a; return (a <= 0)? - a: a;

Thanks for any help!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM