s_round.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. libm_hidden_proto(round)
  21. double
  22. round (double x)
  23. {
  24. int32_t i0, j0;
  25. u_int32_t i1;
  26. EXTRACT_WORDS (i0, i1, x);
  27. j0 = ((i0 >> 20) & 0x7ff) - 0x3ff;
  28. if (j0 < 20)
  29. {
  30. if (j0 < 0)
  31. {
  32. if (huge + x > 0.0)
  33. {
  34. i0 &= 0x80000000;
  35. if (j0 == -1)
  36. i0 |= 0x3ff00000;
  37. i1 = 0;
  38. }
  39. }
  40. else
  41. {
  42. u_int32_t i = 0x000fffff >> j0;
  43. if (((i0 & i) | i1) == 0)
  44. /* X is integral. */
  45. return x;
  46. if (huge + x > 0.0)
  47. {
  48. /* Raise inexact if x != 0. */
  49. i0 += 0x00080000 >> j0;
  50. i0 &= ~i;
  51. i1 = 0;
  52. }
  53. }
  54. }
  55. else if (j0 > 51)
  56. {
  57. if (j0 == 0x400)
  58. /* Inf or NaN. */
  59. return x + x;
  60. else
  61. return x;
  62. }
  63. else
  64. {
  65. u_int32_t i = 0xffffffff >> (j0 - 20);
  66. if ((i1 & i) == 0)
  67. /* X is integral. */
  68. return x;
  69. if (huge + x > 0.0)
  70. {
  71. /* Raise inexact if x != 0. */
  72. u_int32_t j = i1 + (1 << (51 - j0));
  73. if (j < i1)
  74. i0 += 1;
  75. i1 = j;
  76. }
  77. i1 &= ~i;
  78. }
  79. INSERT_WORDS (x, i0, i1);
  80. return x;
  81. }
  82. libm_hidden_def(round)