IEEE 754: is v *= -1 always guaranteed to be the same as v = -v?

Viewed 57

Is it guaranteed by standards (IEEE 754 / C) that in the following code assertion will never be failed?

int main()
{
    for ( /* all possible float / double values */ )
    {
        v_neg1 = v * -1;
        v_neg2 = -v;
        assert( v_neg1 == v_neg2 );
    }
    return 0;
}

UPD.

  1. When asking I've meant all possible float / double values excluding NaNs.
  2. See similar question: .NET decimal.Negate vs multiplying by -1
1 Answers

No, this is not necessarily true, because NaNs never compare equal to each other.

Other than that, given that the sign bit is independent of the exponent and absolute significand, I believe it to be true for all ordinary values. C refers to ISO/IEC 60559 / IEEE 754 appendix; unfortunately I do not have the standard myself.

#include <math.h>
#include <assert.h>


int main(void)
{
    double v, v_neg1, v_neg2;

    v = NAN;
    v_neg1 = v * -1;
    v_neg2 = -v;
    assert( v_neg1 == v_neg2 );
}
Related