Lukin
Lukin

Reputation: 63

How to test if double value is not negative

I failed to google this so I'm asking how to properly and conclusively test double value to be greater then or equal to 0.

I'm somehow aware of double problematic zero value (the ± 0.0 and so on) and I need to check wheter my double variable is greater then or equal to 0. Or else and maybe better if is it not negative.

The question is, can i test this like this:
if(myDoubleValue >= 0.0) (i think this one could be problematic)
or will be better something like this:
if(!(myDoubleValue < 0.0))

Sorry for probably dumb question.

Upvotes: 1

Views: 7678

Answers (3)

Martin Nyolt
Martin Nyolt

Reputation: 4670

The value ±0 only indicates if the value approached 0 from negative or positive values (but this is not a guarantee for every case, of course). However, it still is 0.

Therefore, x >= 0 will include both +0 and -0 zero. You can test that for yourself in a simple program. :)

In the IEEE754 standard, it explicitly says

Comparisons shall ignore the sign of zero (so +0 = -0).

IEEE754 is used by most processors and implementations, so for all practical purposes -0 >= 0 is true.

For any number x, x >= 0 and !(x < 0) are the same. This is also true for +0 and -0.


As pointed out by aschepler in a comment, the two tests x >= 0 and !(x < 0) differ when x is NaN (not-a-number). NaN is always different from any real number, thus !(x < 0) will be true when x is NaN. If NaN can occur in your calculations, you may want to handle that separately.

Upvotes: 4

yman
yman

Reputation: 359

I believe this article might answer your question. Zero has its own noninterchangeable representation. Whether the value is positive or negative is represented by the sign bit.

Citing from the article:

if every bit is zero (the sign bit being irrelevant), then the number is considered zero.

Hence the positive/negative zero must have no impact on the comparison operations - it is still a zero.

Upvotes: 0

Shaikh Hafiz Ahamed
Shaikh Hafiz Ahamed

Reputation: 125

Yes you can test both
if(myDoubleValue >= 0.0)
and
if(!(myDoubleValue < 0.0))

Upvotes: 0

Related Questions