xref: /minix/lib/libm/src/s_modf.c (revision 0a6a1f1d)
1 /* @(#)s_modf.c 5.1 93/09/24 */
2 /*
3  * ====================================================
4  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
5  *
6  * Developed at SunPro, 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 #if defined(LIBM_SCCS) && !defined(lint)
15 __RCSID("$NetBSD: s_modf.c,v 1.15 2014/06/16 12:54:43 joerg Exp $");
16 #endif
17 
18 /*
19  * modf(double x, double *iptr)
20  * return fraction part of x, and return x's integral part in *iptr.
21  * Method:
22  *	Bit twiddling.
23  *
24  * Exception:
25  *	No exception.
26  */
27 
28 #include "math.h"
29 #include "math_private.h"
30 
31 static const double one = 1.0;
32 
33 #ifndef __HAVE_LONG_DOUBLE
__strong_alias(_modfl,modf)34 __strong_alias(_modfl, modf)
35 __weak_alias(modfl, modf)
36 #endif
37 
38 double
39 modf(double x, double *iptr)
40 {
41 	int32_t i0,i1,jj0;
42 	u_int32_t i;
43 	EXTRACT_WORDS(i0,i1,x);
44 	jj0 = (((uint32_t)i0>>20)&0x7ff)-0x3ff;	/* exponent of x */
45 	if(jj0<20) {			/* integer part in high x */
46 	    if(jj0<0) {			/* |x|<1 */
47 	        INSERT_WORDS(*iptr,i0&0x80000000,0);	/* *iptr = +-0 */
48 		return x;
49 	    } else {
50 		i = (0x000fffff)>>jj0;
51 		if(((i0&i)|i1)==0) {		/* x is integral */
52 		    u_int32_t high;
53 		    *iptr = x;
54 		    GET_HIGH_WORD(high,x);
55 		    INSERT_WORDS(x,high&0x80000000,0);	/* return +-0 */
56 		    return x;
57 		} else {
58 		    INSERT_WORDS(*iptr,i0&(~i),0);
59 		    return x - *iptr;
60 		}
61 	    }
62 	} else if (jj0>51) {		/* no fraction part */
63 	    u_int32_t high;
64 	    *iptr = x*one;
65 	    if (jj0 == 0x400)		/* +-inf or NaN */
66 		return 0.0 / x;		/* +-0 or NaN */
67 	    GET_HIGH_WORD(high,x);
68 	    INSERT_WORDS(x,high&0x80000000,0);	/* return +-0 */
69 	    return x;
70 	} else {			/* fraction part in low x */
71 	    i = ((u_int32_t)(0xffffffff))>>(jj0-20);
72 	    if((i1&i)==0) { 		/* x is integral */
73 	        u_int32_t high;
74 		*iptr = x;
75 		GET_HIGH_WORD(high,x);
76 		INSERT_WORDS(x,high&0x80000000,0);	/* return +-0 */
77 		return x;
78 	    } else {
79 	        INSERT_WORDS(*iptr,i0,i1&(~i));
80 		return x - *iptr;
81 	    }
82 	}
83 }
84