2 /* @(#)e_fmod.c 1.3 95/01/18 */
4 * ====================================================
5 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
7 * Developed at SunSoft, a Sun Microsystems, Inc. business.
8 * Permission to use, copy, modify, and distribute this
9 * software is freely granted, provided that this notice
11 * ====================================================
16 * Return x mod y in exact arithmetic
17 * Method: shift and subtract
21 #include "math_private.h"
23 static const double one = 1.0, Zero[] = {0.0, -0.0,};
26 fmod(double x, double y)
28 int32_t n,hx,hy,hz,ix,iy,sx,i;
31 EXTRACT_WORDS(hx,lx,x);
32 EXTRACT_WORDS(hy,ly,y);
33 sx = hx&0x80000000; /* sign of x */
35 hy &= 0x7fffffff; /* |y| */
37 /* purge off exception values */
38 if((hy|ly)==0||(hx>=0x7ff00000)|| /* y=0,or x not finite */
39 ((hy|((ly|-ly)>>31))>0x7ff00000)) /* or y is NaN */
42 if((hx<hy)||(lx<ly)) return x; /* |x|<|y| return x */
44 return Zero[(uint32_t)sx>>31]; /* |x|=|y| return x*0*/
47 /* determine ix = ilogb(x) */
48 if(hx<0x00100000) { /* subnormal x */
50 for (ix = -1043, i=lx; i>0; i<<=1) ix -=1;
52 for (ix = -1022,i=(hx<<11); i>0; i<<=1) ix -=1;
54 } else ix = (hx>>20)-1023;
56 /* determine iy = ilogb(y) */
57 if(hy<0x00100000) { /* subnormal y */
59 for (iy = -1043, i=ly; i>0; i<<=1) iy -=1;
61 for (iy = -1022,i=(hy<<11); i>0; i<<=1) iy -=1;
63 } else iy = (hy>>20)-1023;
65 /* set up {hx,lx}, {hy,ly} and align y to x */
67 hx = 0x00100000|(0x000fffff&hx);
68 else { /* subnormal x, shift x to normal */
71 hx = (hx<<n)|(lx>>(32-n));
79 hy = 0x00100000|(0x000fffff&hy);
80 else { /* subnormal y, shift y to normal */
83 hy = (hy<<n)|(ly>>(32-n));
94 hz=hx-hy;lz=lx-ly; if(lx<ly) hz -= 1;
95 if(hz<0){hx = hx+hx+(lx>>31); lx = lx+lx;}
97 if((hz|lz)==0) /* return sign(x)*0 */
98 return Zero[(uint32_t)sx>>31];
99 hx = hz+hz+(lz>>31); lx = lz+lz;
102 hz=hx-hy;lz=lx-ly; if(lx<ly) hz -= 1;
103 if(hz>=0) {hx=hz;lx=lz;}
105 /* convert back to floating value and restore the sign */
106 if((hx|lx)==0) /* return sign(x)*0 */
107 return Zero[(uint32_t)sx>>31];
108 while(hx<0x00100000) { /* normalize x */
109 hx = hx+hx+(lx>>31); lx = lx+lx;
112 if(iy>= -1022) { /* normalize output */
113 hx = ((hx-0x00100000)|((iy+1023)<<20));
114 INSERT_WORDS(x,hx|sx,lx);
115 } else { /* subnormal output */
118 lx = (lx>>n)|((uint32_t)hx<<(32-n));
121 lx = (hx<<(32-n))|(lx>>n); hx = sx;
123 lx = hx>>(n-32); hx = sx;
125 INSERT_WORDS(x,hx|sx,lx);
126 x *= one; /* create necessary signal */
128 return x; /* exact output */