Consider for example the following double-precision numbers:
x = 1232.2454545e-89;
y = -1232.2454545e-89;
Can I be sure that y
is always exactly equal to -x
(or Matlab's uminus(x)
)? Or should I expect small numerical differences of the order or eps
as it often happens with numerical computations? Try for example sqrt(3)^2-3
: the result is not exactly zero. Can that happen with unary minus as well? Is it lossy like square root is?
Another way to put the question would be: is a negative numerical literal always equal to negating its positive counterpart?
My question refers to Matlab, but probably has more to do with the IEEE 754 standard than with Matlab specifically.
I have done some tests in Matlab with a few randomly selected numbers. I have found that, in those cases,
typecast(x, 'uint8')
and typecast(-x, 'uint8')
differ only in the sign bit as defined by IEEE 754 double-precision format.This suggests that the answer may be affirmative. If applying unary minus only changes the sign bit, and not the significand, no precision is lost.
But of course I have only tested a few cases. I'd like to be sure this happens in all cases.
The - (unary minus) operator negates the value of the operand. The operand can have any arithmetic type. The result is not an lvalue. For example, if quality has the value 100 , -quality has the value -100 .
In some contexts, - is the unary minus operator. In other contexts, - is the subtraction operator. asks for 12 to be subtracted from 95. means add 3 to negative 12 (resulting in -9).
Unary plus ( + ) or minus ( - ) converts a non-numeric value into a number. The unary minus negates the value after the conversion. The prefix increment operator adds one to a value. The value is changed before the statement is evaluated.
Formally, in the examples above we have two different operators that share the same symbol: the negation operator, a unary operator that reverses the sign, and the subtraction operator, a binary operator that subtracts one number from another.
This question is computer architecture dependent. However, the sign of floating point numbers on modern architectures (including x64 and ARM cores) is represented by a single sign bit, and they have instructions to flip this bit (e.g. FCHS). That being the case, we can draw two conclusions:
That said, the only way to be sure would be to inspect the assembly code for uminus in your MATLAB installation. I don't know how to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With