trunc.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* origin: FreeBSD /usr/src/lib/msun/src/s_trunc.c */
  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. /*
  13. * trunc(x)
  14. * Return x rounded toward 0 to integral value
  15. * Method:
  16. * Bit twiddling.
  17. * Exception:
  18. * Inexact flag raised if x not equal to trunc(x).
  19. */
  20. #include "libm.h"
  21. static const double huge = 1.0e300;
  22. double trunc(double x)
  23. {
  24. int32_t i0,i1,j0;
  25. uint32_t i;
  26. EXTRACT_WORDS(i0, i1, x);
  27. j0 = ((i0>>20)&0x7ff) - 0x3ff;
  28. if (j0 < 20) {
  29. if (j0 < 0) { /* |x|<1, return 0*sign(x) */
  30. /* raise inexact if x != 0 */
  31. if (huge+x > 0.0) {
  32. i0 &= 0x80000000U;
  33. i1 = 0;
  34. }
  35. } else {
  36. i = 0x000fffff>>j0;
  37. if (((i0&i)|i1) == 0)
  38. return x; /* x is integral */
  39. /* raise inexact */
  40. if (huge+x > 0.0) {
  41. i0 &= ~i;
  42. i1 = 0;
  43. }
  44. }
  45. } else if (j0 > 51) {
  46. if (j0 == 0x400)
  47. return x + x; /* inf or NaN */
  48. return x; /* x is integral */
  49. } else {
  50. i = (uint32_t)0xffffffff>>(j0-20);
  51. if ((i1&i) == 0)
  52. return x; /* x is integral */
  53. /* raise inexact */
  54. if (huge+x > 0.0)
  55. i1 &= ~i;
  56. }
  57. INSERT_WORDS(x, i0, i1);
  58. return x;
  59. }