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?
Is there a difference between -x vs x * -1.0f?
219 Views Asked by Marek Krzeminski At
4
There are 4 best solutions below
0

Java uses binary floating point representation of IEEE, with the sign represented by a separate bit. Both multiplying by -1
and inverting the sign with -x
are done by flipping this sign bit, while keeping the rest of the representation unchanged. That is why there is no difference in the result, because -1.0f
has an exact representation, and there is no chance of changing the precision of representation of x
.
0

There is a slight difference in the bytecode produced:
float one(float x) {
return -x;
}
float two(float x) {
return x * -1.f;
}
float three(float x) {
return -1.f * x;
}
Decompile to:
float one(float);
Code:
0: fload_1
1: fneg
2: freturn
float two(float);
Code:
0: fload_1
1: ldc #2 // float -1.0f
3: fmul
4: freturn
float three(float);
Code:
0: ldc #2 // float -1.0f
2: fload_1
3: fmul
4: freturn
I would imagine that the fneg
instruction is slightly faster than the fload_1/fmul
; but the difference is likely to be negligible (and very possibly optimized out by the JIT).
In JLS §15.15.4 "Unary Minus Operator -", we find that
(Highlight mine)
The difference can be seen in the emitted bytecode. Unary minus is a simple
fneg
, while(-1f * x)
results in anfload
andfmul
, which is likely slightly slower.I have no idea if the JIT compiler will optimize it.
For readability, using
-x
is usually better.