truncl.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* origin: FreeBSD /usr/src/lib/msun/src/s_truncl.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. * truncl(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 truncl(x).
  19. */
  20. #include "libm.h"
  21. #if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
  22. long double truncl(long double x)
  23. {
  24. return trunc(x);
  25. }
  26. #elif (LDBL_MANT_DIG == 64 || LDBL_MANT_DIG == 113) && LDBL_MAX_EXP == 16384
  27. #ifdef LDBL_IMPLICIT_NBIT
  28. #define MANH_SIZE (LDBL_MANH_SIZE + 1)
  29. #else
  30. #define MANH_SIZE LDBL_MANH_SIZE
  31. #endif
  32. static const long double huge = 1.0e300;
  33. static const float zero[] = { 0.0, -0.0 };
  34. long double truncl(long double x)
  35. {
  36. union IEEEl2bits u = { .e = x };
  37. int e = u.bits.exp - LDBL_MAX_EXP + 1;
  38. if (e < MANH_SIZE - 1) {
  39. if (e < 0) {
  40. /* raise inexact if x != 0 */
  41. if (huge + x > 0.0)
  42. u.e = zero[u.bits.sign];
  43. } else {
  44. uint64_t m = ((1llu << MANH_SIZE) - 1) >> (e + 1);
  45. if (((u.bits.manh & m) | u.bits.manl) == 0)
  46. return x; /* x is integral */
  47. /* raise inexact */
  48. if (huge + x > 0.0) {
  49. u.bits.manh &= ~m;
  50. u.bits.manl = 0;
  51. }
  52. }
  53. } else if (e < LDBL_MANT_DIG - 1) {
  54. uint64_t m = (uint64_t)-1 >> (64 - LDBL_MANT_DIG + e + 1);
  55. if ((u.bits.manl & m) == 0)
  56. return x; /* x is integral */
  57. /* raise inexact */
  58. if (huge + x > 0.0)
  59. u.bits.manl &= ~m;
  60. }
  61. return u.e;
  62. }
  63. #endif