s_rint.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* @(#)s_rint.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. #include <sys/cdefs.h>
  13. /*
  14. * rint(x)
  15. * Return x rounded to integral value according to the prevailing
  16. * rounding mode.
  17. * Method:
  18. * Using floating addition.
  19. * Exception:
  20. * Inexact flag raised if x not equal to rint(x).
  21. */
  22. #include <float.h>
  23. #include "openlibm.h"
  24. #include "math_private.h"
  25. static const double
  26. TWO52[2]={
  27. 4.50359962737049600000e+15, /* 0x43300000, 0x00000000 */
  28. -4.50359962737049600000e+15, /* 0xC3300000, 0x00000000 */
  29. };
  30. double
  31. rint(double x)
  32. {
  33. int32_t i0,j0,sx;
  34. u_int32_t i,i1;
  35. double w,t;
  36. EXTRACT_WORDS(i0,i1,x);
  37. sx = (i0>>31)&1;
  38. j0 = ((i0>>20)&0x7ff)-0x3ff;
  39. if(j0<20) {
  40. if(j0<0) {
  41. if(((i0&0x7fffffff)|i1)==0) return x;
  42. i1 |= (i0&0x0fffff);
  43. i0 &= 0xfffe0000;
  44. i0 |= ((i1|-i1)>>12)&0x80000;
  45. SET_HIGH_WORD(x,i0);
  46. STRICT_ASSIGN(double,w,TWO52[sx]+x);
  47. t = w-TWO52[sx];
  48. GET_HIGH_WORD(i0,t);
  49. SET_HIGH_WORD(t,(i0&0x7fffffff)|(sx<<31));
  50. return t;
  51. } else {
  52. i = (0x000fffff)>>j0;
  53. if(((i0&i)|i1)==0) return x; /* x is integral */
  54. i>>=1;
  55. if(((i0&i)|i1)!=0) {
  56. /*
  57. * Some bit is set after the 0.5 bit. To avoid the
  58. * possibility of errors from double rounding in
  59. * w = TWO52[sx]+x, adjust the 0.25 bit to a lower
  60. * guard bit. We do this for all j0<=51. The
  61. * adjustment is trickiest for j0==18 and j0==19
  62. * since then it spans the word boundary.
  63. */
  64. if(j0==19) i1 = 0x40000000; else
  65. if(j0==18) i1 = 0x80000000; else
  66. i0 = (i0&(~i))|((0x20000)>>j0);
  67. }
  68. }
  69. } else if (j0>51) {
  70. if(j0==0x400) return x+x; /* inf or NaN */
  71. else return x; /* x is integral */
  72. } else {
  73. i = ((u_int32_t)(0xffffffff))>>(j0-20);
  74. if((i1&i)==0) return x; /* x is integral */
  75. i>>=1;
  76. if((i1&i)!=0) i1 = (i1&(~i))|((0x40000000)>>(j0-20));
  77. }
  78. INSERT_WORDS(x,i0,i1);
  79. STRICT_ASSIGN(double,w,TWO52[sx]+x);
  80. return w-TWO52[sx];
  81. }
  82. #if (LDBL_MANT_DIG == 53)
  83. __weak_reference(rint, rintl);
  84. #endif