s_rint.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * ====================================================
  3. * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
  4. *
  5. * Developed at SunPro, a Sun Microsystems, Inc. business.
  6. * Permission to use, copy, modify, and distribute this
  7. * software is freely granted, provided that this notice
  8. * is preserved.
  9. * ====================================================
  10. */
  11. /*
  12. * rint(x)
  13. * Return x rounded to integral value according to the prevailing
  14. * rounding mode.
  15. * Method:
  16. * Using floating addition.
  17. * Exception:
  18. * Inexact flag raised if x not equal to rint(x).
  19. */
  20. #include "math.h"
  21. #include "math_private.h"
  22. static const double
  23. TWO52[2]={
  24. 4.50359962737049600000e+15, /* 0x43300000, 0x00000000 */
  25. -4.50359962737049600000e+15, /* 0xC3300000, 0x00000000 */
  26. };
  27. double rint(double x)
  28. {
  29. int32_t i0,j0,sx;
  30. u_int32_t i,i1;
  31. double w,t;
  32. EXTRACT_WORDS(i0,i1,x);
  33. sx = (i0>>31)&1;
  34. j0 = ((i0>>20)&0x7ff)-0x3ff;
  35. if(j0<20) {
  36. if(j0<0) {
  37. if(((i0&0x7fffffff)|i1)==0) return x;
  38. i1 |= (i0&0x0fffff);
  39. i0 &= 0xfffe0000;
  40. i0 |= ((i1|-i1)>>12)&0x80000;
  41. SET_HIGH_WORD(x,i0);
  42. w = TWO52[sx]+x;
  43. t = w-TWO52[sx];
  44. GET_HIGH_WORD(i0,t);
  45. SET_HIGH_WORD(t,(i0&0x7fffffff)|(sx<<31));
  46. return t;
  47. } else {
  48. i = (0x000fffff)>>j0;
  49. if(((i0&i)|i1)==0) return x; /* x is integral */
  50. i>>=1;
  51. if(((i0&i)|i1)!=0) {
  52. if(j0==19) i1 = 0x40000000; else
  53. i0 = (i0&(~i))|((0x20000)>>j0);
  54. }
  55. }
  56. } else if (j0>51) {
  57. if(j0==0x400) return x+x; /* inf or NaN */
  58. else return x; /* x is integral */
  59. } else {
  60. i = ((u_int32_t)(0xffffffff))>>(j0-20);
  61. if((i1&i)==0) return x; /* x is integral */
  62. i>>=1;
  63. if((i1&i)!=0) i1 = (i1&(~i))|((0x40000000)>>(j0-20));
  64. }
  65. INSERT_WORDS(x,i0,i1);
  66. w = TWO52[sx]+x;
  67. return w-TWO52[sx];
  68. }
  69. libm_hidden_def(rint)
  70. strong_alias(rint, nearbyint)
  71. libm_hidden_def(nearbyint)