s_trunc.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. /*
  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 <math.h>
  21. #include "math_private.h"
  22. static const double huge = 1.0e300;
  23. double
  24. trunc(double x)
  25. {
  26. int32_t i0,i1,j0;
  27. uint32_t i,j;
  28. EXTRACT_WORDS(i0,i1,x);
  29. j0 = ((i0>>20)&0x7ff)-0x3ff;
  30. if(j0<20) {
  31. if(j0<0) { /* raise inexact if x != 0 */
  32. if(huge+x>0.0) {/* |x|<1, so return 0*sign(x) */
  33. i0 &= 0x80000000U;
  34. i1 = 0;
  35. }
  36. } else {
  37. i = (0x000fffff)>>j0;
  38. if(((i0&i)|i1)==0) return x; /* x is integral */
  39. if(huge+x>0.0) { /* raise inexact flag */
  40. i0 &= (~i); i1=0;
  41. }
  42. }
  43. } else if (j0>51) {
  44. if(j0==0x400) return x+x; /* inf or NaN */
  45. else return x; /* x is integral */
  46. } else {
  47. i = ((uint32_t)(0xffffffff))>>(j0-20);
  48. if((i1&i)==0) return x; /* x is integral */
  49. if(huge+x>0.0) /* raise inexact flag */
  50. i1 &= (~i);
  51. }
  52. INSERT_WORDS(x,i0,i1);
  53. return x;
  54. }