s_rint.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* @(#)s_rint.c 1.3 95/01/18 */
  2. /*
  3. * ====================================================
  4. * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
  5. *
  6. * Developed at SunSoft, 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. /*
  13. * rint(x)
  14. * Return x rounded to integral value according to the prevailing
  15. * rounding mode.
  16. * Method:
  17. * Using floating addition.
  18. * Exception:
  19. * Inexact flag raised if x not equal to rint(x).
  20. */
  21. #include "fdlibm.h"
  22. #ifndef _DOUBLE_IS_32BITS
  23. #ifdef __STDC__
  24. static const double
  25. #else
  26. static double
  27. #endif
  28. TWO52[2]={
  29. 4.50359962737049600000e+15, /* 0x43300000, 0x00000000 */
  30. -4.50359962737049600000e+15, /* 0xC3300000, 0x00000000 */
  31. };
  32. #ifdef __STDC__
  33. double rint(double x)
  34. #else
  35. double rint(x)
  36. double x;
  37. #endif
  38. {
  39. int32_t i0,j0,sx;
  40. uint32_t i,i1;
  41. double t;
  42. volatile double w;
  43. EXTRACT_WORDS(i0,i1,x);
  44. sx = (i0>>31)&1;
  45. j0 = ((i0>>20)&0x7ff)-0x3ff;
  46. if(j0<20) {
  47. if(j0<0) {
  48. if(((i0&0x7fffffff)|i1)==0) return x;
  49. i1 |= (i0&0x0fffff);
  50. i0 &= 0xfffe0000;
  51. i0 |= ((i1|-i1)>>12)&0x80000;
  52. SET_HIGH_WORD(x,i0);
  53. w = TWO52[sx]+x;
  54. t = w-TWO52[sx];
  55. GET_HIGH_WORD(i0,t);
  56. SET_HIGH_WORD(t,(i0&0x7fffffff)|(sx<<31));
  57. return t;
  58. } else {
  59. i = (0x000fffff)>>j0;
  60. if(((i0&i)|i1)==0) return x; /* x is integral */
  61. i>>=1;
  62. if(((i0&i)|i1)!=0) {
  63. if(j0==19) i1 = 0x40000000; else
  64. i0 = (i0&(~i))|((0x20000)>>j0);
  65. }
  66. }
  67. } else if (j0>51) {
  68. if(j0==0x400) return x+x; /* inf or NaN */
  69. else return x; /* x is integral */
  70. } else {
  71. i = ((uint32_t)(0xffffffff))>>(j0-20);
  72. if((i1&i)==0) return x; /* x is integral */
  73. i>>=1;
  74. if((i1&i)!=0) i1 = (i1&(~i))|((0x40000000)>>(j0-20));
  75. }
  76. INSERT_WORDS(x,i0,i1);
  77. w = TWO52[sx]+x;
  78. return w-TWO52[sx];
  79. }
  80. #endif /* _DOUBLE_IS_32BITS */