1 /* Complex square root of double value.
2 Copyright (C) 1997-2012 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Based on an algorithm by Stephen L. Moshier <moshier@world.std.com>.
5 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
7 The GNU C Library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
12 The GNU C Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public
18 License along with the GNU C Library; if not, see
19 <http://www.gnu.org/licenses/>. */
23 #include <math_private.h>
27 __csqrt (__complex__ double x)
29 __complex__ double res;
30 int rcls = fpclassify (__real__ x);
31 int icls = fpclassify (__imag__ x);
33 if (__builtin_expect (rcls <= FP_INFINITE || icls <= FP_INFINITE, 0))
35 if (icls == FP_INFINITE)
37 __real__ res = HUGE_VAL;
38 __imag__ res = __imag__ x;
40 else if (rcls == FP_INFINITE)
44 __real__ res = icls == FP_NAN ? __nan ("") : 0;
45 __imag__ res = __copysign (HUGE_VAL, __imag__ x);
49 __real__ res = __real__ x;
50 __imag__ res = (icls == FP_NAN
51 ? __nan ("") : __copysign (0.0, __imag__ x));
56 __real__ res = __nan ("");
57 __imag__ res = __nan ("");
62 if (__builtin_expect (icls == FP_ZERO, 0))
67 __imag__ res = __copysign (__ieee754_sqrt (-__real__ x),
72 __real__ res = fabs (__ieee754_sqrt (__real__ x));
73 __imag__ res = __copysign (0.0, __imag__ x);
76 else if (__builtin_expect (rcls == FP_ZERO, 0))
78 double r = __ieee754_sqrt (0.5 * fabs (__imag__ x));
81 __imag__ res = __copysign (r, __imag__ x);
88 if (fabs (__real__ x) > DBL_MAX / 2.0
89 || fabs (__imag__ x) > DBL_MAX / 2.0)
92 __real__ x = __scalbn (__real__ x, -2 * scale);
93 __imag__ x = __scalbn (__imag__ x, -2 * scale);
95 else if (fabs (__real__ x) < DBL_MIN
96 && fabs (__imag__ x) < DBL_MIN)
98 scale = -(DBL_MANT_DIG / 2);
99 __real__ x = __scalbn (__real__ x, -2 * scale);
100 __imag__ x = __scalbn (__imag__ x, -2 * scale);
103 d = __ieee754_hypot (__real__ x, __imag__ x);
104 /* Use the identity 2 Re res Im res = Im x
105 to avoid cancellation error in d +/- Re x. */
108 r = __ieee754_sqrt (0.5 * d + 0.5 * __real__ x);
109 s = (0.5 * __imag__ x) / r;
113 s = __ieee754_sqrt (0.5 * d - 0.5 * __real__ x);
114 r = fabs ((0.5 * __imag__ x) / s);
119 r = __scalbn (r, scale);
120 s = __scalbn (s, scale);
124 __imag__ res = __copysign (s, __imag__ x);
130 weak_alias (__csqrt, csqrt)
131 #ifdef NO_LONG_DOUBLE
132 strong_alias (__csqrt, __csqrtl)
133 weak_alias (__csqrt, csqrtl)