rework langinfo code for ABI compat and for use by time code
[musl] / 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 double remainder(double x, double p)
24 {
25         int32_t hx,hp;
26         uint32_t sx,lx,lp;
27         double p_half;
28
29         EXTRACT_WORDS(hx, lx, x);
30         EXTRACT_WORDS(hp, lp, p);
31         sx = hx & 0x80000000;
32         hp &= 0x7fffffff;
33         hx &= 0x7fffffff;
34
35         /* purge off exception values */
36         if ((hp|lp) == 0 ||                                  /* p = 0 */
37             hx >= 0x7ff00000 ||                              /* x not finite */
38             (hp >= 0x7ff00000 && (hp-0x7ff00000 | lp) != 0)) /* p is NaN */
39                 return (x*p)/(x*p);
40
41         if (hp <= 0x7fdfffff)
42                 x = fmod(x, p+p);  /* now x < 2p */
43         if (((hx-hp)|(lx-lp)) == 0)
44                 return 0.0*x;
45         x = fabs(x);
46         p = fabs(p);
47         if (hp < 0x00200000) {
48                 if (x + x > p) {
49                         x -= p;
50                         if (x + x >= p)
51                                 x -= p;
52                 }
53         } else {
54                 p_half = 0.5*p;
55                 if (x > p_half) {
56                         x -= p;
57                         if (x >= p_half)
58                                 x -= p;
59                 }
60         }
61         GET_HIGH_WORD(hx, x);
62         if ((hx&0x7fffffff) == 0)
63                 hx = 0;
64         SET_HIGH_WORD(x, hx^sx);
65         return x;
66 }