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'.
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.
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