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