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