In java, is there a difference between negating a variable vs multiplying a variable by a float minus one, if the variable is also a float?
In JLS §15.15.4 "Unary Minus Operator -", we find that
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. Special cases of interest:
If the operand is NaN, the result is NaN. (Recall that NaN has no sign (§4.2.3).)
If the operand is an infinity, the result is the infinity of opposite sign.
If the operand is a zero, the result is the zero of opposite sign.
(Highlight mine)
The difference can be seen in the emitted bytecode. Unary minus is a simple fneg
, while (-1f * x)
results in an fload
and fmul
, which is likely slightly slower.
I have no idea if the JIT compiler will optimize it.
For readability, using -x
is usually better.