1 /* $OpenBSD: s_csqrtl.c,v 1.2 2011/07/20 19:28:33 martynas Exp $ */
4 * Copyright (c) 2008 Stephen L. Moshier <steve@moshier.net>
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
27 * long double complex csqrtl();
28 * long double complex z, w;
37 * If z = x + iy, r = |z|, then
40 * Re w = [ (r + x)/2 ] ,
43 * Im w = [ (r - x)/2 ] .
45 * Cancellation error in r-x or r+x is avoided by using the
46 * identity 2 Re w Im w = y.
48 * Note that -w is also a square root of z. The root chosen
49 * is always in the right half plane and Im w has the same sign as y.
56 * arithmetic domain # trials peak rms
57 * IEEE -10,+10 500000 1.1e-19 3.0e-20
65 csqrtl(long double complex z)
67 long double complex w;
68 long double x, y, r, t, scale;
75 w = 0.0L + sqrtl(-x) * I;
79 w = sqrtl(x) + 0.0L * I;
94 /* Rescale to avoid internal overflow or underflow. */
95 if ((fabsl(x) > 4.0L) || (fabsl(y) > 4.0L)) {
102 x *= 7.3786976294838206464e19; /* 2^66 */
103 y *= 7.3786976294838206464e19;
104 scale = 1.16415321826934814453125e-10; /* 2^-33 */
114 t = sqrtl(0.5L * r + 0.5L * x);
115 r = scale * fabsl((0.5L * y) / t);
119 r = sqrtl(0.5L * r - 0.5L * x);
120 t = scale * fabsl((0.5L * y) / r);