e_remainder.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* @(#)e_remainder.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 char rcsid[] = "$NetBSD: e_remainder.c,v 1.8 1995/05/10 20:46:05 jtc Exp $";
  14. #endif
  15. /* __ieee754_remainder(x,p)
  16. * Return :
  17. * returns x REM p = x - [x/p]*p as if in infinite
  18. * precise arithmetic, where [x/p] is the (infinite bit)
  19. * integer nearest x/p (in half way case choose the even one).
  20. * Method :
  21. * Based on fmod() return x-[x/p]chopped*p exactlp.
  22. */
  23. #include "math.h"
  24. #include "math_private.h"
  25. #ifdef __STDC__
  26. static const double zero = 0.0;
  27. #else
  28. static double zero = 0.0;
  29. #endif
  30. #ifdef __STDC__
  31. double __ieee754_remainder(double x, double p)
  32. #else
  33. double __ieee754_remainder(x,p)
  34. double x,p;
  35. #endif
  36. {
  37. int32_t hx,hp;
  38. u_int32_t sx,lx,lp;
  39. double p_half;
  40. EXTRACT_WORDS(hx,lx,x);
  41. EXTRACT_WORDS(hp,lp,p);
  42. sx = hx&0x80000000;
  43. hp &= 0x7fffffff;
  44. hx &= 0x7fffffff;
  45. /* purge off exception values */
  46. if((hp|lp)==0) return (x*p)/(x*p); /* p = 0 */
  47. if((hx>=0x7ff00000)|| /* x not finite */
  48. ((hp>=0x7ff00000)&& /* p is NaN */
  49. (((hp-0x7ff00000)|lp)!=0)))
  50. return (x*p)/(x*p);
  51. if (hp<=0x7fdfffff) x = __ieee754_fmod(x,p+p); /* now x < 2p */
  52. if (((hx-hp)|(lx-lp))==0) return zero*x;
  53. x = fabs(x);
  54. p = fabs(p);
  55. if (hp<0x00200000) {
  56. if(x+x>p) {
  57. x-=p;
  58. if(x+x>=p) x -= p;
  59. }
  60. } else {
  61. p_half = 0.5*p;
  62. if(x>p_half) {
  63. x-=p;
  64. if(x>=p_half) x -= p;
  65. }
  66. }
  67. GET_HIGH_WORD(hx,x);
  68. SET_HIGH_WORD(x,hx^sx);
  69. return x;
  70. }