Numworks Epsilon  1.4.1
Graphing Calculator Operating System
e_sqrtf.c
Go to the documentation of this file.
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 
19 static const float one = 1.0, tiny=1.0e-30;
20 
21 float
22 sqrtf(float x)
23 {
24  float z;
25  int32_t sign = (int)0x80000000;
26  int32_t ix,s,q,m,t,i;
27  u_int32_t r;
28 
29  GET_FLOAT_WORD(ix,x);
30 
31  /* take care of Inf and NaN */
32  if((ix&0x7f800000)==0x7f800000) {
33  return x*x+x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf
34  sqrt(-inf)=sNaN */
35  }
36  /* take care of zero */
37  if(ix<=0) {
38  if((ix&(~sign))==0) return x;/* sqrt(+-0) = +-0 */
39  else if(ix<0)
40  return (x-x)/(x-x); /* sqrt(-ve) = sNaN */
41  }
42  /* normalize x */
43  m = (ix>>23);
44  if(m==0) { /* subnormal x */
45  for(i=0;(ix&0x00800000)==0;i++) ix<<=1;
46  m -= i-1;
47  }
48  m -= 127; /* unbias exponent */
49  ix = (ix&0x007fffff)|0x00800000;
50  if(m&1) /* odd m, double x to make it even */
51  ix += ix;
52  m >>= 1; /* m = [m/2] */
53 
54  /* generate sqrt(x) bit by bit */
55  ix += ix;
56  q = s = 0; /* q = sqrt(x) */
57  r = 0x01000000; /* r = moving bit from right to left */
58 
59  while(r!=0) {
60  t = s+r;
61  if(t<=ix) {
62  s = t+r;
63  ix -= t;
64  q += r;
65  }
66  ix += ix;
67  r>>=1;
68  }
69 
70  /* use floating add to find out rounding direction */
71  if(ix!=0) {
72  z = one-tiny; /* trigger inexact flag */
73  if (z>=one) {
74  z = one+tiny;
75  if (z>one)
76  q += 2;
77  else
78  q += (q&1);
79  }
80  }
81  ix = (q>>1)+0x3f000000;
82  ix += (m <<23);
83  SET_FLOAT_WORD(z,ix);
84  return z;
85 }
#define one
Definition: k_tan.c:68
uint32_t u_int32_t
Definition: types.h:10
#define SET_FLOAT_WORD(d, i)
Definition: math_private.h:335
#define GET_FLOAT_WORD(i, d)
Definition: math_private.h:326
float sqrtf(float x)
Definition: e_sqrtf.c:22
signed int int32_t
Definition: stdint.h:11