nexttoward.c 796 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include "libm.h"
  2. #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
  3. double nexttoward(double x, long double y)
  4. {
  5. return nextafter(x, y);
  6. }
  7. #else
  8. #define SIGN ((uint64_t)1<<63)
  9. double nexttoward(double x, long double y)
  10. {
  11. union dshape ux;
  12. int e;
  13. if (isnan(x) || isnan(y))
  14. return x + y;
  15. if (x == y)
  16. return y;
  17. ux.value = x;
  18. if (x == 0) {
  19. ux.bits = 1;
  20. if (signbit(y))
  21. ux.bits |= SIGN;
  22. } else if (x < y) {
  23. if (signbit(x))
  24. ux.bits--;
  25. else
  26. ux.bits++;
  27. } else {
  28. if (signbit(x))
  29. ux.bits++;
  30. else
  31. ux.bits--;
  32. }
  33. e = ux.bits>>52 & 0x7ff;
  34. /* raise overflow if ux.value is infinite and x is finite */
  35. if (e == 0x7ff)
  36. return x + x;
  37. /* raise underflow if ux.value is subnormal or zero */
  38. if (e == 0)
  39. FORCE_EVAL(x*x + ux.value*ux.value);
  40. return ux.value;
  41. }
  42. #endif