s_round.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Round double to integer away from zero.
  2. Copyright (C) 1997 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public
  7. License as published by the Free Software Foundation; either
  8. version 2.1 of the License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; if not, write to the Free
  15. Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  16. 02111-1307 USA. */
  17. #include <math.h>
  18. #include "math_private.h"
  19. static const double huge = 1.0e300;
  20. double
  21. round (double x)
  22. {
  23. int32_t i0, _j0;
  24. u_int32_t i1;
  25. EXTRACT_WORDS (i0, i1, x);
  26. _j0 = ((i0 >> 20) & 0x7ff) - 0x3ff;
  27. if (_j0 < 20)
  28. {
  29. if (_j0 < 0)
  30. {
  31. if (huge + x > 0.0)
  32. {
  33. i0 &= 0x80000000;
  34. if (_j0 == -1)
  35. i0 |= 0x3ff00000;
  36. i1 = 0;
  37. }
  38. }
  39. else
  40. {
  41. u_int32_t i = 0x000fffff >> _j0;
  42. if (((i0 & i) | i1) == 0)
  43. /* X is integral. */
  44. return x;
  45. if (huge + x > 0.0)
  46. {
  47. /* Raise inexact if x != 0. */
  48. i0 += 0x00080000 >> _j0;
  49. i0 &= ~i;
  50. i1 = 0;
  51. }
  52. }
  53. }
  54. else if (_j0 > 51)
  55. {
  56. if (_j0 == 0x400)
  57. /* Inf or NaN. */
  58. return x + x;
  59. else
  60. return x;
  61. }
  62. else
  63. {
  64. u_int32_t i = 0xffffffff >> (_j0 - 20);
  65. if ((i1 & i) == 0)
  66. /* X is integral. */
  67. return x;
  68. if (huge + x > 0.0)
  69. {
  70. /* Raise inexact if x != 0. */
  71. u_int32_t j = i1 + (1 << (51 - _j0));
  72. if (j < i1)
  73. i0 += 1;
  74. i1 = j;
  75. }
  76. i1 &= ~i;
  77. }
  78. INSERT_WORDS (x, i0, i1);
  79. return x;
  80. }
  81. libm_hidden_def(round)