xref: /freebsd/lib/msun/src/e_sqrtf.c (revision f5463265955b829775bbb32e1fd0bc11dafc36ce)
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 #include "math.h"
17 #include "math_private.h"
18 
19 #ifdef USE_BUILTIN_SQRTF
20 float
21 sqrtf(float x)
22 {
23 	return (__builtin_sqrtf(x));
24 }
25 #else
26 static	const float	one	= 1.0, tiny=1.0e-30;
27 
28 float
29 sqrtf(float x)
30 {
31 	float z;
32 	int32_t sign = (int)0x80000000;
33 	int32_t ix,s,q,m,t,i;
34 	u_int32_t r;
35 
36 	GET_FLOAT_WORD(ix,x);
37 
38     /* take care of Inf and NaN */
39 	if((ix&0x7f800000)==0x7f800000) {
40 	    return x*x+x;		/* sqrt(NaN)=NaN, sqrt(+inf)=+inf
41 					   sqrt(-inf)=sNaN */
42 	}
43     /* take care of zero */
44 	if(ix<=0) {
45 	    if((ix&(~sign))==0) return x;/* sqrt(+-0) = +-0 */
46 	    else if(ix<0)
47 		return (x-x)/(x-x);		/* sqrt(-ve) = sNaN */
48 	}
49     /* normalize x */
50 	m = (ix>>23);
51 	if(m==0) {				/* subnormal x */
52 	    for(i=0;(ix&0x00800000)==0;i++) ix<<=1;
53 	    m -= i-1;
54 	}
55 	m -= 127;	/* unbias exponent */
56 	ix = (ix&0x007fffff)|0x00800000;
57 	if(m&1)	/* odd m, double x to make it even */
58 	    ix += ix;
59 	m >>= 1;	/* m = [m/2] */
60 
61     /* generate sqrt(x) bit by bit */
62 	ix += ix;
63 	q = s = 0;		/* q = sqrt(x) */
64 	r = 0x01000000;		/* r = moving bit from right to left */
65 
66 	while(r!=0) {
67 	    t = s+r;
68 	    if(t<=ix) {
69 		s    = t+r;
70 		ix  -= t;
71 		q   += r;
72 	    }
73 	    ix += ix;
74 	    r>>=1;
75 	}
76 
77     /* use floating add to find out rounding direction */
78 	if(ix!=0) {
79 	    z = one-tiny; /* trigger inexact flag */
80 	    if (z>=one) {
81 	        z = one+tiny;
82 		if (z>one)
83 		    q += 2;
84 		else
85 		    q += (q&1);
86 	    }
87 	}
88 	ix = (q>>1)+0x3f000000;
89 	ix += (m <<23);
90 	SET_FLOAT_WORD(z,ix);
91 	return z;
92 }
93 #endif
94