xref: /illumos-gate/usr/src/lib/libm/common/m9x/modf.c (revision 66582b606a8194f7f3ba5b3a3a6dca5b0d346361)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
24  */
25 /*
26  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
27  * Use is subject to license terms.
28  */
29 
30 #pragma weak modf = __modf
31 #pragma weak _modf = __modf
32 
33 /*
34  * modf(x, iptr) decomposes x into an integral part and a fractional
35  * part both having the same sign as x.  It stores the integral part
36  * in *iptr and returns the fractional part.
37  *
38  * If x is infinite, modf sets *iptr to x and returns copysign(0.0,x).
39  * If x is NaN, modf sets *iptr to x and returns x.
40  *
41  * If x is a signaling NaN, this code does not attempt to raise the
42  * invalid operation exception.
43  */
44 
45 #include "libm.h"
46 
47 double
48 __modf(double x, double *iptr) {
49 	union {
50 		unsigned i[2];
51 		double d;
52 	} xx, yy;
53 	unsigned hx, s;
54 
55 	xx.d = x;
56 	hx = xx.i[HIWORD] & ~0x80000000;
57 
58 	if (hx >= 0x43300000) {	/* x is NaN, infinite, or integral */
59 		*iptr = x;
60 		if (hx < 0x7ff00000 || (hx == 0x7ff00000 &&
61 			xx.i[LOWORD] == 0)) {
62 			xx.i[HIWORD] &= 0x80000000;
63 			xx.i[LOWORD] = 0;
64 		}
65 		return (xx.d);
66 	}
67 
68 	if (hx < 0x3ff00000) {	/* |x| < 1 */
69 		xx.i[HIWORD] &= 0x80000000;
70 		xx.i[LOWORD] = 0;
71 		*iptr = xx.d;
72 		return (x);
73 	}
74 
75 	/* split x at the binary point */
76 	s = xx.i[HIWORD] & 0x80000000;
77 	if (hx < 0x41400000) {
78 		yy.i[HIWORD] = xx.i[HIWORD] & ~((1 << (0x413 - (hx >> 20))) -
79 			1);
80 		yy.i[LOWORD] = 0;
81 	} else {
82 		yy.i[HIWORD] = xx.i[HIWORD];
83 		yy.i[LOWORD] = xx.i[LOWORD] & ~((1 << (0x433 - (hx >> 20))) -
84 			1);
85 	}
86 	*iptr = yy.d;
87 	xx.d -= yy.d;
88 	xx.i[HIWORD] = (xx.i[HIWORD] & ~0x80000000) | s;
89 							/* keep sign of x */
90 	return (xx.d);
91 }
92