Ask HN: Guess the output of these 3 lines of C++

https://news.ycombinator.com/item?id=35498456
by ur-whale • 3 years ago
2 6 3 years ago

Today, a long-held assumption of mine was shattered.

To wit: can you guess the output of this code?

And if you can, would love to understand why my assumption was obviously wrong:

    #include <math.h>
    #include <stdio.h>

    int main() {
      auto x = -1e-8f;
      printf("%.40f\n", (x - floorf(x)));
      return 0;
    }
Also, note that of all the 4B+ possible floats, there are over 800M of them that all break the assumption in the exact same manner.

a) you learn new stuff every day

b) floats are a bottomless pit of ugly corner cases

[EDIT]: for those wondering, the assumption was that the following always holds true for all float x:

    0.0f <= (x - floorf(x)) < 1.0f
And the assumption breaks for many, many floats, all of them negative, all of them very close to zero.

Related Stories

Loading related stories...

Source preview

news.ycombinator.com