Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid way to check that a double has been assigned a value of 0.0

I know there are plenty of pitfalls with using the equal comparator with double's so I'm cautious on how to implement a check for a value equal to exactly 0.0. Basically, I want to know if a value was never assigned or if it was intentionally assigned the value 0.0 with a literal. I do not want to know if it is nearly zero (ex - 0.0000000001).

So I'm debating between using val == 0.0 or something like so:

bool isZero(double val)
{
    if (val > std::numeric_limits<double>::min()) {
        return false;
    } else if (val < -std::numeric_limits<double>::min()) {
        return false;
    }
    return true;
}

Would there be any difference between these two statements? Should I favor one over the other? I'm particularly concerned with the underflow scenario where val == -0.0.

Thanks


I should have clarified the 'never assigned' statement to 'never assigned after default initialization'.

like image 989
DrTarr Avatar asked Sep 21 '20 11:09

DrTarr


1 Answers

If you need to know if a floating point variable is exactly 0.0 or -0.0 then there is nothing wrong with using val == 0.0.

If you need to know if it is exactly 0.0 and not -0.0 then you must verify that you are using ieee-754 floating points and check whether the bit representation is all zero.

like image 62
Mestkon Avatar answered Nov 19 '22 20:11

Mestkon