Hacker News new | past | comments | ask | show | jobs | submit login

Clear your floating point exception register by calling feclearexcept(FE_ALL_EXCEPT). Convert to long by calling lrint(rint(x)). Then check your exception register using fetestexcept(). FE_INEXACT will indicate that the input wasn't an integer, and FE_INVALID will indicate that the result doesn't fit in a long.

Edit: check for me whether just calling lrint(x) works. The manpage doesn't specify that lrint() will set FE_INEXACT, but it seems weird to me that it wouldn't.




As someone who's had to read C and C++ code using `double`, it's been a few years since I've heard of `feclearexcept` and how important it is.

Great, thanks, now I have to go back and restart some of those code reviews I've been doing of certain third party matrix math libraries...


> The manpage doesn't specify that lrint() will set FE_INEXACT, but it seems weird to me that it wouldn't.

Annex F:

The lrint and llrint functions provide floating-to-integer conversion as prescribed by IEC 60559. They round according to the current rounding direction. If the rounded value is outside the range of the return type, the numeric result is unspecified and the ''invalid'' floating-point exception is raised. When they raise no other floating-point exception and the result differs from the argument, they raise the ''inexact'' floating-point exception.


Thanks. I should file a bug about this against the Linux man-pages project.


I had no idea this feature existed! Does it behave usefully in a multithreaded context?


Yes it does. N1570 7.6:

> The floating-point environment has thread storage duration. The initial state for a thread's floating-point environment is the current state of the floating-point environment of the thread that creates it at the time of creation.


I think it uses thread-local storage like errno does, but I'd have to verify.




Applications are open for YC Summer 2020

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

Search: