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 #if defined(LK) && ARCH_ARM && ARM_WITH_VFP
26 /* use ARM w/VFP sqrt instruction */
27 float
__ieee754_sqrtf(float x)28 __ieee754_sqrtf(float x)
29 {
30     float res;
31 
32     __asm__("vsqrt.f32 %0, %1" : "=t"(res) : "t"(x));
33 
34     return res;
35 }
36 
37 #else
38 
39 float
__ieee754_sqrtf(float x)40 __ieee754_sqrtf(float x)
41 {
42     float z;
43     int32_t sign = (int)0x80000000;
44     int32_t ix,s,q,m,t,i;
45     u_int32_t r;
46 
47     GET_FLOAT_WORD(ix,x);
48 
49     /* take care of Inf and NaN */
50     if ((ix&0x7f800000)==0x7f800000) {
51         return x*x+x;       /* sqrt(NaN)=NaN, sqrt(+inf)=+inf
52                        sqrt(-inf)=sNaN */
53     }
54     /* take care of zero */
55     if (ix<=0) {
56         if ((ix&(~sign))==0) return x; /* sqrt(+-0) = +-0 */
57         else if (ix<0)
58             return (x-x)/(x-x);     /* sqrt(-ve) = sNaN */
59     }
60     /* normalize x */
61     m = (ix>>23);
62     if (m==0) {             /* subnormal x */
63         for (i=0; (ix&0x00800000)==0; i++) ix<<=1;
64         m -= i-1;
65     }
66     m -= 127;   /* unbias exponent */
67     ix = (ix&0x007fffff)|0x00800000;
68     if (m&1) /* odd m, double x to make it even */
69         ix += ix;
70     m >>= 1;    /* m = [m/2] */
71 
72     /* generate sqrt(x) bit by bit */
73     ix += ix;
74     q = s = 0;      /* q = sqrt(x) */
75     r = 0x01000000;     /* r = moving bit from right to left */
76 
77     while (r!=0) {
78         t = s+r;
79         if (t<=ix) {
80             s    = t+r;
81             ix  -= t;
82             q   += r;
83         }
84         ix += ix;
85         r>>=1;
86     }
87 
88     /* use floating add to find out rounding direction */
89     if (ix!=0) {
90         z = one-tiny; /* trigger inexact flag */
91         if (z>=one) {
92             z = one+tiny;
93             if (z>one)
94                 q += 2;
95             else
96                 q += (q&1);
97         }
98     }
99     ix = (q>>1)+0x3f000000;
100     ix += (m <<23);
101     SET_FLOAT_WORD(z,ix);
102     return z;
103 }
104 
105 #endif
106 
107