Suppose x
is a floating point number, I want to know whether - ( - x)
equals to x
in general?
Let us ignore corner cases such as x = max_floating_point_number / min_floating_number.
Suppose x
is a floating point number, I want to know whether - ( - x)
equals to x
in general?
Let us ignore corner cases such as x = max_floating_point_number / min_floating_number.
You have not tagged your question with any programming language, so the answer is yes, according to the IEEE 754 standard, for any non-NaN floating-point value x, x = - (- x).
In some poorly implemented or poorly specified languages, x
can have been computed as a non-NaN value and make - (- x) == x
evaluate to false. This can happen when the compiler is allowed to compute some expressions with extra precision and the reduction from extra precision to the precision indicated by the type is poorly specified (C#) or poorly implemented (as happens with some C compilers). In this case, it is possible that x
on the right-hand side keeps its extra-precise value while - (- x)
is computed at the precision of the type, and the end result is that they are different.
In general, yes; negation of a floating-point value induces no error or loss of precision. (It just involves flipping a bit.)
The one exception to this is NaN. -(-(NaN)) is NaN, but NaN does not compare equal to any value, even another NaN. That's firmly in the realm of "corner cases", though.