floor.c 653 B

12345678910111213141516171819202122232425262728293031
  1. #include "libm.h"
  2. #if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1
  3. #define EPS DBL_EPSILON
  4. #elif FLT_EVAL_METHOD==2
  5. #define EPS LDBL_EPSILON
  6. #endif
  7. static const double_t toint = 1/EPS;
  8. double floor(double x)
  9. {
  10. union {double f; uint64_t i;} u = {x};
  11. int e = u.i >> 52 & 0x7ff;
  12. double_t y;
  13. if (e >= 0x3ff+52 || x == 0)
  14. return x;
  15. /* y = int(x) - x, where int(x) is an integer neighbor of x */
  16. if (u.i >> 63)
  17. y = x - toint + toint - x;
  18. else
  19. y = x + toint - toint - x;
  20. /* special case because of non-nearest rounding modes */
  21. if (e <= 0x3ff-1) {
  22. FORCE_EVAL(y);
  23. return u.i >> 63 ? -1 : 0;
  24. }
  25. if (y > 0)
  26. return x + y - 1;
  27. return x + y;
  28. }