4 ms·
Clear your floating point exception register by calling feclearexcept(FE_ALL_EXCEPT). Convert to long by calling lrint(rint(x)). Then check your exception regis
by dfranke 7y ago
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.
- pjc50 7y agoI had no idea this feature existed! Does it behave usefully in a multithreaded context?
- dfranke 7y agoI think it uses thread-local storage like errno does, but I'd have to verify.
- clarry 7y agoYes 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.
- inetknght 7y agoAs 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...
- clarry 7y ago> 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.
- dfranke 7y agoThanks. I should file a bug about this against the Linux man-pages project.