Java 中的 `x > 0` 和 `x > 0.0D` 有什么区别吗?
Is there any difference between `x > 0` and `x > 0.0D` in Java?
以下代码来自java标准库的Math.java
:
public static double abs(double a) {
return (a <= 0.0D) ? 0.0D - a : a;
}
我有以下问题:
- 代码是否等于
return (a <= 0) ? 0.0D - a : a;
- 此外,代码是否等同于
return (a <= 0) ? - a : a;
感谢您的帮助!
a <= 0
当 a
是 double 时将 0
转换为 double
(由于二进制数字提升),这意味着它等同于 a <= 0.0D
。
a <= 0.0D
可能更有效,因为它保存了转换,但如果编译器将 a <= 0
转换为 a <= 0.0D
以保存该类型转换,我不会感到惊讶.
相关JLS语录:
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.
关于你的第二个问题,使用一元否定运算符的代码不等同于abs
方法的代码,因为:
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 -)
顺便说一句,正零或负零的情况在abs
方法的Javadoc中作为特例提到:
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.
前两个特例是-a
不同于0.0D - a
的情况。
以下代码来自java标准库的Math.java
:
public static double abs(double a) {
return (a <= 0.0D) ? 0.0D - a : a;
}
我有以下问题:
- 代码是否等于
return (a <= 0) ? 0.0D - a : a;
- 此外,代码是否等同于
return (a <= 0) ? - a : a;
感谢您的帮助!
a <= 0
当 a
是 double 时将 0
转换为 double
(由于二进制数字提升),这意味着它等同于 a <= 0.0D
。
a <= 0.0D
可能更有效,因为它保存了转换,但如果编译器将 a <= 0
转换为 a <= 0.0D
以保存该类型转换,我不会感到惊讶.
相关JLS语录:
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.
关于你的第二个问题,使用一元否定运算符的代码不等同于abs
方法的代码,因为:
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 -)
顺便说一句,正零或负零的情况在abs
方法的Javadoc中作为特例提到:
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.
前两个特例是-a
不同于0.0D - a
的情况。