From: Robert Harley <Robert.Harley@inria.fr>
Subject: sqrt.c
Date: Sun, 21 Feb 1999 17:23:07 +0100 (MET) [thread overview]
Message-ID: <199902211623.RAA17291@pauillac.inria.fr> (raw)
[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #1: Type: text/plain, Size: 2352 bytes --]
/* > sqrt.c
* Purpose: Fast double precision square root.
* Copyright: (c) Robert J. Harley, 19-Oct-1998
* Contact: Robert.Harley@inria.fr
* Legalese: This code is subject to the GNU General Public License (v2).
*/
/*-- sqrt ---------------------------------------------------------------*/
double sqrt(double a) {
u64 ea, ua, ux, v, v2, w;
s64 wm, wp;
double b, t, x, z;
union { double d; u64 u; } du;
const double
sqrt2o2 = 0.70710678118654757273731092936941422522068023681640625
;
static const unsigned char tab[64] =
{ 127, 125, 123, 121, 119, 118, 116, 114, 113, 111, 109, 108, 106
, 105, 103, 102, 100, 99, 97, 96, 95, 93, 92, 91, 90, 88, 87, 86, 85
, 84, 83, 82, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 70, 69, 68
, 67, 66, 65, 64, 63, 63, 62, 61, 60, 59, 59, 58, 57, 56, 56, 55, 54, 53
};
/** Initial approximation to 1/sqrt(b) from table. **/
du.d = a; ua = du.u;
du.u = (u64)tab[ua>>46 & 63UL]<<45 | 1022UL<<52; x = du.d;
/* Nuke sign & exponent. */
du.u = ua<<12>>12 | 1022UL<<52; z = du.d;
/** Go out-of-line in rare cases (could do it earlier but faster here). **/
if ((s64)ua <= 0L) goto pm_zero_or_negative;
ea = ua>>52;
if (!ea) goto positive_denormal;
if (ea == 2047UL) goto pos_nan_or_inf;
/** Improve approximation to 1/sqrt(b) with Newton iterations. **/
b = z+z;
z *= x*x; t = 1.5-z; z *= t*t; x *= t; t = 1.5-z; x *= t;
/* Handle exponent parity. */
w = ua<<52;
if (!(ea & 1UL)) { b += b; x *= sqrt2o2; w = ua<<53; }
/** Final Newton iteration and multiply by b to get sqrt(b).. **/
t = b*x; x = t+0.5*x*(b-t*t);
/* Magic incantation to fix last bit. */
du.d = x; ux = du.u;
v = ux-(1022UL<<52); v2 = v*v;
ux += (((ea+1UL)>>1)-512UL)<<52; /* Insert exponent of result. */
wp = (s64)(w+v); wm = (s64)(w-v);
{ union { double d; u64 u; } dut[3];
dut[0].u = ux+1UL;
dut[1].u = ux;
dut[2].u = ux-1UL;
wp = (s64)v2-wp >= 0L;
wm = ((s64)v2-wm)>>63;
x = dut[1L+wp+wm].d;
} /* end block */
return x;
/* Junk for now. TO DO: put code for these cases in. */
pm_zero_or_negative:
positive_denormal:
pos_nan_or_inf:
return 0.0;
} /* end sqrt */
reply other threads:[~1999-02-21 16:23 UTC|newest]
Thread overview: [no followups] expand[flat|nested] mbox.gz Atom feed
read-only archive
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox