xref: /freebsd/lib/msun/src/s_rint.c (revision 1e413cf93298b5b97441a21d9a50fdcd0ee9945e)
1 /* @(#)s_rint.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 #ifndef lint
14 static char rcsid[] = "$FreeBSD$";
15 #endif
16 
17 /*
18  * rint(x)
19  * Return x rounded to integral value according to the prevailing
20  * rounding mode.
21  * Method:
22  *	Using floating addition.
23  * Exception:
24  *	Inexact flag raised if x not equal to rint(x).
25  */
26 
27 #include <float.h>
28 
29 #include "math.h"
30 #include "math_private.h"
31 
32 static const double
33 TWO52[2]={
34   4.50359962737049600000e+15, /* 0x43300000, 0x00000000 */
35  -4.50359962737049600000e+15, /* 0xC3300000, 0x00000000 */
36 };
37 
38 double
39 rint(double x)
40 {
41 	int32_t i0,j0,sx;
42 	u_int32_t i,i1;
43 	double w,t;
44 	EXTRACT_WORDS(i0,i1,x);
45 	sx = (i0>>31)&1;
46 	j0 = ((i0>>20)&0x7ff)-0x3ff;
47 	if(j0<20) {
48 	    if(j0<0) {
49 		if(((i0&0x7fffffff)|i1)==0) return x;
50 		i1 |= (i0&0x0fffff);
51 		i0 &= 0xfffe0000;
52 		i0 |= ((i1|-i1)>>12)&0x80000;
53 		SET_HIGH_WORD(x,i0);
54 	        w = TWO52[sx]+x;
55 	        t =  w-TWO52[sx];
56 		GET_HIGH_WORD(i0,t);
57 		SET_HIGH_WORD(t,(i0&0x7fffffff)|(sx<<31));
58 	        return t;
59 	    } else {
60 		i = (0x000fffff)>>j0;
61 		if(((i0&i)|i1)==0) return x; /* x is integral */
62 		i>>=1;
63 		if(((i0&i)|i1)!=0) {
64 		    /*
65 		     * Some bit is set after the 0.5 bit.  To avoid the
66 		     * possibility of errors from double rounding in
67 		     * w = TWO52[sx]+x, adjust the 0.25 bit to a lower
68 		     * guard bit.  We do this for all j0<=51.  The
69 		     * adjustment is trickiest for j0==18 and j0==19
70 		     * since then it spans the word boundary.
71 		     */
72 		    if(j0==19) i1 = 0x40000000; else
73 		    if(j0==18) i1 = 0x80000000; else
74 		    i0 = (i0&(~i))|((0x20000)>>j0);
75 		}
76 	    }
77 	} else if (j0>51) {
78 	    if(j0==0x400) return x+x;	/* inf or NaN */
79 	    else return x;		/* x is integral */
80 	} else {
81 	    i = ((u_int32_t)(0xffffffff))>>(j0-20);
82 	    if((i1&i)==0) return x;	/* x is integral */
83 	    i>>=1;
84 	    if((i1&i)!=0) i1 = (i1&(~i))|((0x40000000)>>(j0-20));
85 	}
86 	INSERT_WORDS(x,i0,i1);
87 	*(volatile double *)&w = TWO52[sx]+x;	/* clip any extra precision */
88 	return w-TWO52[sx];
89 }
90 
91 #if (LDBL_MANT_DIG == 53)
92 __weak_reference(rint, rintl);
93 #endif
94