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