1 /* $OpenBSD: s_csqrt.c,v 1.6 2013/07/03 04:46:36 espie Exp $ */
3 * Copyright (c) 2008 Stephen L. Moshier <steve@moshier.net>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 * double complex csqrt();
27 * double complex z, w;
36 * If z = x + iy, r = |z|, then
39 * Re w = [ (r + x)/2 ] ,
42 * Im w = [ (r - x)/2 ] .
44 * Cancellation error in r-x or r+x is avoided by using the
45 * identity 2 Re w Im w = y.
47 * Note that -w is also a square root of z. The root chosen
48 * is always in the right half plane and Im w has the same sign as y.
55 * arithmetic domain # trials peak rms
56 * DEC -10,+10 25000 3.2e-17 9.6e-18
57 * IEEE -10,+10 1,000,000 2.9e-16 6.1e-17
66 csqrt(double complex z)
69 double x, y, r, t, scale;
99 /* Rescale to avoid internal overflow or underflow. */
100 if ((fabs(x) > 4.0) || (fabs(y) > 4.0)) {
106 x *= 1.8014398509481984e16; /* 2^54 */
107 y *= 1.8014398509481984e16;
108 scale = 7.450580596923828125e-9; /* 2^-27 */
118 t = sqrt(0.5 * r + 0.5 * x);
119 r = scale * fabs((0.5 * y) / t);
123 r = sqrt( 0.5 * r - 0.5 * x );
124 t = scale * fabs( (0.5 * y) / r );
134 #if LDBL_MANT_DIG == DBL_MANT_DIG
135 __strong_alias(csqrtl, csqrt);
136 #endif /* LDBL_MANT_DIG == DBL_MANT_DIG */