s_nexttoward.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* @(#)s_nextafter.c 5.1 93/09/24 */
  2. /*
  3. * ====================================================
  4. * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
  5. *
  6. * Developed at SunPro, a Sun Microsystems, Inc. business.
  7. * Permission to use, copy, modify, and distribute this
  8. * software is freely granted, provided that this notice
  9. * is preserved.
  10. * ====================================================
  11. */
  12. /* IEEE functions
  13. * nexttoward(x,y)
  14. * return the next machine floating-point number of x in the
  15. * direction toward y.
  16. * Special cases:
  17. */
  18. #include <float.h>
  19. #include <openlibm_math.h>
  20. #include "math_private.h"
  21. double
  22. nexttoward(double x, long double y)
  23. {
  24. int32_t hx,ix;
  25. int64_t hy,iy;
  26. u_int32_t lx;
  27. u_int64_t ly;
  28. EXTRACT_WORDS(hx,lx,x);
  29. GET_LDOUBLE_WORDS64(hy,ly,y);
  30. ix = hx&0x7fffffff; /* |x| */
  31. iy = hy&0x7fffffffffffffffLL; /* |y| */
  32. if(((ix>=0x7ff00000)&&((ix-0x7ff00000)|lx)!=0) || /* x is nan */
  33. ((iy>=0x7fff000000000000LL)&&((iy-0x7fff000000000000LL)|ly)!=0))
  34. /* y is nan */
  35. return x+y;
  36. if((long double) x==y) return y; /* x=y, return y */
  37. if((ix|lx)==0) { /* x == 0 */
  38. volatile double u;
  39. INSERT_WORDS(x,(u_int32_t)((hy>>32)&0x80000000),1);/* return +-minsub */
  40. u = x;
  41. u = u * u; /* raise underflow flag */
  42. return x;
  43. }
  44. if(hx>=0) { /* x > 0 */
  45. if (hy<0||(ix>>20)>(iy>>48)-0x3c00
  46. || ((ix>>20)==(iy>>48)-0x3c00
  47. && (((((int64_t)hx)<<28)|(lx>>4))>(hy&0x0000ffffffffffffLL)
  48. || (((((int64_t)hx)<<28)|(lx>>4))==(hy&0x0000ffffffffffffLL)
  49. && (lx&0xf)>(ly>>60))))) { /* x > y, x -= ulp */
  50. if(lx==0) hx -= 1;
  51. lx -= 1;
  52. } else { /* x < y, x += ulp */
  53. lx += 1;
  54. if(lx==0) hx += 1;
  55. }
  56. } else { /* x < 0 */
  57. if (hy>=0||(ix>>20)>(iy>>48)-0x3c00
  58. || ((ix>>20)==(iy>>48)-0x3c00
  59. && (((((int64_t)hx)<<28)|(lx>>4))>(hy&0x0000ffffffffffffLL)
  60. || (((((int64_t)hx)<<28)|(lx>>4))==(hy&0x0000ffffffffffffLL)
  61. && (lx&0xf)>(ly>>60))))) { /* x < y, x -= ulp */
  62. if(lx==0) hx -= 1;
  63. lx -= 1;
  64. } else { /* x > y, x += ulp */
  65. lx += 1;
  66. if(lx==0) hx += 1;
  67. }
  68. }
  69. hy = hx&0x7ff00000;
  70. if(hy>=0x7ff00000) {
  71. x = x+x; /* overflow */
  72. return x;
  73. }
  74. if(hy<0x00100000) {
  75. volatile double u = x*x; /* underflow */
  76. }
  77. INSERT_WORDS(x,hx,lx);
  78. return x;
  79. }