Floating Point Puzzle of the Day (C++)
Here a small puzzle for those of you who have nothing better to do:
Let “x” be a float.
Can the following assert fire? (assert is the standard macro from cassert).
{ float y=x; assert(x==y); }
If yes, how?
If no, why not?
3 Comments
→
If x is NaN (e.g., sqrt(-1.0)), then x == y will return false:
#include
#include
int main(int argc, char *argv[]) {
float x = sqrt(-1.0);
float y = x;
puts(x == y ? “equal\n” : “not equal\n”);
return 0;
}
will output “not equal”.
Gah—those includes should be stdio.h and math.h.
Indeed, you have won the honor of being the first to solve the puzzle in the comments! :)