Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For a floating point value a: Does a*0.0 == 0.0 always evaluate true for finite values of a?

I was always assuming that the following test will always succeed for finite values (no INF, no NAN) of somefloat:

assert(somefloat*0.0==0.0);

In Multiply by 0 optimization it was stated that double a=0.0 and double a=-0.0 are not strictly speaking the same thing.

So I was wondering whether this can lead to problems on some platforms e.g. can the result of the above test depend on a beeing positive or negative.

like image 971
Martin Avatar asked Dec 20 '12 12:12

Martin


3 Answers

If your implementation uses IEEE 754 arithmetic (which most do), then positive and negative zero will compare equal. Since the left-hand side of your expression can only be either positive or negative zero for finite a, the assertion will always be true.

If it uses some other kind of arithmetic, then only the implementor, and hopefully the implementation-specific documentation, can tell you. Arguably (see comments) the wording of the standard can be taken to imply that they must compare equal in any case, and certainly no sane implementation would do otherwise.

like image 179
Mike Seymour Avatar answered Nov 17 '22 19:11

Mike Seymour


-0.0 == 0.0 according to double comparison rules.

For non-finite values (+-Inf, Nan) somefloat*0.0 != 0.0.

like image 22
Aki Suihkonen Avatar answered Nov 17 '22 19:11

Aki Suihkonen


Your assert can never fail, as long as somefloat is not infinity or NaN. On systems which don't support infinity or NaN, the compiler can simply optimize it out.

like image 1
James Kanze Avatar answered Nov 17 '22 20:11

James Kanze