lrint.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include <limits.h>
  2. #include <fenv.h>
  3. #include "libm.h"
  4. /*
  5. If the result cannot be represented (overflow, nan), then
  6. lrint raises the invalid exception.
  7. Otherwise if the input was not an integer then the inexact
  8. exception is raised.
  9. C99 is a bit vague about whether inexact exception is
  10. allowed to be raised when invalid is raised.
  11. (F.9 explicitly allows spurious inexact exceptions, F.9.6.5
  12. does not make it clear if that rule applies to lrint, but
  13. IEEE 754r 7.8 seems to forbid spurious inexact exception in
  14. the ineger conversion functions)
  15. So we try to make sure that no spurious inexact exception is
  16. raised in case of an overflow.
  17. If the bit size of long > precision of double, then there
  18. cannot be inexact rounding in case the result overflows,
  19. otherwise LONG_MAX and LONG_MIN can be represented exactly
  20. as a double.
  21. */
  22. #if LONG_MAX < 1U<<53 && defined(FE_INEXACT)
  23. long lrint(double x)
  24. {
  25. int e;
  26. e = fetestexcept(FE_INEXACT);
  27. x = rint(x);
  28. if (!e && (x > LONG_MAX || x < LONG_MIN))
  29. feclearexcept(FE_INEXACT);
  30. /* conversion */
  31. return x;
  32. }
  33. #else
  34. long lrint(double x)
  35. {
  36. return rint(x);
  37. }
  38. #endif