Marek Krzeminski
Marek Krzeminski

Reputation: 1398

Is there a difference between -x vs x * -1.0f?

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?

Upvotes: 0

Views: 224

Answers (4)

Polygnome
Polygnome

Reputation: 7820

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.

Upvotes: 2

Andy Turner
Andy Turner

Reputation: 140494

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).

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726899

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.

Upvotes: 2

joe pelletier
joe pelletier

Reputation: 399

If x was already a float then there is no difference. However the -x is more readable.

Upvotes: 1

Related Questions