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 | #include <libm-alias-finite.h> |
19 | #include <math-use-builtins.h> |
20 | |
21 | float |
22 | __ieee754_sqrtf(float x) |
23 | { |
24 | #if USE_SQRTF_BUILTIN |
25 | return __builtin_sqrtf (x); |
26 | #else |
27 | /* Use generic implementation. */ |
28 | float z; |
29 | int32_t sign = (int)0x80000000; |
30 | int32_t ix,s,q,m,t,i; |
31 | uint32_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 = 0x1p0 - 0x1.4484cp-100; /* trigger inexact flag. */ |
77 | if (z >= 0x1p0) { |
78 | z = 0x1p0 + 0x1.4484cp-100; |
79 | if (z > 0x1p0) |
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 | #endif /* ! USE_SQRTF_BUILTIN */ |
90 | } |
91 | #ifndef __ieee754_sqrtf |
92 | libm_alias_finite (__ieee754_sqrtf, __sqrtf) |
93 | #endif |
94 | |