s_round.c 2.0 KB

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