s_floor.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* @(#)s_floor.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 const char rcsid[] =
  14. "$NetBSD: s_floor.c,v 1.8 1995/05/10 20:47:20 jtc Exp $";
  15. #endif
  16. /*
  17. * floor(x)
  18. * Return x rounded toward -inf to integral value
  19. * Method:
  20. * Bit twiddling.
  21. * Exception:
  22. * Inexact flag raised if x not equal to floor(x).
  23. */
  24. #include "math_libm.h"
  25. #include "math_private.h"
  26. #ifdef __STDC__
  27. static const double huge_val = 1.0e300;
  28. #else
  29. static double huge_val = 1.0e300;
  30. #endif
  31. libm_hidden_proto(floor)
  32. #ifdef __STDC__
  33. double floor(double x)
  34. #else
  35. double floor(x)
  36. double x;
  37. #endif
  38. {
  39. int32_t i0, i1, j0;
  40. u_int32_t i, j;
  41. EXTRACT_WORDS(i0, i1, x);
  42. j0 = ((i0 >> 20) & 0x7ff) - 0x3ff;
  43. if (j0 < 20) {
  44. if (j0 < 0) { /* raise inexact if x != 0 */
  45. if (huge_val + x > 0.0) { /* return 0*sign(x) if |x|<1 */
  46. if (i0 >= 0) {
  47. i0 = i1 = 0;
  48. } else if (((i0 & 0x7fffffff) | i1) != 0) {
  49. i0 = 0xbff00000;
  50. i1 = 0;
  51. }
  52. }
  53. } else {
  54. i = (0x000fffff) >> j0;
  55. if (((i0 & i) | i1) == 0)
  56. return x; /* x is integral */
  57. if (huge_val + x > 0.0) { /* raise inexact flag */
  58. if (i0 < 0)
  59. i0 += (0x00100000) >> j0;
  60. i0 &= (~i);
  61. i1 = 0;
  62. }
  63. }
  64. } else if (j0 > 51) {
  65. if (j0 == 0x400)
  66. return x + x; /* inf or NaN */
  67. else
  68. return x; /* x is integral */
  69. } else {
  70. i = ((u_int32_t) (0xffffffff)) >> (j0 - 20);
  71. if ((i1 & i) == 0)
  72. return x; /* x is integral */
  73. if (huge_val + x > 0.0) { /* raise inexact flag */
  74. if (i0 < 0) {
  75. if (j0 == 20)
  76. i0 += 1;
  77. else {
  78. j = i1 + (1 << (52 - j0));
  79. if (j < (u_int32_t) i1)
  80. i0 += 1; /* got a carry */
  81. i1 = j;
  82. }
  83. }
  84. i1 &= (~i);
  85. }
  86. }
  87. INSERT_WORDS(x, i0, i1);
  88. return x;
  89. }
  90. libm_hidden_def(floor)