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