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 thoughts on “Floating Point Puzzle of the Day (C++)

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

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>