Reputation: 20674
I understand that equality operation should not be performed on floating point numbers due to the way the value is stored, and instead a threshold comparison should be performed. But is it safe to use equality when the value is set to a constant value, say 0?
void test() {
double max = 0.0;
do {
if (condition) {
if (max != 0.0) { // Is this safe
// myval is always a large positive number
max = min(myval, max);
} else {
max = myval;
}
}
} while (my_condition);
return myval;
}
I can see several similar questions on StackOverflow. But my question is specific to a variable assigned the constant zero (not the result of an operation).
Upvotes: 0
Views: 89
Reputation: 227458
0.0
has an exact representation in IEEE-754, so if two variables are set to 0.0
their comparison should always yield true. But if in your code max
is really always 0.0
, you might as well remove the if block because it would never execute.
Upvotes: 2
Reputation: 145879
Assuming you are using IEEE-754 binary formats, yes it is safe as 0.0
can be represented exactly in IEEE-754. There is exactly one representation for +0
in binary formats (and one for -0
and note also that+0 = -0
).
Upvotes: 2