xref: /freebsd/lib/msun/src/e_sqrtf.c (revision 62cfcf62f627e5093fb37026a6d8c98e4d2ef04c)
1 /* e_sqrtf.c -- float version of e_sqrt.c.
2  * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
3  */
4 
5 /*
6  * ====================================================
7  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
8  *
9  * Developed at SunPro, a Sun Microsystems, Inc. business.
10  * Permission to use, copy, modify, and distribute this
11  * software is freely granted, provided that this notice
12  * is preserved.
13  * ====================================================
14  */
15 
16 #ifndef lint
17 static char rcsid[] = "$FreeBSD$";
18 #endif
19 
20 #include "math.h"
21 #include "math_private.h"
22 
23 static	const float	one	= 1.0, tiny=1.0e-30;
24 
25 float
26 __ieee754_sqrtf(float x)
27 {
28 	float z;
29 	int32_t sign = (int)0x80000000;
30 	int32_t ix,s,q,m,t,i;
31 	u_int32_t r;
32 
33 	GET_FLOAT_WORD(ix,x);
34 
35     /* take care of Inf and NaN */
36 	if((ix&0x7f800000)==0x7f800000) {
37 	    return x*x+x;		/* sqrt(NaN)=NaN, sqrt(+inf)=+inf
38 					   sqrt(-inf)=sNaN */
39 	}
40     /* take care of zero */
41 	if(ix<=0) {
42 	    if((ix&(~sign))==0) return x;/* sqrt(+-0) = +-0 */
43 	    else if(ix<0)
44 		return (x-x)/(x-x);		/* sqrt(-ve) = sNaN */
45 	}
46     /* normalize x */
47 	m = (ix>>23);
48 	if(m==0) {				/* subnormal x */
49 	    for(i=0;(ix&0x00800000)==0;i++) ix<<=1;
50 	    m -= i-1;
51 	}
52 	m -= 127;	/* unbias exponent */
53 	ix = (ix&0x007fffff)|0x00800000;
54 	if(m&1)	/* odd m, double x to make it even */
55 	    ix += ix;
56 	m >>= 1;	/* m = [m/2] */
57 
58     /* generate sqrt(x) bit by bit */
59 	ix += ix;
60 	q = s = 0;		/* q = sqrt(x) */
61 	r = 0x01000000;		/* r = moving bit from right to left */
62 
63 	while(r!=0) {
64 	    t = s+r;
65 	    if(t<=ix) {
66 		s    = t+r;
67 		ix  -= t;
68 		q   += r;
69 	    }
70 	    ix += ix;
71 	    r>>=1;
72 	}
73 
74     /* use floating add to find out rounding direction */
75 	if(ix!=0) {
76 	    z = one-tiny; /* trigger inexact flag */
77 	    if (z>=one) {
78 	        z = one+tiny;
79 		if (z>one)
80 		    q += 2;
81 		else
82 		    q += (q&1);
83 	    }
84 	}
85 	ix = (q>>1)+0x3f000000;
86 	ix += (m <<23);
87 	SET_FLOAT_WORD(z,ix);
88 	return z;
89 }
90