xref: /openbsd-src/lib/libm/src/s_trunc.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /* @(#)s_floor.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 /* LINTLIBRARY */
14 
15 #if 0
16 #include <sys/cdefs.h>
17 __FBSDID("$FreeBSD: src/lib/msun/src/s_trunc.c,v 1.1 2004/06/20 09:25:43 das Exp $");
18 #endif
19 
20 /*
21  * trunc(x)
22  * Return x rounded toward 0 to integral value
23  * Method:
24  *	Bit twiddling.
25  * Exception:
26  *	Inexact flag raised if x not equal to trunc(x).
27  */
28 
29 #include <sys/cdefs.h>
30 #include <float.h>
31 #include <math.h>
32 
33 #include "math_private.h"
34 
35 static const double huge = 1.0e300;
36 
37 double
38 trunc(double x)
39 {
40 	int32_t i0,i1,jj0;
41 	u_int32_t i;
42 	EXTRACT_WORDS(i0,i1,x);
43 	jj0 = ((i0>>20)&0x7ff)-0x3ff;
44 	if(jj0<20) {
45 	    if(jj0<0) { 	/* raise inexact if x != 0 */
46 		if(huge+x>0.0) {/* |x|<1, so return 0*sign(x) */
47 		    i0 &= 0x80000000U;
48 		    i1 = 0;
49 		}
50 	    } else {
51 		i = (0x000fffff)>>jj0;
52 		if(((i0&i)|i1)==0) return x; /* x is integral */
53 		if(huge+x>0.0) {	/* raise inexact flag */
54 		    i0 &= (~i); i1=0;
55 		}
56 	    }
57 	} else if (jj0>51) {
58 	    if(jj0==0x400) return x+x;	/* inf or NaN */
59 	    else return x;		/* x is integral */
60 	} else {
61 	    i = ((u_int32_t)(0xffffffff))>>(jj0-20);
62 	    if((i1&i)==0) return x;	/* x is integral */
63 	    if(huge+x>0.0)		/* raise inexact flag */
64 		i1 &= (~i);
65 	}
66 	INSERT_WORDS(x,i0,i1);
67 	return x;
68 }
69 
70 #if	LDBL_MANT_DIG == 53
71 #ifdef	lint
72 /* PROTOLIB1 */
73 long double truncl(long double);
74 #else	/* lint */
75 __weak_alias(truncl, trunc);
76 #endif	/* lint */
77 #endif	/* LDBL_MANT_DIG == 53 */
78