Skip to content

Floating Point Puzzle of the Day (C++)

by Thomas on November 16th, 2010

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?


											

From → Development

3 Comments
  1. 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”.

  2. Gah—those includes should be stdio.h and math.h.

  3. Indeed, you have won the honor of being the first to solve the puzzle in the comments! :)

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS