math: rewrite modf.c and clean up modff.c
[musl] / src / math / modf.c
1 #include <math.h>
2 #include <stdint.h>
3
4 double modf(double x, double *iptr)
5 {
6         union {double x; uint64_t n;} u = {x};
7         uint64_t mask;
8         int e;
9
10         e = (int)(u.n>>52 & 0x7ff) - 0x3ff;
11
12         /* no fractional part */
13         if (e >= 52) {
14                 *iptr = x;
15                 if (e == 0x400 && u.n<<12 != 0) /* nan */
16                         return x;
17                 u.n &= (uint64_t)1<<63;
18                 return u.x;
19         }
20
21         /* no integral part*/
22         if (e < 0) {
23                 u.n &= (uint64_t)1<<63;
24                 *iptr = u.x;
25                 return x;
26         }
27
28         mask = (uint64_t)-1>>12 >> e;
29         if ((u.n & mask) == 0) {
30                 *iptr = x;
31                 u.n &= (uint64_t)1<<63;
32                 return u.x;
33         }
34         u.n &= ~mask;
35         *iptr = u.x;
36         return x - *iptr;
37 }