s_rint.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #if defined(LIBM_SCCS) && !defined(lint)
  13. static char rcsid[] = "$NetBSD: s_rint.c,v 1.8 1995/05/10 20:48:04 jtc Exp $";
  14. #endif
  15. /*
  16. * rint(x)
  17. * Return x rounded to integral value according to the prevailing
  18. * rounding mode.
  19. * Method:
  20. * Using floating addition.
  21. * Exception:
  22. * Inexact flag raised if x not equal to rint(x).
  23. */
  24. #include "math.h"
  25. #include "math_private.h"
  26. #ifdef __STDC__
  27. static const double
  28. #else
  29. static double
  30. #endif
  31. TWO52[2]={
  32. 4.50359962737049600000e+15, /* 0x43300000, 0x00000000 */
  33. -4.50359962737049600000e+15, /* 0xC3300000, 0x00000000 */
  34. };
  35. #ifdef __STDC__
  36. double rint(double x)
  37. #else
  38. double rint(x)
  39. double x;
  40. #endif
  41. {
  42. int32_t i0,j0,sx;
  43. u_int32_t i,i1;
  44. double w,t;
  45. EXTRACT_WORDS(i0,i1,x);
  46. sx = (i0>>31)&1;
  47. j0 = ((i0>>20)&0x7ff)-0x3ff;
  48. if(j0<20) {
  49. if(j0<0) {
  50. if(((i0&0x7fffffff)|i1)==0) return x;
  51. i1 |= (i0&0x0fffff);
  52. i0 &= 0xfffe0000;
  53. i0 |= ((i1|-i1)>>12)&0x80000;
  54. SET_HIGH_WORD(x,i0);
  55. w = TWO52[sx]+x;
  56. t = w-TWO52[sx];
  57. GET_HIGH_WORD(i0,t);
  58. SET_HIGH_WORD(t,(i0&0x7fffffff)|(sx<<31));
  59. return t;
  60. } else {
  61. i = (0x000fffff)>>j0;
  62. if(((i0&i)|i1)==0) return x; /* x is integral */
  63. i>>=1;
  64. if(((i0&i)|i1)!=0) {
  65. if(j0==19) i1 = 0x40000000; 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. w = TWO52[sx]+x;
  80. return w-TWO52[sx];
  81. }