1 | /* ef_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 "fdlibm.h" |
---|
17 | |
---|
18 | #ifdef __STDC__ |
---|
19 | static const float one = 1.0, tiny=1.0e-30; |
---|
20 | #else |
---|
21 | static float one = 1.0, tiny=1.0e-30; |
---|
22 | #endif |
---|
23 | |
---|
24 | #ifdef __STDC__ |
---|
25 | float __ieee754_sqrtf(float x) |
---|
26 | #else |
---|
27 | float __ieee754_sqrtf(x) |
---|
28 | float x; |
---|
29 | #endif |
---|
30 | { |
---|
31 | float z; |
---|
32 | __uint32_t r,hx; |
---|
33 | __int32_t ix,s,q,m,t,i; |
---|
34 | |
---|
35 | GET_FLOAT_WORD(ix,x); |
---|
36 | hx = ix&0x7fffffff; |
---|
37 | |
---|
38 | /* take care of Inf and NaN */ |
---|
39 | if(!FLT_UWORD_IS_FINITE(hx)) |
---|
40 | return x*x+x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf |
---|
41 | sqrt(-inf)=sNaN */ |
---|
42 | /* take care of zero and -ves */ |
---|
43 | if(FLT_UWORD_IS_ZERO(hx)) return x;/* sqrt(+-0) = +-0 */ |
---|
44 | if(ix<0) return (x-x)/(x-x); /* sqrt(-ve) = sNaN */ |
---|
45 | |
---|
46 | /* normalize x */ |
---|
47 | m = (ix>>23); |
---|
48 | if(FLT_UWORD_IS_SUBNORMAL(hx)) { /* subnormal x */ |
---|
49 | for(i=0;(ix&0x00800000L)==0;i++) ix<<=1; |
---|
50 | m -= i-1; |
---|
51 | } |
---|
52 | m -= 127; /* unbias exponent */ |
---|
53 | ix = (ix&0x007fffffL)|0x00800000L; |
---|
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 = 0x01000000L; /* 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)+0x3f000000L; |
---|
86 | ix += (m <<23); |
---|
87 | SET_FLOAT_WORD(z,ix); |
---|
88 | return z; |
---|
89 | } |
---|