Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Ask HN: Guess the output of these 3 lines of C++
2 points by ur-whale on April 8, 2023 | hide | past | favorite | 6 comments
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.


You may also then be surprised that 1.0f - .000000001f gives the same result: 1.0f


> You may also then be surprised that 1.0f - .000000001f gives the same result: 1.0f

No, that anything but surprising.

But the fact that some floats are exactly 1.0f away from their floor, is not only surprising, it's super annoying.


You're not surprised that 1.0f is exactly 1.0f away from .000000001f, but you are surprised that -1.0f is exactly 1.0f away from -.000000001f?


> But the fact that some floats are exactly 1.0f away from their floor

Why do you think that computation produces an exact result? I would think it doesn’t.


not wrong as c++ libr, math.h etc, specs defines its functions' specs along with limitations


Not sure what you mean (what is libr?) and where specifically does it say (x-floorf(x)) jumps around that way?




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: