xref: /freebsd/lib/msun/src/e_remainder.c (revision 02e9120893770924227138ba49df1edb3896112a)
1 
2 /*
3  * ====================================================
4  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
5  *
6  * Developed at SunSoft, 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 #include <sys/cdefs.h>
14 /* remainder(x,p)
15  * Return :
16  * 	returns  x REM p  =  x - [x/p]*p as if in infinite
17  * 	precise arithmetic, where [x/p] is the (infinite bit)
18  *	integer nearest x/p (in half way case choose the even one).
19  * Method :
20  *	Based on fmod() return x-[x/p]chopped*p exactlp.
21  */
22 
23 #include <float.h>
24 
25 #include "math.h"
26 #include "math_private.h"
27 
28 static const double zero = 0.0;
29 
30 
31 double
32 remainder(double x, double p)
33 {
34 	int32_t hx,hp;
35 	u_int32_t sx,lx,lp;
36 	double p_half;
37 
38 	EXTRACT_WORDS(hx,lx,x);
39 	EXTRACT_WORDS(hp,lp,p);
40 	sx = hx&0x80000000;
41 	hp &= 0x7fffffff;
42 	hx &= 0x7fffffff;
43 
44     /* purge off exception values */
45 	if(((hp|lp)==0)||		 	/* p = 0 */
46 	  (hx>=0x7ff00000)||			/* x not finite */
47 	  ((hp>=0x7ff00000)&&			/* p is NaN */
48 	  (((hp-0x7ff00000)|lp)!=0)))
49 	    return nan_mix_op(x, p, *)/nan_mix_op(x, p, *);
50 
51 
52 	if (hp<=0x7fdfffff) x = fmod(x,p+p);	/* now x < 2p */
53 	if (((hx-hp)|(lx-lp))==0) return zero*x;
54 	x  = fabs(x);
55 	p  = fabs(p);
56 	if (hp<0x00200000) {
57 	    if(x+x>p) {
58 		x-=p;
59 		if(x+x>=p) x -= p;
60 	    }
61 	} else {
62 	    p_half = 0.5*p;
63 	    if(x>p_half) {
64 		x-=p;
65 		if(x>=p_half) x -= p;
66 	    }
67 	}
68 	GET_HIGH_WORD(hx,x);
69 	if ((hx&0x7fffffff)==0) hx = 0;
70 	SET_HIGH_WORD(x,hx^sx);
71 	return x;
72 }
73 
74 #if LDBL_MANT_DIG == 53
75 __weak_reference(remainder, remainderl);
76 #endif
77