s_rint.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 t;
  32. /* We use w = x + 2^52; t = w - 2^52; trick to round x to integer.
  33. * This trick requires that compiler does not optimize it
  34. * by keeping intermediate result w in a register wider than double.
  35. * Declaring w volatile assures that value gets truncated to double
  36. * (unfortunately, it also forces store+load):
  37. */
  38. volatile double w;
  39. EXTRACT_WORDS(i0,i1,x);
  40. /* Unbiased exponent */
  41. j0 = ((((u_int32_t)i0) >> 20)&0x7ff)-0x3ff;
  42. if (j0 > 51) {
  43. //Why bother? Just returning x works too
  44. //if (j0 == 0x400) /* inf or NaN */
  45. // return x+x;
  46. return x; /* x is integral */
  47. }
  48. /* Sign */
  49. sx = ((u_int32_t)i0) >> 31;
  50. if (j0<20) {
  51. if (j0<0) { /* |x| < 1 */
  52. if (((i0&0x7fffffff)|i1)==0) return x;
  53. i1 |= (i0&0x0fffff);
  54. i0 &= 0xfffe0000;
  55. i0 |= ((i1|-i1)>>12)&0x80000;
  56. SET_HIGH_WORD(x,i0);
  57. w = TWO52[sx]+x;
  58. t = w-TWO52[sx];
  59. GET_HIGH_WORD(i0,t);
  60. SET_HIGH_WORD(t,(i0&0x7fffffff)|(sx<<31));
  61. return t;
  62. } else {
  63. i = (0x000fffff)>>j0;
  64. if (((i0&i)|i1)==0) return x; /* x is integral */
  65. i>>=1;
  66. if (((i0&i)|i1)!=0) {
  67. if (j0==19) i1 = 0x40000000;
  68. else i0 = (i0&(~i))|((0x20000)>>j0);
  69. }
  70. }
  71. } else {
  72. i = ((u_int32_t)(0xffffffff))>>(j0-20);
  73. if ((i1&i)==0) return x; /* x is integral */
  74. i>>=1;
  75. if ((i1&i)!=0) i1 = (i1&(~i))|((0x40000000)>>(j0-20));
  76. }
  77. INSERT_WORDS(x,i0,i1);
  78. w = TWO52[sx]+x;
  79. return w-TWO52[sx];
  80. }
  81. libm_hidden_def(rint)
  82. strong_alias(rint, nearbyint)
  83. libm_hidden_def(nearbyint)