rint.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* origin: FreeBSD /usr/src/lib/msun/src/s_rint.c */
  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. /*
  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 "libm.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. uint32_t i,i1;
  31. double w,t;
  32. EXTRACT_WORDS(i0, i1, x);
  33. // FIXME: signed shift
  34. sx = (i0>>31) & 1;
  35. j0 = ((i0>>20)&0x7ff) - 0x3ff;
  36. if (j0 < 20) {
  37. if (j0 < 0) {
  38. if (((i0&0x7fffffff)|i1) == 0)
  39. return x;
  40. i1 |= i0 & 0x0fffff;
  41. i0 &= 0xfffe0000;
  42. i0 |= ((i1|-i1)>>12) & 0x80000;
  43. SET_HIGH_WORD(x, i0);
  44. STRICT_ASSIGN(double, w, TWO52[sx] + x);
  45. t = w - TWO52[sx];
  46. GET_HIGH_WORD(i0, t);
  47. SET_HIGH_WORD(t, (i0&0x7fffffff)|(sx<<31));
  48. return t;
  49. } else {
  50. i = 0x000fffff>>j0;
  51. if (((i0&i)|i1) == 0)
  52. return x; /* x is integral */
  53. i >>= 1;
  54. if (((i0&i)|i1) != 0) {
  55. /*
  56. * Some bit is set after the 0.5 bit. To avoid the
  57. * possibility of errors from double rounding in
  58. * w = TWO52[sx]+x, adjust the 0.25 bit to a lower
  59. * guard bit. We do this for all j0<=51. The
  60. * adjustment is trickiest for j0==18 and j0==19
  61. * since then it spans the word boundary.
  62. */
  63. if (j0 == 19)
  64. i1 = 0x40000000;
  65. else if (j0 == 18)
  66. i1 = 0x80000000;
  67. else
  68. i0 = (i0 & ~i)|(0x20000>>j0);
  69. }
  70. }
  71. } else if (j0 > 51) {
  72. if (j0 == 0x400)
  73. return x+x; /* inf or NaN */
  74. return x; /* x is integral */
  75. } else {
  76. i = (uint32_t)0xffffffff>>(j0-20);
  77. if ((i1&i) == 0)
  78. return x; /* x is integral */
  79. i >>= 1;
  80. if ((i1&i) != 0)
  81. i1 = (i1 & ~i)|(0x40000000>>(j0-20));
  82. }
  83. INSERT_WORDS(x, i0, i1);
  84. STRICT_ASSIGN(double, w, TWO52[sx] + x);
  85. return w - TWO52[sx];
  86. }