1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Copyright ©2017 The Gonum Authors. All rights reserved.
6 // Use of this source code is governed by a BSD-style
7 // license that can be found in the LICENSE file.
11 import math "gonum.org/v1/gonum/internal/math32"
13 // The original C code, the long comment, and the constants
14 // below are from http://netlib.sandia.gov/cephes/c9x-complex/clog.c.
15 // The go code is a simplified version of the original C.
17 // Cephes Math Library Release 2.8: June, 2000
18 // Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
20 // The readme file at http://netlib.sandia.gov/cephes/ says:
21 // Some software in this archive may be from the book _Methods and
22 // Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster
23 // International, 1989) or from the Cephes Mathematical Library, a
24 // commercial product. In either event, it is copyrighted by the author.
25 // What you see here may be used freely but it comes with no support or
28 // The two known misprints in the book are repaired here in the
29 // source listings for the gamma function and the incomplete beta
33 // moshier@na-net.ornl.gov
35 // Complex square root
39 // If z = x + iy, r = |z|, then
42 // Re w = [ (r + x)/2 ] ,
45 // Im w = [ (r - x)/2 ] .
47 // Cancelation error in r-x or r+x is avoided by using the
48 // identity 2 Re w Im w = y.
50 // Note that -w is also a square root of z. The root chosen
51 // is always in the right half plane and Im w has the same sign as y.
56 // arithmetic domain # trials peak rms
57 // DEC -10,+10 25000 3.2e-17 9.6e-18
58 // IEEE -10,+10 1,000,000 2.9e-16 6.1e-17
60 // Sqrt returns the square root of x.
61 // The result r is chosen so that real(r) ≥ 0 and imag(r) has the same sign as imag(x).
62 func Sqrt(x complex64) complex64 {
68 return complex(0, math.Sqrt(-real(x)))
70 return complex(math.Sqrt(real(x)), 0)
74 r := math.Sqrt(-0.5 * imag(x))
77 r := math.Sqrt(0.5 * imag(x))
83 // Rescale to avoid internal overflow or underflow.
84 if math.Abs(a) > 4 || math.Abs(b) > 4 {
89 a *= 1.8014398509481984e16 // 2**54
90 b *= 1.8014398509481984e16
91 scale = 7.450580596923828125e-9 // 2**-27
96 t = math.Sqrt(0.5*r + 0.5*a)
97 r = scale * math.Abs((0.5*b)/t)
100 r = math.Sqrt(0.5*r - 0.5*a)
101 t = scale * math.Abs((0.5*b)/r)
105 return complex(t, -r)