POK
e_sqrtf.c
1 /*
2  * POK header
3  *
4  * The following file is a part of the POK project. Any modification should
5  * made according to the POK licence. You CANNOT use this file or a part of
6  * this file is this part of a file for your own project
7  *
8  * For more information on the POK licence, please see our LICENCE FILE
9  *
10  * Please follow the coding guidelines described in doc/CODING_GUIDELINES
11  *
12  * Copyright (c) 2007-2009 POK team
13  *
14  * Created by julien on Fri Jan 30 14:41:34 2009
15  */
16 
17 /* e_sqrtf.c -- float version of e_sqrt.c.
18  * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com.
19  */
20 
21 /*
22  * ====================================================
23  * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
24  *
25  * Developed at SunPro, a Sun Microsystems, Inc. business.
26  * Permission to use, copy, modify, and distribute this
27  * software is freely granted, provided that this notice
28  * is preserved.
29  * ====================================================
30  */
31 
32 #ifdef POK_NEEDS_LIBMATH
33 #include <types.h>
34 #include "math_private.h"
35 
36 static const float one = 1.0, tiny=1.0e-30;
37 
38 float
39 __ieee754_sqrtf(float x)
40 {
41  float z;
42  int32_t sign = (int)0x80000000;
43  int32_t ix,s,q,m,t,i;
44  uint32_t r;
45 
46  GET_FLOAT_WORD(ix,x);
47 
48  /* take care of Inf and NaN */
49  if((ix&0x7f800000)==0x7f800000) {
50  return x*x+x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf
51  sqrt(-inf)=sNaN */
52  }
53  /* take care of zero */
54  if(ix<=0) {
55  if((ix&(~sign))==0) return x;/* sqrt(+-0) = +-0 */
56  else if(ix<0)
57  return (x-x)/(x-x); /* sqrt(-ve) = sNaN */
58  }
59  /* normalize x */
60  m = (ix>>23);
61  if(m==0) { /* subnormal x */
62  for(i=0;(ix&0x00800000)==0;i++) ix<<=1;
63  m -= i-1;
64  }
65  m -= 127; /* unbias exponent */
66  ix = (ix&0x007fffff)|0x00800000;
67  if(m&1) /* odd m, double x to make it even */
68  ix += ix;
69  m >>= 1; /* m = [m/2] */
70 
71  /* generate sqrt(x) bit by bit */
72  ix += ix;
73  q = s = 0; /* q = sqrt(x) */
74  r = 0x01000000; /* r = moving bit from right to left */
75 
76  while(r!=0) {
77  t = s+r;
78  if(t<=ix) {
79  s = t+r;
80  ix -= t;
81  q += r;
82  }
83  ix += ix;
84  r>>=1;
85  }
86 
87  /* use floating add to find out rounding direction */
88  if(ix!=0) {
89  z = one-tiny; /* trigger inexact flag */
90  if (z>=one) {
91  z = one+tiny;
92  if (z>one)
93  q += 2;
94  else
95  q += (q&1);
96  }
97  }
98  ix = (q>>1)+0x3f000000;
99  ix += (m <<23);
100  SET_FLOAT_WORD(z,ix);
101  return z;
102 }
103 #endif
104