001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.numbers.complex;
019
020import java.io.Serializable;
021import java.util.ArrayList;
022import java.util.List;
023import java.util.function.DoubleUnaryOperator;
024
025/**
026 * Cartesian representation of a complex number, i.e. a number which has both a
027 * real and imaginary part.
028 *
029 * <p>This class is immutable. All arithmetic will create a new instance for the
030 * result.</p>
031 *
032 * <p>Arithmetic in this class conforms to the C99 standard for complex numbers
033 * defined in ISO/IEC 9899, Annex G. Methods have been named using the equivalent
034 * method in ISO C99. The behavior for special cases is listed as defined in C99.</p>
035 *
036 * <p>For functions \( f \) which obey the conjugate equality \( conj(f(z)) = f(conj(z)) \),
037 * the specifications for the upper half-plane imply the specifications for the lower
038 * half-plane.</p>
039 *
040 * <p>For functions that are either odd, \( f(z) = -f(-z) \), or even, \( f(z) =  f(-z) \),
041 * the specifications for the first quadrant imply the specifications for the other three
042 * quadrants.</p>
043 *
044 * <p>Special cases of <a href="http://mathworld.wolfram.com/BranchCut.html">branch cuts</a>
045 * for multivalued functions adopt the principle value convention from C99. Specials cases
046 * from C99 that raise the "invalid" or "divide-by-zero"
047 * <a href="https://en.cppreference.com/w/c/numeric/fenv/FE_exceptions">floating-point
048 * exceptions</a> return the documented value without an explicit mechanism to notify
049 * of the exception case, that is no exceptions are thrown during computations in-line with
050 * the convention of the corresponding single-valued functions in
051 * {@link java.lang.Math java.lang.Math}.
052 * These cases are documented in the method special cases as "invalid" or "divide-by-zero"
053 * floating-point operation.
054 * Note: Invalid floating-point exception cases will result in a complex number where the
055 * cardinality of NaN component parts has increased as a real or imaginary part could
056 * not be computed and is set to NaN.
057 *
058 * @see <a href="http://www.open-std.org/JTC1/SC22/WG14/www/standards">
059 *    ISO/IEC 9899 - Programming languages - C</a>
060 */
061public final class Complex implements Serializable  {
062    /**
063     * A complex number representing \( i \), the square root of \( -1 \).
064     *
065     * <p>\( (0 + i 1) \).
066     */
067    public static final Complex I = new Complex(0, 1);
068    /**
069     * A complex number representing one.
070     *
071     * <p>\( (1 + i 0) \).
072     */
073    public static final Complex ONE = new Complex(1, 0);
074    /**
075     * A complex number representing zero.
076     *
077     * <p>\( (0 + i 0) \).
078     */
079    public static final Complex ZERO = new Complex(0, 0);
080
081    /** A complex number representing {@code NaN + i NaN}. */
082    private static final Complex NAN = new Complex(Double.NaN, Double.NaN);
083    /** &pi;/2. */
084    private static final double PI_OVER_2 = 0.5 * Math.PI;
085    /** &pi;/4. */
086    private static final double PI_OVER_4 = 0.25 * Math.PI;
087    /** Natural logarithm of 2 (ln(2)). */
088    private static final double LN_2 = Math.log(2);
089    /** Base 10 logarithm of 10 divided by 2 (log10(e)/2). */
090    private static final double LOG_10E_O_2 = Math.log10(Math.E) / 2;
091    /** Base 10 logarithm of 2 (log10(2)). */
092    private static final double LOG10_2 = Math.log10(2);
093    /** {@code 1/2}. */
094    private static final double HALF = 0.5;
095    /** {@code sqrt(2)}. */
096    private static final double ROOT2 = 1.4142135623730951;
097    /** {@code 1.0 / sqrt(2)}.
098     * This is pre-computed to the closest double from the exact result.
099     * It is 1 ULP different from 1.0 / Math.sqrt(2) but equal to Math.sqrt(2) / 2.
100     */
101    private static final double ONE_OVER_ROOT2 = 0.7071067811865476;
102    /** The bit representation of {@code -0.0}. */
103    private static final long NEGATIVE_ZERO_LONG_BITS = Double.doubleToLongBits(-0.0);
104    /** Exponent offset in IEEE754 representation. */
105    private static final int EXPONENT_OFFSET = 1023;
106    /**
107     * Largest double-precision floating-point number such that
108     * {@code 1 + EPSILON} is numerically equal to 1. This value is an upper
109     * bound on the relative error due to rounding real numbers to double
110     * precision floating-point numbers.
111     *
112     * <p>In IEEE 754 arithmetic, this is 2<sup>-53</sup>.
113     * Copied from o.a.c.numbers.Precision.
114     *
115     * @see <a href="http://en.wikipedia.org/wiki/Machine_epsilon">Machine epsilon</a>
116     */
117    private static final double EPSILON = Double.longBitsToDouble((EXPONENT_OFFSET - 53L) << 52);
118    /** Mask to remove the sign bit from a long. */
119    private static final long UNSIGN_MASK = 0x7fff_ffff_ffff_ffffL;
120    /** Mask to extract the 52-bit mantissa from a long representation of a double. */
121    private static final long MANTISSA_MASK = 0x000f_ffff_ffff_ffffL;
122    /** The multiplier used to split the double value into hi and low parts. This must be odd
123     * and a value of 2^s + 1 in the range {@code p/2 <= s <= p-1} where p is the number of
124     * bits of precision of the floating point number. Here {@code s = 27}.*/
125    private static final double MULTIPLIER = 1.34217729E8;
126
127    /**
128     * Crossover point to switch computation for asin/acos factor A.
129     * This has been updated from the 1.5 value used by Hull et al to 10
130     * as used in boost::math::complex.
131     * @see <a href="https://svn.boost.org/trac/boost/ticket/7290">Boost ticket 7290</a>
132     */
133    private static final double A_CROSSOVER = 10.0;
134    /** Crossover point to switch computation for asin/acos factor B. */
135    private static final double B_CROSSOVER = 0.6471;
136    /**
137     * The safe maximum double value {@code x} to avoid loss of precision in asin/acos.
138     * Equal to sqrt(M) / 8 in Hull, et al (1997) with M the largest normalised floating-point value.
139     */
140    private static final double SAFE_MAX = Math.sqrt(Double.MAX_VALUE) / 8;
141    /**
142     * The safe minimum double value {@code x} to avoid loss of precision/underflow in asin/acos.
143     * Equal to sqrt(u) * 4 in Hull, et al (1997) with u the smallest normalised floating-point value.
144     */
145    private static final double SAFE_MIN = Math.sqrt(Double.MIN_NORMAL) * 4;
146    /**
147     * The safe maximum double value {@code x} to avoid loss of precision in atanh.
148     * Equal to sqrt(M) / 2 with M the largest normalised floating-point value.
149     */
150    private static final double SAFE_UPPER = Math.sqrt(Double.MAX_VALUE) / 2;
151    /**
152     * The safe minimum double value {@code x} to avoid loss of precision/underflow in atanh.
153     * Equal to sqrt(u) * 2 with u the smallest normalised floating-point value.
154     */
155    private static final double SAFE_LOWER = Math.sqrt(Double.MIN_NORMAL) * 2;
156    /** The safe maximum double value {@code x} to avoid overflow in sqrt. */
157    private static final double SQRT_SAFE_UPPER = Double.MAX_VALUE / 8;
158    /**
159     * A safe maximum double value {@code m} where {@code e^m} is not infinite.
160     * This can be used when functions require approximations of sinh(x) or cosh(x)
161     * when x is large using exp(x):
162     * <pre>
163     * sinh(x) = (e^x - e^-x) / 2 = sign(x) * e^|x| / 2
164     * cosh(x) = (e^x + e^-x) / 2 = e^|x| / 2 </pre>
165     *
166     * <p>This value can be used to approximate e^x using a product:
167     *
168     * <pre>
169     * e^x = product_n (e^m) * e^(x-nm)
170     * n = (int) x/m
171     * e.g. e^2000 = e^m * e^m * e^(2000 - 2m) </pre>
172     *
173     * <p>The value should be below ln(max_value) ~ 709.783.
174     * The value m is set to an integer for less error when subtracting m and chosen as
175     * even (m=708) as it is used as a threshold in tanh with m/2.
176     *
177     * <p>The value is used to compute e^x multiplied by a small number avoiding
178     * overflow (sinh/cosh) or a small number divided by e^x without underflow due to
179     * infinite e^x (tanh). The following conditions are used:
180     * <pre>
181     * 0.5 * e^m * Double.MIN_VALUE * e^m * e^m = Infinity
182     * 2.0 / e^m / e^m = 0.0 </pre>
183     */
184    private static final double SAFE_EXP = 708;
185    /**
186     * The value of Math.exp(SAFE_EXP): e^708.
187     * To be used in overflow/underflow safe products of e^m to approximate e^x where x > m.
188     */
189    private static final double EXP_M = Math.exp(SAFE_EXP);
190
191    /** 54 shifted 20-bits to align with the exponent of the upper 32-bits of a double. */
192    private static final int EXP_54 = 0x36_00000;
193    /** Represents an exponent of 500 in unbiased form shifted 20-bits to align with the upper 32-bits of a double. */
194    private static final int EXP_500 = 0x5f3_00000;
195    /** Represents an exponent of 1024 in unbiased form (infinite or nan)
196     * shifted 20-bits to align with the upper 32-bits of a double. */
197    private static final int EXP_1024 = 0x7ff_00000;
198    /** Represents an exponent of -500 in unbiased form shifted 20-bits to align with the upper 32-bits of a double. */
199    private static final int EXP_NEG_500 = 0x20b_00000;
200    /** 2^600. */
201    private static final double TWO_POW_600 = 0x1.0p+600;
202    /** 2^-600. */
203    private static final double TWO_POW_NEG_600 = 0x1.0p-600;
204
205    /** Serializable version identifier. */
206    private static final long serialVersionUID = 20180201L;
207
208    /**
209     * The size of the buffer for {@link #toString()}.
210     *
211     * <p>The longest double will require a sign, a maximum of 17 digits, the decimal place
212     * and the exponent, e.g. for max value this is 24 chars: -1.7976931348623157e+308.
213     * Set the buffer size to twice this and round up to a power of 2 thus
214     * allowing for formatting characters. The size is 64.
215     */
216    private static final int TO_STRING_SIZE = 64;
217    /** The minimum number of characters in the format. This is 5, e.g. {@code "(0,0)"}. */
218    private static final int FORMAT_MIN_LEN = 5;
219    /** {@link #toString() String representation}. */
220    private static final char FORMAT_START = '(';
221    /** {@link #toString() String representation}. */
222    private static final char FORMAT_END = ')';
223    /** {@link #toString() String representation}. */
224    private static final char FORMAT_SEP = ',';
225    /** The minimum number of characters before the separator. This is 2, e.g. {@code "(0"}. */
226    private static final int BEFORE_SEP = 2;
227
228    /** The imaginary part. */
229    private final double imaginary;
230    /** The real part. */
231    private final double real;
232
233    /**
234     * Define a constructor for a Complex.
235     * This is used in functions that implement trigonomic identities.
236     */
237    @FunctionalInterface
238    private interface ComplexConstructor {
239        /**
240         * Create a complex number given the real and imaginary parts.
241         *
242         * @param real Real part.
243         * @param imaginary Imaginary part.
244         * @return {@code Complex} object.
245         */
246        Complex create(double real, double imaginary);
247    }
248
249    /**
250     * Private default constructor.
251     *
252     * @param real Real part.
253     * @param imaginary Imaginary part.
254     */
255    private Complex(double real, double imaginary) {
256        this.real = real;
257        this.imaginary = imaginary;
258    }
259
260    /**
261     * Create a complex number given the real and imaginary parts.
262     *
263     * @param real Real part.
264     * @param imaginary Imaginary part.
265     * @return {@code Complex} number.
266     */
267    public static Complex ofCartesian(double real, double imaginary) {
268        return new Complex(real, imaginary);
269    }
270
271    /**
272     * Creates a complex number from its polar representation using modulus {@code rho} (\( \rho \))
273     * and phase angle {@code theta} (\( \theta \)).
274     *
275     * \[ x = \rho \cos(\theta) \\
276     *    y = \rho \sin(\theta) \]
277     *
278     * <p>Requires that {@code rho} is non-negative and non-NaN and {@code theta} is finite;
279     * otherwise returns a complex with NaN real and imaginary parts. A {@code rho} value of
280     * {@code -0.0} is considered negative and an invalid modulus.
281     *
282     * <p>A non-NaN complex number constructed using this method will satisfy the following
283     * to within floating-point error when {@code theta} is in the range
284     * \( -\pi\ \lt \theta \leq \pi \):
285     *
286     * <pre>
287     *  Complex.ofPolar(rho, theta).abs() == rho
288     *  Complex.ofPolar(rho, theta).arg() == theta</pre>
289     *
290     * <p>If {@code rho} is infinite then the resulting parts may be infinite or NaN
291     * following the rules for double arithmetic, for example:</p>
292     *
293     * <ul>
294     * <li>{@code ofPolar(}\( -0.0 \){@code , }\( 0 \){@code ) = }\( \text{NaN} + i \text{NaN} \)
295     * <li>{@code ofPolar(}\( 0.0 \){@code , }\( 0 \){@code ) = }\( 0 + i 0 \)
296     * <li>{@code ofPolar(}\( 1 \){@code , }\( 0 \){@code ) = }\( 1 + i 0 \)
297     * <li>{@code ofPolar(}\( 1 \){@code , }\( \pi \){@code ) = }\( -1 + i \sin(\pi) \)
298     * <li>{@code ofPolar(}\( \infty \){@code , }\( \pi \){@code ) = }\( -\infty + i \infty \)
299     * <li>{@code ofPolar(}\( \infty \){@code , }\( 0 \){@code ) = }\( -\infty + i \text{NaN} \)
300     * <li>{@code ofPolar(}\( \infty \){@code , }\( -\frac{\pi}{4} \){@code ) = }\( \infty - i \infty \)
301     * <li>{@code ofPolar(}\( \infty \){@code , }\( 5\frac{\pi}{4} \){@code ) = }\( -\infty - i \infty \)
302     * </ul>
303     *
304     * <p>This method is the functional equivalent of the C++ method {@code std::polar}.
305     *
306     * @param rho The modulus of the complex number.
307     * @param theta The argument of the complex number.
308     * @return {@code Complex} number.
309     * @see <a href="http://mathworld.wolfram.com/PolarCoordinates.html">Polar Coordinates</a>
310     */
311    public static Complex ofPolar(double rho, double theta) {
312        // Require finite theta and non-negative, non-nan rho
313        if (!Double.isFinite(theta) || negative(rho) || Double.isNaN(rho)) {
314            return NAN;
315        }
316        final double x = rho * Math.cos(theta);
317        final double y = rho * Math.sin(theta);
318        return new Complex(x, y);
319    }
320
321    /**
322     * Create a complex cis number. This is also known as the complex exponential:
323     *
324     * \[ \text{cis}(x) = e^{ix} = \cos(x) + i \sin(x) \]
325     *
326     * @param x {@code double} to build the cis number.
327     * @return {@code Complex} cis number.
328     * @see <a href="http://mathworld.wolfram.com/Cis.html">Cis</a>
329     */
330    public static Complex ofCis(double x) {
331        return new Complex(Math.cos(x), Math.sin(x));
332    }
333
334    /**
335     * Returns a {@code Complex} instance representing the specified string {@code s}.
336     *
337     * <p>If {@code s} is {@code null}, then a {@code NullPointerException} is thrown.
338     *
339     * <p>The string must be in a format compatible with that produced by
340     * {@link #toString() Complex.toString()}.
341     * The format expects a start and end parentheses surrounding two numeric parts split
342     * by a separator. Leading and trailing spaces are allowed around each numeric part.
343     * Each numeric part is parsed using {@link Double#parseDouble(String)}. The parts
344     * are interpreted as the real and imaginary parts of the complex number.
345     *
346     * <p>Examples of valid strings and the equivalent {@code Complex} are shown below:
347     *
348     * <pre>
349     * "(0,0)"             = Complex.ofCartesian(0, 0)
350     * "(0.0,0.0)"         = Complex.ofCartesian(0, 0)
351     * "(-0.0, 0.0)"       = Complex.ofCartesian(-0.0, 0)
352     * "(-1.23, 4.56)"     = Complex.ofCartesian(-1.23, 4.56)
353     * "(1e300,-1.1e-2)"   = Complex.ofCartesian(1e300, -1.1e-2)</pre>
354     *
355     * @param s String representation.
356     * @return {@code Complex} number.
357     * @throws NullPointerException if the string is null.
358     * @throws NumberFormatException if the string does not contain a parsable complex number.
359     * @see Double#parseDouble(String)
360     * @see #toString()
361     */
362    public static Complex parse(String s) {
363        final int len = s.length();
364        if (len < FORMAT_MIN_LEN) {
365            throw new NumberFormatException(
366                parsingExceptionMsg("Input too short, expected format",
367                                    FORMAT_START + "x" + FORMAT_SEP + "y" + FORMAT_END, s));
368        }
369
370        // Confirm start: '('
371        if (s.charAt(0) != FORMAT_START) {
372            throw new NumberFormatException(
373                parsingExceptionMsg("Expected start delimiter", FORMAT_START, s));
374        }
375
376        // Confirm end: ')'
377        if (s.charAt(len - 1) != FORMAT_END) {
378            throw new NumberFormatException(
379                parsingExceptionMsg("Expected end delimiter", FORMAT_END, s));
380        }
381
382        // Confirm separator ',' is between at least 2 characters from
383        // either end: "(x,x)"
384        // Count back from the end ignoring the last 2 characters.
385        final int sep = s.lastIndexOf(FORMAT_SEP, len - 3);
386        if (sep < BEFORE_SEP) {
387            throw new NumberFormatException(
388                parsingExceptionMsg("Expected separator between two numbers", FORMAT_SEP, s));
389        }
390
391        // Should be no more separators
392        if (s.indexOf(FORMAT_SEP, sep + 1) != -1) {
393            throw new NumberFormatException(
394                parsingExceptionMsg("Incorrect number of parts, expected only 2 using separator",
395                                    FORMAT_SEP, s));
396        }
397
398        // Try to parse the parts
399
400        final String rePart = s.substring(1, sep);
401        final double re;
402        try {
403            re = Double.parseDouble(rePart);
404        } catch (final NumberFormatException ex) {
405            throw new NumberFormatException(
406                parsingExceptionMsg("Could not parse real part", rePart, s));
407        }
408
409        final String imPart = s.substring(sep + 1, len - 1);
410        final double im;
411        try {
412            im = Double.parseDouble(imPart);
413        } catch (final NumberFormatException ex) {
414            throw new NumberFormatException(
415                parsingExceptionMsg("Could not parse imaginary part", imPart, s));
416        }
417
418        return ofCartesian(re, im);
419    }
420
421    /**
422     * Creates an exception message.
423     *
424     * @param message Message prefix.
425     * @param error Input that caused the error.
426     * @param s String representation.
427     * @return A message.
428     */
429    private static String parsingExceptionMsg(String message,
430                                              Object error,
431                                              String s) {
432        final StringBuilder sb = new StringBuilder(100)
433            .append(message)
434            .append(" '").append(error)
435            .append("' for input \"").append(s).append('"');
436        return sb.toString();
437    }
438
439    /**
440     * Gets the real part \( a \) of this complex number \( (a + i b) \).
441     *
442     * @return The real part.
443     */
444    public double getReal() {
445        return real;
446    }
447
448    /**
449     * Gets the real part \( a \) of this complex number \( (a + i b) \).
450     *
451     * <p>This method is the equivalent of the C++ method {@code std::complex::real}.
452     *
453     * @return The real part.
454     * @see #getReal()
455     */
456    public double real() {
457        return getReal();
458    }
459
460    /**
461     * Gets the imaginary part \( b \) of this complex number \( (a + i b) \).
462     *
463     * @return The imaginary part.
464     */
465    public double getImaginary() {
466        return imaginary;
467    }
468
469    /**
470     * Gets the imaginary part \( b \) of this complex number \( (a + i b) \).
471     *
472     * <p>This method is the equivalent of the C++ method {@code std::complex::imag}.
473     *
474     * @return The imaginary part.
475     * @see #getImaginary()
476     */
477    public double imag() {
478        return getImaginary();
479    }
480
481    /**
482     * Returns the absolute value of this complex number. This is also called complex norm, modulus,
483     * or magnitude.
484     *
485     * <p>\[ \text{abs}(x + i y) = \sqrt{(x^2 + y^2)} \]
486     *
487     * <p>Special cases:
488     *
489     * <ul>
490     * <li>{@code abs(x + iy) == abs(y + ix) == abs(x - iy)}.
491     * <li>If {@code z} is ±∞ + iy for any y, returns +∞.
492     * <li>If {@code z} is x + iNaN for non-infinite x, returns NaN.
493     * <li>If {@code z} is x + i0, returns |x|.
494     * </ul>
495     *
496     * <p>The cases ensure that if either component is infinite then the result is positive
497     * infinity. If either component is NaN and this is not {@link #isInfinite() infinite} then
498     * the result is NaN.
499     *
500     * <p>This method follows the
501     * <a href="http://www.iso-9899.info/wiki/The_Standard">ISO C Standard</a>, Annex G,
502     * in calculating the returned value without intermediate overflow or underflow.
503     *
504     * <p>The computed result will be within 1 ulp of the exact result.
505     *
506     * @return The absolute value.
507     * @see #isInfinite()
508     * @see #isNaN()
509     * @see <a href="http://mathworld.wolfram.com/ComplexModulus.html">Complex modulus</a>
510     */
511    public double abs() {
512        return abs(real, imaginary);
513    }
514
515    /**
516     * Returns the absolute value of the complex number.
517     * <pre>abs(x + i y) = sqrt(x^2 + y^2)</pre>
518     *
519     * <p>This should satisfy the special cases of the hypot function in ISO C99 F.9.4.3:
520     * "The hypot functions compute the square root of the sum of the squares of x and y,
521     * without undue overflow or underflow."
522     *
523     * <ul>
524     * <li>hypot(x, y), hypot(y, x), and hypot(x, −y) are equivalent.
525     * <li>hypot(x, ±0) is equivalent to |x|.
526     * <li>hypot(±∞, y) returns +∞, even if y is a NaN.
527     * </ul>
528     *
529     * <p>This method is called by all methods that require the absolute value of the complex
530     * number, e.g. abs(), sqrt() and log().
531     *
532     * @param real Real part.
533     * @param imaginary Imaginary part.
534     * @return The absolute value.
535     */
536    private static double abs(double real, double imaginary) {
537        // Specialised implementation of hypot.
538        // See NUMBERS-143
539        return hypot(real, imaginary);
540    }
541
542    /**
543     * Returns the argument of this complex number.
544     *
545     * <p>The argument is the angle phi between the positive real axis and
546     * the point representing this number in the complex plane.
547     * The value returned is between \( -\pi \) (not inclusive)
548     * and \( \pi \) (inclusive), with negative values returned for numbers with
549     * negative imaginary parts.
550     *
551     * <p>If either real or imaginary part (or both) is NaN, then the result is NaN.
552     * Infinite parts are handled as {@linkplain Math#atan2} handles them,
553     * essentially treating finite parts as zero in the presence of an
554     * infinite coordinate and returning a multiple of \( \frac{\pi}{4} \) depending on
555     * the signs of the infinite parts.
556     *
557     * <p>This code follows the
558     * <a href="http://www.iso-9899.info/wiki/The_Standard">ISO C Standard</a>, Annex G,
559     * in calculating the returned value using the {@code atan2(y, x)} method for complex
560     * \( x + iy \).
561     *
562     * @return The argument of this complex number.
563     * @see Math#atan2(double, double)
564     */
565    public double arg() {
566        // Delegate
567        return Math.atan2(imaginary, real);
568    }
569
570    /**
571     * Returns the squared norm value of this complex number. This is also called the absolute
572     * square.
573     *
574     * <p>\[ \text{norm}(x + i y) = x^2 + y^2 \]
575     *
576     * <p>If either component is infinite then the result is positive infinity. If either
577     * component is NaN and this is not {@link #isInfinite() infinite} then the result is NaN.
578     *
579     * <p>Note: This method may not return the same value as the square of {@link #abs()} as
580     * that method uses an extended precision computation.
581     *
582     * <p>{@code norm()} can be used as a faster alternative than {@code abs()} for ranking by
583     * magnitude. If used for ranking any overflow to infinity will create an equal ranking for
584     * values that may be still distinguished by {@code abs()}.
585     *
586     * @return The square norm value.
587     * @see #isInfinite()
588     * @see #isNaN()
589     * @see #abs()
590     * @see <a href="http://mathworld.wolfram.com/AbsoluteSquare.html">Absolute square</a>
591     */
592    public double norm() {
593        if (isInfinite()) {
594            return Double.POSITIVE_INFINITY;
595        }
596        return real * real + imaginary * imaginary;
597    }
598
599    /**
600     * Returns {@code true} if either the real <em>or</em> imaginary component of the complex number is NaN
601     * <em>and</em> the complex number is not infinite.
602     *
603     * <p>Note that:
604     * <ul>
605     *   <li>There is more than one complex number that can return {@code true}.
606     *   <li>Different representations of NaN can be distinguished by the
607     *       {@link #equals(Object) Complex.equals(Object)} method.
608     * </ul>
609     *
610     * @return {@code true} if this instance contains NaN and no infinite parts.
611     * @see Double#isNaN(double)
612     * @see #isInfinite()
613     * @see #equals(Object) Complex.equals(Object)
614     */
615    public boolean isNaN() {
616        if (Double.isNaN(real) || Double.isNaN(imaginary)) {
617            return !isInfinite();
618        }
619        return false;
620    }
621
622    /**
623     * Returns {@code true} if either real or imaginary component of the complex number is infinite.
624     *
625     * <p>Note: A complex number with at least one infinite part is regarded
626     * as an infinity (even if its other part is a NaN).
627     *
628     * @return {@code true} if this instance contains an infinite value.
629     * @see Double#isInfinite(double)
630     */
631    public boolean isInfinite() {
632        return Double.isInfinite(real) || Double.isInfinite(imaginary);
633    }
634
635    /**
636     * Returns {@code true} if both real and imaginary component of the complex number are finite.
637     *
638     * @return {@code true} if this instance contains finite values.
639     * @see Double#isFinite(double)
640     */
641    public boolean isFinite() {
642        return Double.isFinite(real) && Double.isFinite(imaginary);
643    }
644
645    /**
646     * Returns the
647     * <a href="http://mathworld.wolfram.com/ComplexConjugate.html">conjugate</a>
648     * \( \overline{z} \) of this complex number \( z \).
649     *
650     * <p>\[ z           = a + i b \\
651     *      \overline{z} = a - i b \]
652     *
653     * @return The conjugate (\( \overline{z} \)) of this complex number.
654     */
655    public Complex conj() {
656        return new Complex(real, -imaginary);
657    }
658
659    /**
660     * Returns a {@code Complex} whose value is the negation of both the real and imaginary parts
661     * of complex number \( z \).
662     *
663     * <p>\[ z  =  a + i b \\
664     *      -z  = -a - i b \]
665     *
666     * @return \( -z \).
667     */
668    public Complex negate() {
669        return new Complex(-real, -imaginary);
670    }
671
672    /**
673     * Returns the projection of this complex number onto the Riemann sphere.
674     *
675     * <p>\( z \) projects to \( z \), except that all complex infinities (even those
676     * with one infinite part and one NaN part) project to positive infinity on the real axis.
677     *
678     * If \( z \) has an infinite part, then {@code z.proj()} shall be equivalent to:
679     *
680     * <pre>return Complex.ofCartesian(Double.POSITIVE_INFINITY, Math.copySign(0.0, z.imag());</pre>
681     *
682     * @return \( z \) projected onto the Riemann sphere.
683     * @see #isInfinite()
684     * @see <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/cproj.html">
685     * IEEE and ISO C standards: cproj</a>
686     */
687    public Complex proj() {
688        if (isInfinite()) {
689            return new Complex(Double.POSITIVE_INFINITY, Math.copySign(0.0, imaginary));
690        }
691        return this;
692    }
693
694    /**
695     * Returns a {@code Complex} whose value is {@code (this + addend)}.
696     * Implements the formula:
697     *
698     * <p>\[ (a + i b) + (c + i d) = (a + c) + i (b + d) \]
699     *
700     * @param  addend Value to be added to this complex number.
701     * @return {@code this + addend}.
702     * @see <a href="http://mathworld.wolfram.com/ComplexAddition.html">Complex Addition</a>
703     */
704    public Complex add(Complex addend) {
705        return new Complex(real + addend.real,
706                           imaginary + addend.imaginary);
707    }
708
709    /**
710     * Returns a {@code Complex} whose value is {@code (this + addend)},
711     * with {@code addend} interpreted as a real number.
712     * Implements the formula:
713     *
714     * <p>\[ (a + i b) + c = (a + c) + i b \]
715     *
716     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
717     * real-only and complex numbers.</p>
718     *
719     * <p>Note: This method preserves the sign of the imaginary component \( b \) if it is {@code -0.0}.
720     * The sign would be lost if adding \( (c + i 0) \) using
721     * {@link #add(Complex) add(Complex.ofCartesian(addend, 0))} since
722     * {@code -0.0 + 0.0 = 0.0}.
723     *
724     * @param addend Value to be added to this complex number.
725     * @return {@code this + addend}.
726     * @see #add(Complex)
727     * @see #ofCartesian(double, double)
728     */
729    public Complex add(double addend) {
730        return new Complex(real + addend, imaginary);
731    }
732
733    /**
734     * Returns a {@code Complex} whose value is {@code (this + addend)},
735     * with {@code addend} interpreted as an imaginary number.
736     * Implements the formula:
737     *
738     * <p>\[ (a + i b) + i d = a + i (b + d) \]
739     *
740     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
741     * imaginary-only and complex numbers.</p>
742     *
743     * <p>Note: This method preserves the sign of the real component \( a \) if it is {@code -0.0}.
744     * The sign would be lost if adding \( (0 + i d) \) using
745     * {@link #add(Complex) add(Complex.ofCartesian(0, addend))} since
746     * {@code -0.0 + 0.0 = 0.0}.
747     *
748     * @param addend Value to be added to this complex number.
749     * @return {@code this + addend}.
750     * @see #add(Complex)
751     * @see #ofCartesian(double, double)
752     */
753    public Complex addImaginary(double addend) {
754        return new Complex(real, imaginary + addend);
755    }
756
757    /**
758     * Returns a {@code Complex} whose value is {@code (this - subtrahend)}.
759     * Implements the formula:
760     *
761     * <p>\[ (a + i b) - (c + i d) = (a - c) + i (b - d) \]
762     *
763     * @param  subtrahend Value to be subtracted from this complex number.
764     * @return {@code this - subtrahend}.
765     * @see <a href="http://mathworld.wolfram.com/ComplexSubtraction.html">Complex Subtraction</a>
766     */
767    public Complex subtract(Complex subtrahend) {
768        return new Complex(real - subtrahend.real,
769                           imaginary - subtrahend.imaginary);
770    }
771
772    /**
773     * Returns a {@code Complex} whose value is {@code (this - subtrahend)},
774     * with {@code subtrahend} interpreted as a real number.
775     * Implements the formula:
776     *
777     * <p>\[ (a + i b) - c = (a - c) + i b \]
778     *
779     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
780     * real-only and complex numbers.</p>
781     *
782     * @param  subtrahend Value to be subtracted from this complex number.
783     * @return {@code this - subtrahend}.
784     * @see #subtract(Complex)
785     */
786    public Complex subtract(double subtrahend) {
787        return new Complex(real - subtrahend, imaginary);
788    }
789
790    /**
791     * Returns a {@code Complex} whose value is {@code (this - subtrahend)},
792     * with {@code subtrahend} interpreted as an imaginary number.
793     * Implements the formula:
794     *
795     * <p>\[ (a + i b) - i d = a + i (b - d) \]
796     *
797     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
798     * imaginary-only and complex numbers.</p>
799     *
800     * @param  subtrahend Value to be subtracted from this complex number.
801     * @return {@code this - subtrahend}.
802     * @see #subtract(Complex)
803     */
804    public Complex subtractImaginary(double subtrahend) {
805        return new Complex(real, imaginary - subtrahend);
806    }
807
808    /**
809     * Returns a {@code Complex} whose value is {@code (minuend - this)},
810     * with {@code minuend} interpreted as a real number.
811     * Implements the formula:
812     * \[ c - (a + i b) = (c - a) - i b \]
813     *
814     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
815     * real-only and complex numbers.</p>
816     *
817     * <p>Note: This method inverts the sign of the imaginary component \( b \) if it is {@code 0.0}.
818     * The sign would not be inverted if subtracting from \( c + i 0 \) using
819     * {@link #subtract(Complex) Complex.ofCartesian(minuend, 0).subtract(this)} since
820     * {@code 0.0 - 0.0 = 0.0}.
821     *
822     * @param  minuend Value this complex number is to be subtracted from.
823     * @return {@code minuend - this}.
824     * @see #subtract(Complex)
825     * @see #ofCartesian(double, double)
826     */
827    public Complex subtractFrom(double minuend) {
828        return new Complex(minuend - real, -imaginary);
829    }
830
831    /**
832     * Returns a {@code Complex} whose value is {@code (this - subtrahend)},
833     * with {@code minuend} interpreted as an imaginary number.
834     * Implements the formula:
835     * \[ i d - (a + i b) = -a + i (d - b) \]
836     *
837     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
838     * imaginary-only and complex numbers.</p>
839     *
840     * <p>Note: This method inverts the sign of the real component \( a \) if it is {@code 0.0}.
841     * The sign would not be inverted if subtracting from \( 0 + i d \) using
842     * {@link #subtract(Complex) Complex.ofCartesian(0, minuend).subtract(this)} since
843     * {@code 0.0 - 0.0 = 0.0}.
844     *
845     * @param  minuend Value this complex number is to be subtracted from.
846     * @return {@code this - subtrahend}.
847     * @see #subtract(Complex)
848     * @see #ofCartesian(double, double)
849     */
850    public Complex subtractFromImaginary(double minuend) {
851        return new Complex(-real, minuend - imaginary);
852    }
853
854    /**
855     * Returns a {@code Complex} whose value is {@code this * factor}.
856     * Implements the formula:
857     *
858     * <p>\[ (a + i b)(c + i d) = (ac - bd) + i (ad + bc) \]
859     *
860     * <p>Recalculates to recover infinities as specified in C99 standard G.5.1.
861     *
862     * @param  factor Value to be multiplied by this complex number.
863     * @return {@code this * factor}.
864     * @see <a href="http://mathworld.wolfram.com/ComplexMultiplication.html">Complex Muliplication</a>
865     */
866    public Complex multiply(Complex factor) {
867        return multiply(real, imaginary, factor.real, factor.imaginary);
868    }
869
870    /**
871     * Returns a {@code Complex} whose value is:
872     * <pre>
873     *  (a + i b)(c + i d) = (ac - bd) + i (ad + bc)</pre>
874     *
875     * <p>Recalculates to recover infinities as specified in C99 standard G.5.1.
876     *
877     * @param re1 Real component of first number.
878     * @param im1 Imaginary component of first number.
879     * @param re2 Real component of second number.
880     * @param im2 Imaginary component of second number.
881     * @return (a + b i)(c + d i).
882     */
883    private static Complex multiply(double re1, double im1, double re2, double im2) {
884        double a = re1;
885        double b = im1;
886        double c = re2;
887        double d = im2;
888        final double ac = a * c;
889        final double bd = b * d;
890        final double ad = a * d;
891        final double bc = b * c;
892        double x = ac - bd;
893        double y = ad + bc;
894
895        // --------------
896        // NaN can occur if:
897        // - any of (a,b,c,d) are NaN (for NaN or Infinite complex numbers)
898        // - a multiplication of infinity by zero (ac,bd,ad,bc).
899        // - a subtraction of infinity from infinity (e.g. ac - bd)
900        //   Note that (ac,bd,ad,bc) can be infinite due to overflow.
901        //
902        // Detect a NaN result and perform correction.
903        //
904        // Modification from the listing in ISO C99 G.5.1 (6)
905        // Do not correct infinity multiplied by zero. This is left as NaN.
906        // --------------
907
908        if (Double.isNaN(x) && Double.isNaN(y)) {
909            // Recover infinities that computed as NaN+iNaN ...
910            boolean recalc = false;
911            if ((Double.isInfinite(a) || Double.isInfinite(b)) &&
912                isNotZero(c, d)) {
913                // This complex is infinite.
914                // "Box" the infinity and change NaNs in the other factor to 0.
915                a = boxInfinity(a);
916                b = boxInfinity(b);
917                c = changeNaNtoZero(c);
918                d = changeNaNtoZero(d);
919                recalc = true;
920            }
921            if ((Double.isInfinite(c) || Double.isInfinite(d)) &&
922                isNotZero(a, b)) {
923                // The other complex is infinite.
924                // "Box" the infinity and change NaNs in the other factor to 0.
925                c = boxInfinity(c);
926                d = boxInfinity(d);
927                a = changeNaNtoZero(a);
928                b = changeNaNtoZero(b);
929                recalc = true;
930            }
931            if (!recalc && (Double.isInfinite(ac) || Double.isInfinite(bd) ||
932                            Double.isInfinite(ad) || Double.isInfinite(bc))) {
933                // The result overflowed to infinity.
934                // Recover infinities from overflow by changing NaNs to 0 ...
935                a = changeNaNtoZero(a);
936                b = changeNaNtoZero(b);
937                c = changeNaNtoZero(c);
938                d = changeNaNtoZero(d);
939                recalc = true;
940            }
941            if (recalc) {
942                x = Double.POSITIVE_INFINITY * (a * c - b * d);
943                y = Double.POSITIVE_INFINITY * (a * d + b * c);
944            }
945        }
946        return new Complex(x, y);
947    }
948
949    /**
950     * Box values for the real or imaginary component of an infinite complex number.
951     * Any infinite value will be returned as one. Non-infinite values will be returned as zero.
952     * The sign is maintained.
953     *
954     * <pre>
955     *  inf  =  1
956     * -inf  = -1
957     *  x    =  0
958     * -x    = -0
959     * </pre>
960     *
961     * @param component the component
962     * @return The boxed value
963     */
964    private static double boxInfinity(double component) {
965        return Math.copySign(Double.isInfinite(component) ? 1.0 : 0.0, component);
966    }
967
968    /**
969     * Checks if the complex number is not zero.
970     *
971     * @param real the real component
972     * @param imaginary the imaginary component
973     * @return true if the complex is not zero
974     */
975    private static boolean isNotZero(double real, double imaginary) {
976        // The use of equals is deliberate.
977        // This method must distinguish NaN from zero thus ruling out:
978        // (real != 0.0 || imaginary != 0.0)
979        return !(real == 0.0 && imaginary == 0.0);
980    }
981
982    /**
983     * Change NaN to zero preserving the sign; otherwise return the value.
984     *
985     * @param value the value
986     * @return The new value
987     */
988    private static double changeNaNtoZero(double value) {
989        return Double.isNaN(value) ? Math.copySign(0.0, value) : value;
990    }
991
992    /**
993     * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor}
994     * interpreted as a real number.
995     * Implements the formula:
996     *
997     * <p>\[ (a + i b) c =  (ac) + i (bc) \]
998     *
999     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
1000     * real-only and complex numbers.</p>
1001     *
1002     * <p>Note: This method should be preferred over using
1003     * {@link #multiply(Complex) multiply(Complex.ofCartesian(factor, 0))}. Multiplication
1004     * can generate signed zeros if either {@code this} complex has zeros for the real
1005     * and/or imaginary component, or if the factor is zero. The summation of signed zeros
1006     * in {@link #multiply(Complex)} may create zeros in the result that differ in sign
1007     * from the equivalent call to multiply by a real-only number.
1008     *
1009     * @param  factor Value to be multiplied by this complex number.
1010     * @return {@code this * factor}.
1011     * @see #multiply(Complex)
1012     */
1013    public Complex multiply(double factor) {
1014        return new Complex(real * factor, imaginary * factor);
1015    }
1016
1017    /**
1018     * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor}
1019     * interpreted as an imaginary number.
1020     * Implements the formula:
1021     *
1022     * <p>\[ (a + i b) id = (-bd) + i (ad) \]
1023     *
1024     * <p>This method can be used to compute the multiplication of this complex number \( z \)
1025     * by \( i \) using a factor with magnitude 1.0. This should be used in preference to
1026     * {@link #multiply(Complex) multiply(Complex.I)} with or without {@link #negate() negation}:</p>
1027     *
1028     * \[ iz = (-b + i a) \\
1029     *   -iz = (b - i a) \]
1030     *
1031     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
1032     * imaginary-only and complex numbers.</p>
1033     *
1034     * <p>Note: This method should be preferred over using
1035     * {@link #multiply(Complex) multiply(Complex.ofCartesian(0, factor))}. Multiplication
1036     * can generate signed zeros if either {@code this} complex has zeros for the real
1037     * and/or imaginary component, or if the factor is zero. The summation of signed zeros
1038     * in {@link #multiply(Complex)} may create zeros in the result that differ in sign
1039     * from the equivalent call to multiply by an imaginary-only number.
1040     *
1041     * @param  factor Value to be multiplied by this complex number.
1042     * @return {@code this * factor}.
1043     * @see #multiply(Complex)
1044     */
1045    public Complex multiplyImaginary(double factor) {
1046        return new Complex(-imaginary * factor, real * factor);
1047    }
1048
1049    /**
1050     * Returns a {@code Complex} whose value is {@code (this / divisor)}.
1051     * Implements the formula:
1052     *
1053     * <p>\[ \frac{a + i b}{c + i d} = \frac{(ac + bd) + i (bc - ad)}{c^2+d^2} \]
1054     *
1055     * <p>Re-calculates NaN result values to recover infinities as specified in C99 standard G.5.1.
1056     *
1057     * @param divisor Value by which this complex number is to be divided.
1058     * @return {@code this / divisor}.
1059     * @see <a href="http://mathworld.wolfram.com/ComplexDivision.html">Complex Division</a>
1060     */
1061    public Complex divide(Complex divisor) {
1062        return divide(real, imaginary, divisor.real, divisor.imaginary);
1063    }
1064
1065    /**
1066     * Returns a {@code Complex} whose value is:
1067     * <pre>
1068     * <code>
1069     *   a + i b     (ac + bd) + i (bc - ad)
1070     *   -------  =  -----------------------
1071     *   c + i d            c<sup>2</sup> + d<sup>2</sup>
1072     * </code>
1073     * </pre>
1074     *
1075     * <p>Recalculates to recover infinities as specified in C99
1076     * standard G.5.1. Method is fully in accordance with
1077     * C++11 standards for complex numbers.</p>
1078     *
1079     * <p>Note: In the event of divide by zero this method produces the same result
1080     * as dividing by a real-only zero using {@link #divide(double)}.
1081     *
1082     * @param re1 Real component of first number.
1083     * @param im1 Imaginary component of first number.
1084     * @param re2 Real component of second number.
1085     * @param im2 Imaginary component of second number.
1086     * @return (a + i b) / (c + i d).
1087     * @see <a href="http://mathworld.wolfram.com/ComplexDivision.html">Complex Division</a>
1088     * @see #divide(double)
1089     */
1090    private static Complex divide(double re1, double im1, double re2, double im2) {
1091        double a = re1;
1092        double b = im1;
1093        double c = re2;
1094        double d = im2;
1095        int ilogbw = 0;
1096        // Get the exponent to scale the divisor parts to the range [1, 2).
1097        final int exponent = getScale(c, d);
1098        if (exponent <= Double.MAX_EXPONENT) {
1099            ilogbw = exponent;
1100            c = Math.scalb(c, -ilogbw);
1101            d = Math.scalb(d, -ilogbw);
1102        }
1103        final double denom = c * c + d * d;
1104
1105        // Note: Modification from the listing in ISO C99 G.5.1 (8):
1106        // Avoid overflow if a or b are very big.
1107        // Since (c, d) in the range [1, 2) the sum (ac + bd) could overflow
1108        // when (a, b) are both above (Double.MAX_VALUE / 4). The same applies to
1109        // (bc - ad) with large negative values.
1110        // Use the maximum exponent as an approximation to the magnitude.
1111        if (getMaxExponent(a, b) > Double.MAX_EXPONENT - 2) {
1112            ilogbw -= 2;
1113            a /= 4;
1114            b /= 4;
1115        }
1116
1117        double x = Math.scalb((a * c + b * d) / denom, -ilogbw);
1118        double y = Math.scalb((b * c - a * d) / denom, -ilogbw);
1119        // Recover infinities and zeros that computed as NaN+iNaN
1120        // the only cases are nonzero/zero, infinite/finite, and finite/infinite, ...
1121        if (Double.isNaN(x) && Double.isNaN(y)) {
1122            if ((denom == 0.0) &&
1123                    (!Double.isNaN(a) || !Double.isNaN(b))) {
1124                // nonzero/zero
1125                // This case produces the same result as divide by a real-only zero
1126                // using Complex.divide(+/-0.0)
1127                x = Math.copySign(Double.POSITIVE_INFINITY, c) * a;
1128                y = Math.copySign(Double.POSITIVE_INFINITY, c) * b;
1129            } else if ((Double.isInfinite(a) || Double.isInfinite(b)) &&
1130                    Double.isFinite(c) && Double.isFinite(d)) {
1131                // infinite/finite
1132                a = boxInfinity(a);
1133                b = boxInfinity(b);
1134                x = Double.POSITIVE_INFINITY * (a * c + b * d);
1135                y = Double.POSITIVE_INFINITY * (b * c - a * d);
1136            } else if ((Double.isInfinite(c) || Double.isInfinite(d)) &&
1137                    Double.isFinite(a) && Double.isFinite(b)) {
1138                // finite/infinite
1139                c = boxInfinity(c);
1140                d = boxInfinity(d);
1141                x = 0.0 * (a * c + b * d);
1142                y = 0.0 * (b * c - a * d);
1143            }
1144        }
1145        return new Complex(x, y);
1146    }
1147
1148    /**
1149     * Returns a {@code Complex} whose value is {@code (this / divisor)},
1150     * with {@code divisor} interpreted as a real number.
1151     * Implements the formula:
1152     *
1153     * <p>\[ \frac{a + i b}{c} = \frac{a}{c} + i \frac{b}{c} \]
1154     *
1155     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
1156     * real-only and complex numbers.</p>
1157     *
1158     * <p>Note: This method should be preferred over using
1159     * {@link #divide(Complex) divide(Complex.ofCartesian(divisor, 0))}. Division
1160     * can generate signed zeros if {@code this} complex has zeros for the real
1161     * and/or imaginary component, or the divisor is infinite. The summation of signed zeros
1162     * in {@link #divide(Complex)} may create zeros in the result that differ in sign
1163     * from the equivalent call to divide by a real-only number.
1164     *
1165     * @param  divisor Value by which this complex number is to be divided.
1166     * @return {@code this / divisor}.
1167     * @see #divide(Complex)
1168     */
1169    public Complex divide(double divisor) {
1170        return new Complex(real / divisor, imaginary / divisor);
1171    }
1172
1173    /**
1174     * Returns a {@code Complex} whose value is {@code (this / divisor)},
1175     * with {@code divisor} interpreted as an imaginary number.
1176     * Implements the formula:
1177     *
1178     * <p>\[ \frac{a + i b}{id} = \frac{b}{d} - i \frac{a}{d} \]
1179     *
1180     * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
1181     * imaginary-only and complex numbers.</p>
1182     *
1183     * <p>Note: This method should be preferred over using
1184     * {@link #divide(Complex) divide(Complex.ofCartesian(0, divisor))}. Division
1185     * can generate signed zeros if {@code this} complex has zeros for the real
1186     * and/or imaginary component, or the divisor is infinite. The summation of signed zeros
1187     * in {@link #divide(Complex)} may create zeros in the result that differ in sign
1188     * from the equivalent call to divide by an imaginary-only number.
1189     *
1190     * <p>Warning: This method will generate a different result from
1191     * {@link #divide(Complex) divide(Complex.ofCartesian(0, divisor))} if the divisor is zero.
1192     * In this case the divide method using a zero-valued Complex will produce the same result
1193     * as dividing by a real-only zero. The output from dividing by imaginary zero will create
1194     * infinite and NaN values in the same component parts as the output from
1195     * {@code this.divide(Complex.ZERO).multiplyImaginary(1)}, however the sign
1196     * of some infinite values may be negated.
1197     *
1198     * @param  divisor Value by which this complex number is to be divided.
1199     * @return {@code this / divisor}.
1200     * @see #divide(Complex)
1201     * @see #divide(double)
1202     */
1203    public Complex divideImaginary(double divisor) {
1204        return new Complex(imaginary / divisor, -real / divisor);
1205    }
1206
1207    /**
1208     * Returns the
1209     * <a href="http://mathworld.wolfram.com/ExponentialFunction.html">
1210     * exponential function</a> of this complex number.
1211     *
1212     * <p>\[ \exp(z) = e^z \]
1213     *
1214     * <p>The exponential function of \( z \) is an entire function in the complex plane.
1215     * Special cases:
1216     *
1217     * <ul>
1218     * <li>{@code z.conj().exp() == z.exp().conj()}.
1219     * <li>If {@code z} is ±0 + i0, returns 1 + i0.
1220     * <li>If {@code z} is x + i∞ for finite x, returns NaN + iNaN ("invalid" floating-point operation).
1221     * <li>If {@code z} is x + iNaN for finite x, returns NaN + iNaN ("invalid" floating-point operation).
1222     * <li>If {@code z} is +∞ + i0, returns +∞ + i0.
1223     * <li>If {@code z} is −∞ + iy for finite y, returns +0 cis(y) (see {@link #ofCis(double)}).
1224     * <li>If {@code z} is +∞ + iy for finite nonzero y, returns +∞ cis(y).
1225     * <li>If {@code z} is −∞ + i∞, returns ±0 ± i0 (where the signs of the real and imaginary parts of the result are unspecified).
1226     * <li>If {@code z} is +∞ + i∞, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified; "invalid" floating-point operation).
1227     * <li>If {@code z} is −∞ + iNaN, returns ±0 ± i0 (where the signs of the real and imaginary parts of the result are unspecified).
1228     * <li>If {@code z} is +∞ + iNaN, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified).
1229     * <li>If {@code z} is NaN + i0, returns NaN + i0.
1230     * <li>If {@code z} is NaN + iy for all nonzero numbers y, returns NaN + iNaN ("invalid" floating-point operation).
1231     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
1232     * </ul>
1233     *
1234     * <p>Implements the formula:
1235     *
1236     * <p>\[ \exp(x + iy) = e^x (\cos(y) + i \sin(y)) \]
1237     *
1238     * @return The exponential of this complex number.
1239     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Exp/">Exp</a>
1240     */
1241    public Complex exp() {
1242        if (Double.isInfinite(real)) {
1243            // Set the scale factor applied to cis(y)
1244            double zeroOrInf;
1245            if (real < 0) {
1246                if (!Double.isFinite(imaginary)) {
1247                    // (−∞ + i∞) or (−∞ + iNaN) returns (±0 ± i0) (where the signs of the
1248                    // real and imaginary parts of the result are unspecified).
1249                    // Here we preserve the conjugate equality.
1250                    return new Complex(0, Math.copySign(0, imaginary));
1251                }
1252                // (−∞ + iy) returns +0 cis(y), for finite y
1253                zeroOrInf = 0;
1254            } else {
1255                // (+∞ + i0) returns +∞ + i0.
1256                if (imaginary == 0) {
1257                    return this;
1258                }
1259                // (+∞ + i∞) or (+∞ + iNaN) returns (±∞ + iNaN) and raises the invalid
1260                // floating-point exception (where the sign of the real part of the
1261                // result is unspecified).
1262                if (!Double.isFinite(imaginary)) {
1263                    return new Complex(real, Double.NaN);
1264                }
1265                // (+∞ + iy) returns (+∞ cis(y)), for finite nonzero y.
1266                zeroOrInf = real;
1267            }
1268            return new Complex(zeroOrInf * Math.cos(imaginary),
1269                               zeroOrInf * Math.sin(imaginary));
1270        } else if (Double.isNaN(real)) {
1271            // (NaN + i0) returns (NaN + i0)
1272            // (NaN + iy) returns (NaN + iNaN) and optionally raises the invalid floating-point exception
1273            // (NaN + iNaN) returns (NaN + iNaN)
1274            return imaginary == 0 ? this : NAN;
1275        } else if (!Double.isFinite(imaginary)) {
1276            // (x + i∞) or (x + iNaN) returns (NaN + iNaN) and raises the invalid
1277            // floating-point exception, for finite x.
1278            return NAN;
1279        }
1280        // real and imaginary are finite.
1281        // Compute e^a * (cos(b) + i sin(b)).
1282
1283        // Special case:
1284        // (±0 + i0) returns (1 + i0)
1285        final double exp = Math.exp(real);
1286        if (imaginary == 0) {
1287            return new Complex(exp, imaginary);
1288        }
1289        return new Complex(exp * Math.cos(imaginary),
1290                           exp * Math.sin(imaginary));
1291    }
1292
1293    /**
1294     * Returns the
1295     * <a href="http://mathworld.wolfram.com/NaturalLogarithm.html">
1296     * natural logarithm</a> of this complex number.
1297     *
1298     * <p>The natural logarithm of \( z \) is unbounded along the real axis and
1299     * in the range \( [-\pi, \pi] \) along the imaginary axis. The imaginary part of the
1300     * natural logarithm has a branch cut along the negative real axis \( (-infty,0] \).
1301     * Special cases:
1302     *
1303     * <ul>
1304     * <li>{@code z.conj().log() == z.log().conj()}.
1305     * <li>If {@code z} is −0 + i0, returns −∞ + iπ ("divide-by-zero" floating-point operation).
1306     * <li>If {@code z} is +0 + i0, returns −∞ + i0 ("divide-by-zero" floating-point operation).
1307     * <li>If {@code z} is x + i∞ for finite x, returns +∞ + iπ/2.
1308     * <li>If {@code z} is x + iNaN for finite x, returns NaN + iNaN ("invalid" floating-point operation).
1309     * <li>If {@code z} is −∞ + iy for finite positive-signed y, returns +∞ + iπ.
1310     * <li>If {@code z} is +∞ + iy for finite positive-signed y, returns +∞ + i0.
1311     * <li>If {@code z} is −∞ + i∞, returns +∞ + i3π/4.
1312     * <li>If {@code z} is +∞ + i∞, returns +∞ + iπ/4.
1313     * <li>If {@code z} is ±∞ + iNaN, returns +∞ + iNaN.
1314     * <li>If {@code z} is NaN + iy for finite y, returns NaN + iNaN ("invalid" floating-point operation).
1315     * <li>If {@code z} is NaN + i∞, returns +∞ + iNaN.
1316     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
1317     * </ul>
1318     *
1319     * <p>Implements the formula:
1320     *
1321     * <p>\[ \ln(z) = \ln |z| + i \arg(z) \]
1322     *
1323     * <p>where \( |z| \) is the absolute and \( \arg(z) \) is the argument.
1324     *
1325     * <p>The implementation is based on the method described in:</p>
1326     * <blockquote>
1327     * T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang (1994)
1328     * Implementing complex elementary functions using exception handling.
1329     * ACM Transactions on Mathematical Software, Vol 20, No 2, pp 215-244.
1330     * </blockquote>
1331     *
1332     * @return The natural logarithm of this complex number.
1333     * @see Math#log(double)
1334     * @see #abs()
1335     * @see #arg()
1336     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Log/">Log</a>
1337     */
1338    public Complex log() {
1339        return log(Math::log, HALF, LN_2, Complex::ofCartesian);
1340    }
1341
1342    /**
1343     * Returns the base 10
1344     * <a href="http://mathworld.wolfram.com/CommonLogarithm.html">
1345     * common logarithm</a> of this complex number.
1346     *
1347     * <p>The common logarithm of \( z \) is unbounded along the real axis and
1348     * in the range \( [-\pi, \pi] \) along the imaginary axis. The imaginary part of the
1349     * common logarithm has a branch cut along the negative real axis \( (-infty,0] \).
1350     * Special cases are as defined in the {@link #log() natural logarithm}:
1351     *
1352     * <p>Implements the formula:
1353     *
1354     * <p>\[ \log_{10}(z) = \log_{10} |z| + i \arg(z) \]
1355     *
1356     * <p>where \( |z| \) is the absolute and \( \arg(z) \) is the argument.
1357     *
1358     * @return The base 10 logarithm of this complex number.
1359     * @see Math#log10(double)
1360     * @see #abs()
1361     * @see #arg()
1362     */
1363    public Complex log10() {
1364        return log(Math::log10, LOG_10E_O_2, LOG10_2, Complex::ofCartesian);
1365    }
1366
1367    /**
1368     * Returns the logarithm of this complex number using the provided function.
1369     * Implements the formula:
1370     *
1371     * <pre>
1372     *   log(x + i y) = log(|x + i y|) + i arg(x + i y)</pre>
1373     *
1374     * <p>Warning: The argument {@code logOf2} must be equal to {@code log(2)} using the
1375     * provided log function otherwise scaling using powers of 2 in the case of overflow
1376     * will be incorrect. This is provided as an internal optimisation.
1377     *
1378     * @param log Log function.
1379     * @param logOfeOver2 The log function applied to e, then divided by 2.
1380     * @param logOf2 The log function applied to 2.
1381     * @param constructor Constructor for the returned complex.
1382     * @return The logarithm of this complex number.
1383     * @see #abs()
1384     * @see #arg()
1385     */
1386    private Complex log(DoubleUnaryOperator log, double logOfeOver2, double logOf2, ComplexConstructor constructor) {
1387        // Handle NaN
1388        if (Double.isNaN(real) || Double.isNaN(imaginary)) {
1389            // Return NaN unless infinite
1390            if (isInfinite()) {
1391                return constructor.create(Double.POSITIVE_INFINITY, Double.NaN);
1392            }
1393            // No-use of the input constructor
1394            return NAN;
1395        }
1396
1397        // Returns the real part:
1398        // log(sqrt(x^2 + y^2))
1399        // log(x^2 + y^2) / 2
1400
1401        // Compute with positive values
1402        double x = Math.abs(real);
1403        double y = Math.abs(imaginary);
1404
1405        // Find the larger magnitude.
1406        if (x < y) {
1407            final double tmp = x;
1408            x = y;
1409            y = tmp;
1410        }
1411
1412        if (x == 0) {
1413            // Handle zero: raises the ‘‘divide-by-zero’’ floating-point exception.
1414            return constructor.create(Double.NEGATIVE_INFINITY,
1415                                      negative(real) ? Math.copySign(Math.PI, imaginary) : imaginary);
1416        }
1417
1418        double re;
1419
1420        // This alters the implementation of Hull et al (1994) which used a standard
1421        // precision representation of |z|: sqrt(x*x + y*y).
1422        // This formula should use the same definition of the magnitude returned
1423        // by Complex.abs() which is a high precision computation with scaling.
1424        // The checks for overflow thus only require ensuring the output of |z|
1425        // will not overflow or underflow.
1426
1427        if (x > HALF && x < ROOT2) {
1428            // x^2+y^2 close to 1. Use log1p(x^2+y^2 - 1) / 2.
1429            re = Math.log1p(x2y2m1(x, y)) * logOfeOver2;
1430        } else {
1431            // Check for over/underflow in |z|
1432            // When scaling:
1433            // log(a / b) = log(a) - log(b)
1434            // So initialize the result with the log of the scale factor.
1435            re = 0;
1436            if (x > Double.MAX_VALUE / 2) {
1437                // Potential overflow.
1438                if (isPosInfinite(x)) {
1439                    // Handle infinity
1440                    return constructor.create(x, arg());
1441                }
1442                // Scale down.
1443                x /= 2;
1444                y /= 2;
1445                // log(2)
1446                re = logOf2;
1447            } else if (y < Double.MIN_NORMAL) {
1448                // Potential underflow.
1449                if (y == 0) {
1450                    // Handle real only number
1451                    return constructor.create(log.applyAsDouble(x), arg());
1452                }
1453                // Scale up sub-normal numbers to make them normal by scaling by 2^54,
1454                // i.e. more than the mantissa digits.
1455                x *= 0x1.0p54;
1456                y *= 0x1.0p54;
1457                // log(2^-54) = -54 * log(2)
1458                re = -54 * logOf2;
1459            }
1460            re += log.applyAsDouble(abs(x, y));
1461        }
1462
1463        // All ISO C99 edge cases for the imaginary are satisfied by the Math library.
1464        return constructor.create(re, arg());
1465    }
1466
1467    /**
1468     * Returns the complex power of this complex number raised to the power of {@code x}.
1469     * Implements the formula:
1470     *
1471     * <p>\[ z^x = e^{x \ln(z)} \]
1472     *
1473     * <p>If this complex number is zero then this method returns zero if {@code x} is positive
1474     * in the real component and zero in the imaginary component;
1475     * otherwise it returns NaN + iNaN.
1476     *
1477     * @param  x The exponent to which this complex number is to be raised.
1478     * @return This complex number raised to the power of {@code x}.
1479     * @see #log()
1480     * @see #multiply(Complex)
1481     * @see #exp()
1482     * @see <a href="http://mathworld.wolfram.com/ComplexExponentiation.html">Complex exponentiation</a>
1483     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Power/">Power</a>
1484     */
1485    public Complex pow(Complex x) {
1486        if (real == 0 &&
1487            imaginary == 0) {
1488            // This value is zero. Test the other.
1489            if (x.real > 0 &&
1490                x.imaginary == 0) {
1491                // 0 raised to positive number is 0
1492                return ZERO;
1493            }
1494            // 0 raised to anything else is NaN
1495            return NAN;
1496        }
1497        return log().multiply(x).exp();
1498    }
1499
1500    /**
1501     * Returns the complex power of this complex number raised to the power of {@code x},
1502     * with {@code x} interpreted as a real number.
1503     * Implements the formula:
1504     *
1505     * <p>\[ z^x = e^{x \ln(z)} \]
1506     *
1507     * <p>If this complex number is zero then this method returns zero if {@code x} is positive;
1508     * otherwise it returns NaN + iNaN.
1509     *
1510     * @param  x The exponent to which this complex number is to be raised.
1511     * @return This complex number raised to the power of {@code x}.
1512     * @see #log()
1513     * @see #multiply(double)
1514     * @see #exp()
1515     * @see #pow(Complex)
1516     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Power/">Power</a>
1517     */
1518    public Complex pow(double x) {
1519        if (real == 0 &&
1520            imaginary == 0) {
1521            // This value is zero. Test the other.
1522            if (x > 0) {
1523                // 0 raised to positive number is 0
1524                return ZERO;
1525            }
1526            // 0 raised to anything else is NaN
1527            return NAN;
1528        }
1529        return log().multiply(x).exp();
1530    }
1531
1532    /**
1533     * Returns the
1534     * <a href="http://mathworld.wolfram.com/SquareRoot.html">
1535     * square root</a> of this complex number.
1536     *
1537     * <p>\[ \sqrt{x + iy} = \frac{1}{2} \sqrt{2} \left( \sqrt{ \sqrt{x^2 + y^2} + x } + i\ \text{sgn}(y) \sqrt{ \sqrt{x^2 + y^2} - x } \right) \]
1538     *
1539     * <p>The square root of \( z \) is in the range \( [0, +\infty) \) along the real axis and
1540     * is unbounded along the imaginary axis. The imaginary part of the square root has a
1541     * branch cut along the negative real axis \( (-infty,0) \). Special cases:
1542     *
1543     * <ul>
1544     * <li>{@code z.conj().sqrt() == z.sqrt().conj()}.
1545     * <li>If {@code z} is ±0 + i0, returns +0 + i0.
1546     * <li>If {@code z} is x + i∞ for all x (including NaN), returns +∞ + i∞.
1547     * <li>If {@code z} is x + iNaN for finite x, returns NaN + iNaN ("invalid" floating-point operation).
1548     * <li>If {@code z} is −∞ + iy for finite positive-signed y, returns +0 + i∞.
1549     * <li>If {@code z} is +∞ + iy for finite positive-signed y, returns +∞ + i0.
1550     * <li>If {@code z} is −∞ + iNaN, returns NaN ± i∞ (where the sign of the imaginary part of the result is unspecified).
1551     * <li>If {@code z} is +∞ + iNaN, returns +∞ + iNaN.
1552     * <li>If {@code z} is NaN + iy for finite y, returns NaN + iNaN ("invalid" floating-point operation).
1553     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
1554     * </ul>
1555     *
1556     * <p>Implements the following algorithm to compute \( \sqrt{x + iy} \):
1557     * <ol>
1558     * <li>Let \( t = \sqrt{2 (|x| + |x + iy|)} \)
1559     * <li>if \( x \geq 0 \) return \( \frac{t}{2} + i \frac{y}{t} \)
1560     * <li>else return \( \frac{|y|}{t} + i\ \text{sgn}(y) \frac{t}{2} \)
1561     * </ol>
1562     * where:
1563     * <ul>
1564     * <li>\( |x| =\ \){@link Math#abs(double) abs}(x)
1565     * <li>\( |x + y i| =\ \){@link Complex#abs}
1566     * <li>\( \text{sgn}(y) =\ \){@link Math#copySign(double,double) copySign}(1.0, y)
1567     * </ul>
1568     *
1569     * <p>The implementation is overflow and underflow safe based on the method described in:</p>
1570     * <blockquote>
1571     * T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang (1994)
1572     * Implementing complex elementary functions using exception handling.
1573     * ACM Transactions on Mathematical Software, Vol 20, No 2, pp 215-244.
1574     * </blockquote>
1575     *
1576     * @return The square root of this complex number.
1577     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Sqrt/">Sqrt</a>
1578     */
1579    public Complex sqrt() {
1580        return sqrt(real, imaginary);
1581    }
1582
1583    /**
1584     * Returns the square root of the complex number {@code sqrt(x + i y)}.
1585     *
1586     * @param real Real component.
1587     * @param imaginary Imaginary component.
1588     * @return The square root of the complex number.
1589     */
1590    private static Complex sqrt(double real, double imaginary) {
1591        // Handle NaN
1592        if (Double.isNaN(real) || Double.isNaN(imaginary)) {
1593            // Check for infinite
1594            if (Double.isInfinite(imaginary)) {
1595                return new Complex(Double.POSITIVE_INFINITY, imaginary);
1596            }
1597            if (Double.isInfinite(real)) {
1598                if (real == Double.NEGATIVE_INFINITY) {
1599                    return new Complex(Double.NaN, Math.copySign(Double.POSITIVE_INFINITY, imaginary));
1600                }
1601                return new Complex(Double.POSITIVE_INFINITY, Double.NaN);
1602            }
1603            return NAN;
1604        }
1605
1606        // Compute with positive values and determine sign at the end
1607        final double x = Math.abs(real);
1608        final double y = Math.abs(imaginary);
1609
1610        // Compute
1611        double t;
1612
1613        // This alters the implementation of Hull et al (1994) which used a standard
1614        // precision representation of |z|: sqrt(x*x + y*y).
1615        // This formula should use the same definition of the magnitude returned
1616        // by Complex.abs() which is a high precision computation with scaling.
1617        // Worry about overflow if 2 * (|z| + |x|) will overflow.
1618        // Worry about underflow if |z| or |x| are sub-normal components.
1619
1620        if (inRegion(x, y, Double.MIN_NORMAL, SQRT_SAFE_UPPER)) {
1621            // No over/underflow
1622            t = Math.sqrt(2 * (abs(x, y) + x));
1623        } else {
1624            // Potential over/underflow. First check infinites and real/imaginary only.
1625
1626            // Check for infinite
1627            if (isPosInfinite(y)) {
1628                return new Complex(Double.POSITIVE_INFINITY, imaginary);
1629            } else if (isPosInfinite(x)) {
1630                if (real == Double.NEGATIVE_INFINITY) {
1631                    return new Complex(0, Math.copySign(Double.POSITIVE_INFINITY, imaginary));
1632                }
1633                return new Complex(Double.POSITIVE_INFINITY, Math.copySign(0, imaginary));
1634            } else if (y == 0) {
1635                // Real only
1636                final double sqrtAbs = Math.sqrt(x);
1637                if (real < 0) {
1638                    return new Complex(0, Math.copySign(sqrtAbs, imaginary));
1639                }
1640                return new Complex(sqrtAbs, imaginary);
1641            } else if (x == 0) {
1642                // Imaginary only. This sets the two components to the same magnitude.
1643                // Note: In polar coordinates this does not happen:
1644                // real = sqrt(abs()) * Math.cos(arg() / 2)
1645                // imag = sqrt(abs()) * Math.sin(arg() / 2)
1646                // arg() / 2 = pi/4 and cos and sin should both return sqrt(2)/2 but
1647                // are different by 1 ULP.
1648                final double sqrtAbs = Math.sqrt(y) * ONE_OVER_ROOT2;
1649                return new Complex(sqrtAbs, Math.copySign(sqrtAbs, imaginary));
1650            } else {
1651                // Over/underflow.
1652                // Full scaling is not required as this is done in the hypotenuse function.
1653                // Keep the number as big as possible for maximum precision in the second sqrt.
1654                // Note if we scale by an even power of 2, we can re-scale by sqrt of the number.
1655                // a = sqrt(b)
1656                // a = sqrt(b/4) * sqrt(4)
1657
1658                double rescale;
1659                double sx;
1660                double sy;
1661                if (Math.max(x, y) > SQRT_SAFE_UPPER) {
1662                    // Overflow. Scale down by 16 and rescale by sqrt(16).
1663                    sx = x / 16;
1664                    sy = y / 16;
1665                    rescale = 4;
1666                } else {
1667                    // Sub-normal numbers. Make them normal by scaling by 2^54,
1668                    // i.e. more than the mantissa digits, and rescale by sqrt(2^54) = 2^27.
1669                    sx = x * 0x1.0p54;
1670                    sy = y * 0x1.0p54;
1671                    rescale = 0x1.0p-27;
1672                }
1673                t = rescale * Math.sqrt(2 * (abs(sx, sy) + sx));
1674            }
1675        }
1676
1677        if (real >= 0) {
1678            return new Complex(t / 2, imaginary / t);
1679        }
1680        return new Complex(y / t, Math.copySign(t / 2, imaginary));
1681    }
1682
1683    /**
1684     * Returns the
1685     * <a href="http://mathworld.wolfram.com/Sine.html">
1686     * sine</a> of this complex number.
1687     *
1688     * <p>\[ \sin(z) = \frac{1}{2} i \left( e^{-iz} - e^{iz} \right) \]
1689     *
1690     * <p>This is an odd function: \( \sin(z) = -\sin(-z) \).
1691     * The sine is an entire function and requires no branch cuts.
1692     *
1693     * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
1694     *
1695     * <p>\[ \sin(x + iy) = \sin(x)\cosh(y) + i \cos(x)\sinh(y) \]
1696     *
1697     * <p>As per the C99 standard this function is computed using the trigonomic identity:
1698     *
1699     * <p>\[ \sin(z) = -i \sinh(iz) \]
1700     *
1701     * @return The sine of this complex number.
1702     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Sin/">Sin</a>
1703     */
1704    public Complex sin() {
1705        // Define in terms of sinh
1706        // sin(z) = -i sinh(iz)
1707        // Multiply this number by I, compute sinh, then multiply by back
1708        return sinh(-imaginary, real, Complex::multiplyNegativeI);
1709    }
1710
1711    /**
1712     * Returns the
1713     * <a href="http://mathworld.wolfram.com/Cosine.html">
1714     * cosine</a> of this complex number.
1715     *
1716     * <p>\[ \cos(z) = \frac{1}{2} \left( e^{iz} + e^{-iz} \right) \]
1717     *
1718     * <p>This is an even function: \( \cos(z) = \cos(-z) \).
1719     * The cosine is an entire function and requires no branch cuts.
1720     *
1721     * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
1722     *
1723     * <p>\[ \cos(x + iy) = \cos(x)\cosh(y) - i \sin(x)\sinh(y) \]
1724     *
1725     * <p>As per the C99 standard this function is computed using the trigonomic identity:
1726     *
1727     * <p>\[ cos(z) = cosh(iz) \]
1728     *
1729     * @return The cosine of this complex number.
1730     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Cos/">Cos</a>
1731     */
1732    public Complex cos() {
1733        // Define in terms of cosh
1734        // cos(z) = cosh(iz)
1735        // Multiply this number by I and compute cosh.
1736        return cosh(-imaginary, real, Complex::ofCartesian);
1737    }
1738
1739    /**
1740     * Returns the
1741     * <a href="http://mathworld.wolfram.com/Tangent.html">
1742     * tangent</a> of this complex number.
1743     *
1744     * <p>\[ \tan(z) = \frac{i(e^{-iz} - e^{iz})}{e^{-iz} + e^{iz}} \]
1745     *
1746     * <p>This is an odd function: \( \tan(z) = -\tan(-z) \).
1747     * The tangent is an entire function and requires no branch cuts.
1748     *
1749     * <p>This is implemented using real \( x \) and imaginary \( y \) parts:</p>
1750     * \[ \tan(x + iy) = \frac{\sin(2x)}{\cos(2x)+\cosh(2y)} + i \frac{\sinh(2y)}{\cos(2x)+\cosh(2y)} \]
1751     *
1752     * <p>As per the C99 standard this function is computed using the trigonomic identity:</p>
1753     * \[ \tan(z) = -i \tanh(iz) \]
1754     *
1755     * @return The tangent of this complex number.
1756     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Tan/">Tangent</a>
1757     */
1758    public Complex tan() {
1759        // Define in terms of tanh
1760        // tan(z) = -i tanh(iz)
1761        // Multiply this number by I, compute tanh, then multiply by back
1762        return tanh(-imaginary, real, Complex::multiplyNegativeI);
1763    }
1764
1765    /**
1766     * Returns the
1767     * <a href="http://mathworld.wolfram.com/InverseSine.html">
1768     * inverse sine</a> of this complex number.
1769     *
1770     * <p>\[ \sin^{-1}(z) = - i \left(\ln{iz + \sqrt{1 - z^2}}\right) \]
1771     *
1772     * <p>The inverse sine of \( z \) is unbounded along the imaginary axis and
1773     * in the range \( [-\pi, \pi] \) along the real axis. Special cases are handled
1774     * as if the operation is implemented using \( \sin^{-1}(z) = -i \sinh^{-1}(iz) \).
1775     *
1776     * <p>The inverse sine is a multivalued function and requires a branch cut in
1777     * the complex plane; the cut is conventionally placed at the line segments
1778     * \( (\infty,-1) \) and \( (1,\infty) \) of the real axis.
1779     *
1780     * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
1781     *
1782     * <p>\[ \sin^{-1}(z) = \sin^{-1}(B) + i\ \text{sgn}(y)\ln \left(A + \sqrt{A^2-1} \right) \\
1783     *   A = \frac{1}{2} \left[ \sqrt{(x+1)^2+y^2} + \sqrt{(x-1)^2+y^2} \right] \\
1784     *   B = \frac{1}{2} \left[ \sqrt{(x+1)^2+y^2} - \sqrt{(x-1)^2+y^2} \right] \]
1785     *
1786     * <p>where \( \text{sgn}(y) \) is the sign function implemented using
1787     * {@link Math#copySign(double,double) copySign(1.0, y)}.
1788     *
1789     * <p>The implementation is based on the method described in:</p>
1790     * <blockquote>
1791     * T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang (1997)
1792     * Implementing the complex Arcsine and Arccosine Functions using Exception Handling.
1793     * ACM Transactions on Mathematical Software, Vol 23, No 3, pp 299-335.
1794     * </blockquote>
1795     *
1796     * <p>The code has been adapted from the <a href="https://www.boost.org/">Boost</a>
1797     * {@code c++} implementation {@code <boost/math/complex/asin.hpp>}.
1798     *
1799     * @return The inverse sine of this complex number.
1800     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcSin/">ArcSin</a>
1801     */
1802    public Complex asin() {
1803        return asin(real, imaginary, Complex::ofCartesian);
1804    }
1805
1806    /**
1807     * Returns the inverse sine of the complex number.
1808     *
1809     * <p>This function exists to allow implementation of the identity
1810     * {@code asinh(z) = -i asin(iz)}.
1811     *
1812     * <p>Adapted from {@code <boost/math/complex/asin.hpp>}. This method only (and not
1813     * invoked methods within) is distributed under the Boost Software License V1.0.
1814     * The original notice is shown below and the licence is shown in full in LICENSE:
1815     * <pre>
1816     * (C) Copyright John Maddock 2005.
1817     * Distributed under the Boost Software License, Version 1.0. (See accompanying
1818     * file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
1819     * </pre>
1820     *
1821     * @param real Real part.
1822     * @param imaginary Imaginary part.
1823     * @param constructor Constructor.
1824     * @return The inverse sine of this complex number.
1825     */
1826    private static Complex asin(final double real, final double imaginary,
1827                                final ComplexConstructor constructor) {
1828        // Compute with positive values and determine sign at the end
1829        final double x = Math.abs(real);
1830        final double y = Math.abs(imaginary);
1831        // The result (without sign correction)
1832        double re;
1833        double im;
1834
1835        // Handle C99 special cases
1836        if (Double.isNaN(x)) {
1837            if (isPosInfinite(y)) {
1838                re = x;
1839                im = y;
1840            } else {
1841                // No-use of the input constructor
1842                return NAN;
1843            }
1844        } else if (Double.isNaN(y)) {
1845            if (x == 0) {
1846                re = 0;
1847                im = y;
1848            } else if (isPosInfinite(x)) {
1849                re = y;
1850                im = x;
1851            } else {
1852                // No-use of the input constructor
1853                return NAN;
1854            }
1855        } else if (isPosInfinite(x)) {
1856            re = isPosInfinite(y) ? PI_OVER_4 : PI_OVER_2;
1857            im = x;
1858        } else if (isPosInfinite(y)) {
1859            re = 0;
1860            im = y;
1861        } else {
1862            // Special case for real numbers:
1863            if (y == 0 && x <= 1) {
1864                return constructor.create(Math.asin(real), imaginary);
1865            }
1866
1867            final double xp1 = x + 1;
1868            final double xm1 = x - 1;
1869
1870            if (inRegion(x, y, SAFE_MIN, SAFE_MAX)) {
1871                final double yy = y * y;
1872                final double r = Math.sqrt(xp1 * xp1 + yy);
1873                final double s = Math.sqrt(xm1 * xm1 + yy);
1874                final double a = 0.5 * (r + s);
1875                final double b = x / a;
1876
1877                if (b <= B_CROSSOVER) {
1878                    re = Math.asin(b);
1879                } else {
1880                    final double apx = a + x;
1881                    if (x <= 1) {
1882                        re = Math.atan(x / Math.sqrt(0.5 * apx * (yy / (r + xp1) + (s - xm1))));
1883                    } else {
1884                        re = Math.atan(x / (y * Math.sqrt(0.5 * (apx / (r + xp1) + apx / (s + xm1)))));
1885                    }
1886                }
1887
1888                if (a <= A_CROSSOVER) {
1889                    double am1;
1890                    if (x < 1) {
1891                        am1 = 0.5 * (yy / (r + xp1) + yy / (s - xm1));
1892                    } else {
1893                        am1 = 0.5 * (yy / (r + xp1) + (s + xm1));
1894                    }
1895                    im = Math.log1p(am1 + Math.sqrt(am1 * (a + 1)));
1896                } else {
1897                    im = Math.log(a + Math.sqrt(a * a - 1));
1898                }
1899            } else {
1900                // Hull et al: Exception handling code from figure 4
1901                if (y <= (EPSILON * Math.abs(xm1))) {
1902                    if (x < 1) {
1903                        re = Math.asin(x);
1904                        im = y / Math.sqrt(xp1 * (1 - x));
1905                    } else {
1906                        re = PI_OVER_2;
1907                        if ((Double.MAX_VALUE / xp1) > xm1) {
1908                            // xp1 * xm1 won't overflow:
1909                            im = Math.log1p(xm1 + Math.sqrt(xp1 * xm1));
1910                        } else {
1911                            im = LN_2 + Math.log(x);
1912                        }
1913                    }
1914                } else if (y <= SAFE_MIN) {
1915                    // Hull et al: Assume x == 1.
1916                    // True if:
1917                    // E^2 > 8*sqrt(u)
1918                    //
1919                    // E = Machine epsilon: (1 + epsilon) = 1
1920                    // u = Double.MIN_NORMAL
1921                    re = PI_OVER_2 - Math.sqrt(y);
1922                    im = Math.sqrt(y);
1923                } else if (EPSILON * y - 1 >= x) {
1924                    // Possible underflow:
1925                    re = x / y;
1926                    im = LN_2 + Math.log(y);
1927                } else if (x > 1) {
1928                    re = Math.atan(x / y);
1929                    final double xoy = x / y;
1930                    im = LN_2 + Math.log(y) + 0.5 * Math.log1p(xoy * xoy);
1931                } else {
1932                    final double a = Math.sqrt(1 + y * y);
1933                    // Possible underflow:
1934                    re = x / a;
1935                    im = 0.5 * Math.log1p(2 * y * (y + a));
1936                }
1937            }
1938        }
1939
1940        return constructor.create(changeSign(re, real),
1941                                  changeSign(im, imaginary));
1942    }
1943
1944    /**
1945     * Returns the
1946     * <a href="http://mathworld.wolfram.com/InverseCosine.html">
1947     * inverse cosine</a> of this complex number.
1948     *
1949     * <p>\[ \cos^{-1}(z) = \frac{\pi}{2} + i \left(\ln{iz + \sqrt{1 - z^2}}\right) \]
1950     *
1951     * <p>The inverse cosine of \( z \) is in the range \( [0, \pi) \) along the real axis and
1952     * unbounded along the imaginary axis. Special cases:
1953     *
1954     * <ul>
1955     * <li>{@code z.conj().acos() == z.acos().conj()}.
1956     * <li>If {@code z} is ±0 + i0, returns π/2 − i0.
1957     * <li>If {@code z} is ±0 + iNaN, returns π/2 + iNaN.
1958     * <li>If {@code z} is x + i∞ for finite x, returns π/2 − i∞.
1959     * <li>If {@code z} is x + iNaN, returns NaN + iNaN ("invalid" floating-point operation).
1960     * <li>If {@code z} is −∞ + iy for positive-signed finite y, returns π − i∞.
1961     * <li>If {@code z} is +∞ + iy for positive-signed finite y, returns +0 − i∞.
1962     * <li>If {@code z} is −∞ + i∞, returns 3π/4 − i∞.
1963     * <li>If {@code z} is +∞ + i∞, returns π/4 − i∞.
1964     * <li>If {@code z} is ±∞ + iNaN, returns NaN ± i∞ where the sign of the imaginary part of the result is unspecified.
1965     * <li>If {@code z} is NaN + iy for finite y, returns NaN + iNaN ("invalid" floating-point operation).
1966     * <li>If {@code z} is NaN + i∞, returns NaN − i∞.
1967     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
1968     * </ul>
1969     *
1970     * <p>The inverse cosine is a multivalued function and requires a branch cut in
1971     * the complex plane; the cut is conventionally placed at the line segments
1972     * \( (-\infty,-1) \) and \( (1,\infty) \) of the real axis.
1973     *
1974     * <p>This function is implemented using real \( x \) and imaginary \( y \) parts:
1975     *
1976     * <p>\[ \cos^{-1}(z) = \cos^{-1}(B) - i\ \text{sgn}(y) \ln\left(A + \sqrt{A^2-1}\right) \\
1977     *   A = \frac{1}{2} \left[ \sqrt{(x+1)^2+y^2} + \sqrt{(x-1)^2+y^2} \right] \\
1978     *   B = \frac{1}{2} \left[ \sqrt{(x+1)^2+y^2} - \sqrt{(x-1)^2+y^2} \right] \]
1979     *
1980     * <p>where \( \text{sgn}(y) \) is the sign function implemented using
1981     * {@link Math#copySign(double,double) copySign(1.0, y)}.
1982     *
1983     * <p>The implementation is based on the method described in:</p>
1984     * <blockquote>
1985     * T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang (1997)
1986     * Implementing the complex Arcsine and Arccosine Functions using Exception Handling.
1987     * ACM Transactions on Mathematical Software, Vol 23, No 3, pp 299-335.
1988     * </blockquote>
1989     *
1990     * <p>The code has been adapted from the <a href="https://www.boost.org/">Boost</a>
1991     * {@code c++} implementation {@code <boost/math/complex/acos.hpp>}.
1992     *
1993     * @return The inverse cosine of this complex number.
1994     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcCos/">ArcCos</a>
1995     */
1996    public Complex acos() {
1997        return acos(real, imaginary, Complex::ofCartesian);
1998    }
1999
2000    /**
2001     * Returns the inverse cosine of the complex number.
2002     *
2003     * <p>This function exists to allow implementation of the identity
2004     * {@code acosh(z) = +-i acos(z)}.
2005     *
2006     * <p>Adapted from {@code <boost/math/complex/acos.hpp>}. This method only (and not
2007     * invoked methods within) is distributed under the Boost Software License V1.0.
2008     * The original notice is shown below and the licence is shown in full in LICENSE:
2009     * <pre>
2010     * (C) Copyright John Maddock 2005.
2011     * Distributed under the Boost Software License, Version 1.0. (See accompanying
2012     * file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
2013     * </pre>
2014     *
2015     * @param real Real part.
2016     * @param imaginary Imaginary part.
2017     * @param constructor Constructor.
2018     * @return The inverse cosine of the complex number.
2019     */
2020    private static Complex acos(final double real, final double imaginary,
2021                                final ComplexConstructor constructor) {
2022        // Compute with positive values and determine sign at the end
2023        final double x = Math.abs(real);
2024        final double y = Math.abs(imaginary);
2025        // The result (without sign correction)
2026        double re;
2027        double im;
2028
2029        // Handle C99 special cases
2030        if (isPosInfinite(x)) {
2031            if (isPosInfinite(y)) {
2032                re = PI_OVER_4;
2033                im = y;
2034            } else if (Double.isNaN(y)) {
2035                // sign of the imaginary part of the result is unspecified
2036                return constructor.create(imaginary, real);
2037            } else {
2038                re = 0;
2039                im = Double.POSITIVE_INFINITY;
2040            }
2041        } else if (Double.isNaN(x)) {
2042            if (isPosInfinite(y)) {
2043                return constructor.create(x, -imaginary);
2044            }
2045            // No-use of the input constructor
2046            return NAN;
2047        } else if (isPosInfinite(y)) {
2048            re = PI_OVER_2;
2049            im = y;
2050        } else if (Double.isNaN(y)) {
2051            return constructor.create(x == 0 ? PI_OVER_2 : y, y);
2052        } else {
2053            // Special case for real numbers:
2054            if (y == 0 && x <= 1) {
2055                return constructor.create(x == 0 ? PI_OVER_2 : Math.acos(real), -imaginary);
2056            }
2057
2058            final double xp1 = x + 1;
2059            final double xm1 = x - 1;
2060
2061            if (inRegion(x, y, SAFE_MIN, SAFE_MAX)) {
2062                final double yy = y * y;
2063                final double r = Math.sqrt(xp1 * xp1 + yy);
2064                final double s = Math.sqrt(xm1 * xm1 + yy);
2065                final double a = 0.5 * (r + s);
2066                final double b = x / a;
2067
2068                if (b <= B_CROSSOVER) {
2069                    re = Math.acos(b);
2070                } else {
2071                    final double apx = a + x;
2072                    if (x <= 1) {
2073                        re = Math.atan(Math.sqrt(0.5 * apx * (yy / (r + xp1) + (s - xm1))) / x);
2074                    } else {
2075                        re = Math.atan((y * Math.sqrt(0.5 * (apx / (r + xp1) + apx / (s + xm1)))) / x);
2076                    }
2077                }
2078
2079                if (a <= A_CROSSOVER) {
2080                    double am1;
2081                    if (x < 1) {
2082                        am1 = 0.5 * (yy / (r + xp1) + yy / (s - xm1));
2083                    } else {
2084                        am1 = 0.5 * (yy / (r + xp1) + (s + xm1));
2085                    }
2086                    im = Math.log1p(am1 + Math.sqrt(am1 * (a + 1)));
2087                } else {
2088                    im = Math.log(a + Math.sqrt(a * a - 1));
2089                }
2090            } else {
2091                // Hull et al: Exception handling code from figure 6
2092                if (y <= (EPSILON * Math.abs(xm1))) {
2093                    if (x < 1) {
2094                        re = Math.acos(x);
2095                        im = y / Math.sqrt(xp1 * (1 - x));
2096                    } else {
2097                        // This deviates from Hull et al's paper as per
2098                        // https://svn.boost.org/trac/boost/ticket/7290
2099                        if ((Double.MAX_VALUE / xp1) > xm1) {
2100                            // xp1 * xm1 won't overflow:
2101                            re = y / Math.sqrt(xm1 * xp1);
2102                            im = Math.log1p(xm1 + Math.sqrt(xp1 * xm1));
2103                        } else {
2104                            re = y / x;
2105                            im = LN_2 + Math.log(x);
2106                        }
2107                    }
2108                } else if (y <= SAFE_MIN) {
2109                    // Hull et al: Assume x == 1.
2110                    // True if:
2111                    // E^2 > 8*sqrt(u)
2112                    //
2113                    // E = Machine epsilon: (1 + epsilon) = 1
2114                    // u = Double.MIN_NORMAL
2115                    re = Math.sqrt(y);
2116                    im = Math.sqrt(y);
2117                } else if (EPSILON * y - 1 >= x) {
2118                    re = PI_OVER_2;
2119                    im = LN_2 + Math.log(y);
2120                } else if (x > 1) {
2121                    re = Math.atan(y / x);
2122                    final double xoy = x / y;
2123                    im = LN_2 + Math.log(y) + 0.5 * Math.log1p(xoy * xoy);
2124                } else {
2125                    re = PI_OVER_2;
2126                    final double a = Math.sqrt(1 + y * y);
2127                    im = 0.5 * Math.log1p(2 * y * (y + a));
2128                }
2129            }
2130        }
2131
2132        return constructor.create(negative(real) ? Math.PI - re : re,
2133                                  negative(imaginary) ? im : -im);
2134    }
2135
2136    /**
2137     * Returns the
2138     * <a href="http://mathworld.wolfram.com/InverseTangent.html">
2139     * inverse tangent</a> of this complex number.
2140     *
2141     * <p>\[ \tan^{-1}(z) = \frac{i}{2} \ln \left( \frac{i + z}{i - z} \right) \]
2142     *
2143     * <p>The inverse hyperbolic tangent of \( z \) is unbounded along the imaginary axis and
2144     * in the range \( [-\pi/2, \pi/2] \) along the real axis.
2145     *
2146     * <p>The inverse tangent is a multivalued function and requires a branch cut in
2147     * the complex plane; the cut is conventionally placed at the line segments
2148     * \( (i \infty,-i] \) and \( [i,i \infty) \) of the imaginary axis.
2149     *
2150     * <p>As per the C99 standard this function is computed using the trigonomic identity:
2151     * \[ \tan^{-1}(z) = -i \tanh^{-1}(iz) \]
2152     *
2153     * @return The inverse tangent of this complex number.
2154     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcTan/">ArcTan</a>
2155     */
2156    public Complex atan() {
2157        // Define in terms of atanh
2158        // atan(z) = -i atanh(iz)
2159        // Multiply this number by I, compute atanh, then multiply by back
2160        return atanh(-imaginary, real, Complex::multiplyNegativeI);
2161    }
2162
2163    /**
2164     * Returns the
2165     * <a href="http://mathworld.wolfram.com/HyperbolicSine.html">
2166     * hyperbolic sine</a> of this complex number.
2167     *
2168     * <p>\[ \sinh(z) = \frac{1}{2} \left( e^{z} - e^{-z} \right) \]
2169     *
2170     * <p>The hyperbolic sine of \( z \) is an entire function in the complex plane
2171     * and is periodic with respect to the imaginary component with period \( 2\pi i \).
2172     * Special cases:
2173     *
2174     * <ul>
2175     * <li>{@code z.conj().sinh() == z.sinh().conj()}.
2176     * <li>This is an odd function: \( \sinh(z) = -\sinh(-z) \).
2177     * <li>If {@code z} is +0 + i0, returns +0 + i0.
2178     * <li>If {@code z} is +0 + i∞, returns ±0 + iNaN (where the sign of the real part of the result is unspecified; "invalid" floating-point operation).
2179     * <li>If {@code z} is +0 + iNaN, returns ±0 + iNaN (where the sign of the real part of the result is unspecified).
2180     * <li>If {@code z} is x + i∞ for positive finite x, returns NaN + iNaN ("invalid" floating-point operation).
2181     * <li>If {@code z} is x + iNaN for finite nonzero x, returns NaN + iNaN ("invalid" floating-point operation).
2182     * <li>If {@code z} is +∞ + i0, returns +∞ + i0.
2183     * <li>If {@code z} is +∞ + iy for positive finite y, returns +∞ cis(y) (see {@link #ofCis(double)}.
2184     * <li>If {@code z} is +∞ + i∞, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified; "invalid" floating-point operation).
2185     * <li>If {@code z} is +∞ + iNaN, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified).
2186     * <li>If {@code z} is NaN + i0, returns NaN + i0.
2187     * <li>If {@code z} is NaN + iy for all nonzero numbers y, returns NaN + iNaN ("invalid" floating-point operation).
2188     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
2189     * </ul>
2190     *
2191     * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
2192     *
2193     * <p>\[ \sinh(x + iy) = \sinh(x)\cos(y) + i \cosh(x)\sin(y) \]
2194     *
2195     * @return The hyperbolic sine of this complex number.
2196     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Sinh/">Sinh</a>
2197     */
2198    public Complex sinh() {
2199        return sinh(real, imaginary, Complex::ofCartesian);
2200    }
2201
2202    /**
2203     * Returns the hyperbolic sine of the complex number.
2204     *
2205     * <p>This function exists to allow implementation of the identity
2206     * {@code sin(z) = -i sinh(iz)}.<p>
2207     *
2208     * @param real Real part.
2209     * @param imaginary Imaginary part.
2210     * @param constructor Constructor.
2211     * @return The hyperbolic sine of the complex number.
2212     */
2213    private static Complex sinh(double real, double imaginary, ComplexConstructor constructor) {
2214        if (Double.isInfinite(real) && !Double.isFinite(imaginary)) {
2215            return constructor.create(real, Double.NaN);
2216        }
2217        if (real == 0) {
2218            // Imaginary-only sinh(iy) = i sin(y).
2219            if (Double.isFinite(imaginary)) {
2220                // Maintain periodic property with respect to the imaginary component.
2221                // sinh(+/-0.0) * cos(+/-x) = +/-0 * cos(x)
2222                return constructor.create(changeSign(real, Math.cos(imaginary)),
2223                                          Math.sin(imaginary));
2224            }
2225            // If imaginary is inf/NaN the sign of the real part is unspecified.
2226            // Returning the same real value maintains the conjugate equality.
2227            // It is not possible to also maintain the odd function (hence the unspecified sign).
2228            return constructor.create(real, Double.NaN);
2229        }
2230        if (imaginary == 0) {
2231            // Real-only sinh(x).
2232            return constructor.create(Math.sinh(real), imaginary);
2233        }
2234        final double x = Math.abs(real);
2235        if (x > SAFE_EXP) {
2236            // Approximate sinh/cosh(x) using exp^|x| / 2
2237            return coshsinh(x, real, imaginary, true, constructor);
2238        }
2239        // No overflow of sinh/cosh
2240        return constructor.create(Math.sinh(real) * Math.cos(imaginary),
2241                                  Math.cosh(real) * Math.sin(imaginary));
2242    }
2243
2244    /**
2245     * Returns the
2246     * <a href="http://mathworld.wolfram.com/HyperbolicCosine.html">
2247     * hyperbolic cosine</a> of this complex number.
2248     *
2249     * <p>\[ \cosh(z) = \frac{1}{2} \left( e^{z} + e^{-z} \right) \]
2250     *
2251     * <p>The hyperbolic cosine of \( z \) is an entire function in the complex plane
2252     * and is periodic with respect to the imaginary component with period \( 2\pi i \).
2253     * Special cases:
2254     *
2255     * <ul>
2256     * <li>{@code z.conj().cosh() == z.cosh().conj()}.
2257     * <li>This is an even function: \( \cosh(z) = \cosh(-z) \).
2258     * <li>If {@code z} is +0 + i0, returns 1 + i0.
2259     * <li>If {@code z} is +0 + i∞, returns NaN ± i0 (where the sign of the imaginary part of the result is unspecified; "invalid" floating-point operation).
2260     * <li>If {@code z} is +0 + iNaN, returns NaN ± i0 (where the sign of the imaginary part of the result is unspecified).
2261     * <li>If {@code z} is x + i∞ for finite nonzero x, returns NaN + iNaN ("invalid" floating-point operation).
2262     * <li>If {@code z} is x + iNaN for finite nonzero x, returns NaN + iNaN ("invalid" floating-point operation).
2263     * <li>If {@code z} is +∞ + i0, returns +∞ + i0.
2264     * <li>If {@code z} is +∞ + iy for finite nonzero y, returns +∞ cis(y) (see {@link #ofCis(double)}).
2265     * <li>If {@code z} is +∞ + i∞, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified).
2266     * <li>If {@code z} is +∞ + iNaN, returns +∞ + iNaN.
2267     * <li>If {@code z} is NaN + i0, returns NaN ± i0 (where the sign of the imaginary part of the result is unspecified).
2268     * <li>If {@code z} is NaN + iy for all nonzero numbers y, returns NaN + iNaN ("invalid" floating-point operation).
2269     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
2270     * </ul>
2271     *
2272     * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
2273     *
2274     * <p>\[ \cosh(x + iy) = \cosh(x)\cos(y) + i \sinh(x)\sin(y) \]
2275     *
2276     * @return The hyperbolic cosine of this complex number.
2277     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Cosh/">Cosh</a>
2278     */
2279    public Complex cosh() {
2280        return cosh(real, imaginary, Complex::ofCartesian);
2281    }
2282
2283    /**
2284     * Returns the hyperbolic cosine of the complex number.
2285     *
2286     * <p>This function exists to allow implementation of the identity
2287     * {@code cos(z) = cosh(iz)}.<p>
2288     *
2289     * @param real Real part.
2290     * @param imaginary Imaginary part.
2291     * @param constructor Constructor.
2292     * @return The hyperbolic cosine of the complex number.
2293     */
2294    private static Complex cosh(double real, double imaginary, ComplexConstructor constructor) {
2295        // ISO C99: Preserve the even function by mapping to positive
2296        // f(z) = f(-z)
2297        if (Double.isInfinite(real) && !Double.isFinite(imaginary)) {
2298            return constructor.create(Math.abs(real), Double.NaN);
2299        }
2300        if (real == 0) {
2301            // Imaginary-only cosh(iy) = cos(y).
2302            if (Double.isFinite(imaginary)) {
2303                // Maintain periodic property with respect to the imaginary component.
2304                // sinh(+/-0.0) * sin(+/-x) = +/-0 * sin(x)
2305                return constructor.create(Math.cos(imaginary),
2306                                          changeSign(real, Math.sin(imaginary)));
2307            }
2308            // If imaginary is inf/NaN the sign of the imaginary part is unspecified.
2309            // Although not required by C99 changing the sign maintains the conjugate equality.
2310            // It is not possible to also maintain the even function (hence the unspecified sign).
2311            return constructor.create(Double.NaN, changeSign(real, imaginary));
2312        }
2313        if (imaginary == 0) {
2314            // Real-only cosh(x).
2315            // Change sign to preserve conjugate equality and even function.
2316            // sin(+/-0) * sinh(+/-x) = +/-0 * +/-a (sinh is monotonic and same sign)
2317            // => change the sign of imaginary using real. Handles special case of infinite real.
2318            // If real is NaN the sign of the imaginary part is unspecified.
2319            return constructor.create(Math.cosh(real), changeSign(imaginary, real));
2320        }
2321        final double x = Math.abs(real);
2322        if (x > SAFE_EXP) {
2323            // Approximate sinh/cosh(x) using exp^|x| / 2
2324            return coshsinh(x, real, imaginary, false, constructor);
2325        }
2326        // No overflow of sinh/cosh
2327        return constructor.create(Math.cosh(real) * Math.cos(imaginary),
2328                                  Math.sinh(real) * Math.sin(imaginary));
2329    }
2330
2331    /**
2332     * Compute cosh or sinh when the absolute real component |x| is large. In this case
2333     * cosh(x) and sinh(x) can be approximated by exp(|x|) / 2:
2334     *
2335     * <pre>
2336     * cosh(x+iy) real = (e^|x| / 2) * cos(y)
2337     * cosh(x+iy) imag = (e^|x| / 2) * sin(y) * sign(x)
2338     * sinh(x+iy) real = (e^|x| / 2) * cos(y) * sign(x)
2339     * sinh(x+iy) imag = (e^|x| / 2) * sin(y)
2340     * </pre>
2341     *
2342     * @param x Absolute real component |x|.
2343     * @param real Real part (x).
2344     * @param imaginary Imaginary part (y).
2345     * @param sinh Set to true to compute sinh, otherwise cosh.
2346     * @param constructor Constructor.
2347     * @return The hyperbolic sine/cosine of the complex number.
2348     */
2349    private static Complex coshsinh(double x, double real, double imaginary, boolean sinh,
2350                                    ComplexConstructor constructor) {
2351        // Always require the cos and sin.
2352        double re = Math.cos(imaginary);
2353        double im = Math.sin(imaginary);
2354        // Compute the correct function
2355        if (sinh) {
2356            re = changeSign(re, real);
2357        } else {
2358            im = changeSign(im, real);
2359        }
2360        // Multiply by (e^|x| / 2).
2361        // Overflow safe computation since sin/cos can be very small allowing a result
2362        // when e^x overflows: e^x / 2 = (e^m / 2) * e^m * e^(x-2m)
2363        if (x > SAFE_EXP * 3) {
2364            // e^x > e^m * e^m * e^m
2365            // y * (e^m / 2) * e^m * e^m will overflow when starting with Double.MIN_VALUE.
2366            // Note: Do not multiply by +inf to safeguard against sin(y)=0.0 which
2367            // will create 0 * inf = nan.
2368            re *= Double.MAX_VALUE * Double.MAX_VALUE * Double.MAX_VALUE;
2369            im *= Double.MAX_VALUE * Double.MAX_VALUE * Double.MAX_VALUE;
2370        } else {
2371            // Initial part of (e^x / 2) using (e^m / 2)
2372            re *= EXP_M / 2;
2373            im *= EXP_M / 2;
2374            double xm;
2375            if (x > SAFE_EXP * 2) {
2376                // e^x = e^m * e^m * e^(x-2m)
2377                re *= EXP_M;
2378                im *= EXP_M;
2379                xm = x - SAFE_EXP * 2;
2380            } else {
2381                // e^x = e^m * e^(x-m)
2382                xm = x - SAFE_EXP;
2383            }
2384            final double exp = Math.exp(xm);
2385            re *= exp;
2386            im *= exp;
2387        }
2388        return constructor.create(re, im);
2389    }
2390
2391    /**
2392     * Returns the
2393     * <a href="http://mathworld.wolfram.com/HyperbolicTangent.html">
2394     * hyperbolic tangent</a> of this complex number.
2395     *
2396     * <p>\[ \tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}} \]
2397     *
2398     * <p>The hyperbolic tangent of \( z \) is an entire function in the complex plane
2399     * and is periodic with respect to the imaginary component with period \( \pi i \)
2400     * and has poles of the first order along the imaginary line, at coordinates
2401     * \( (0, \pi(\frac{1}{2} + n)) \).
2402     * Note that the {@code double} floating-point representation is unable to exactly represent
2403     * \( \pi/2 \) and there is no value for which a pole error occurs. Special cases:
2404     *
2405     * <ul>
2406     * <li>{@code z.conj().tanh() == z.tanh().conj()}.
2407     * <li>This is an odd function: \( \tanh(z) = -\tanh(-z) \).
2408     * <li>If {@code z} is +0 + i0, returns +0 + i0.
2409     * <li>If {@code z} is 0 + i∞, returns 0 + iNaN.
2410     * <li>If {@code z} is x + i∞ for finite non-zero x, returns NaN + iNaN ("invalid" floating-point operation).
2411     * <li>If {@code z} is 0 + iNaN, returns 0 + iNAN.
2412     * <li>If {@code z} is x + iNaN for finite non-zero x, returns NaN + iNaN ("invalid" floating-point operation).
2413     * <li>If {@code z} is +∞ + iy for positive-signed finite y, returns 1 + i0 sin(2y).
2414     * <li>If {@code z} is +∞ + i∞, returns 1 ± i0 (where the sign of the imaginary part of the result is unspecified).
2415     * <li>If {@code z} is +∞ + iNaN, returns 1 ± i0 (where the sign of the imaginary part of the result is unspecified).
2416     * <li>If {@code z} is NaN + i0, returns NaN + i0.
2417     * <li>If {@code z} is NaN + iy for all nonzero numbers y, returns NaN + iNaN ("invalid" floating-point operation).
2418     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
2419     * </ul>
2420     *
2421     * <p>Special cases include the technical corrigendum
2422     * <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471">
2423     * DR 471: Complex math functions cacosh and ctanh</a>.
2424     *
2425     * <p>This is defined using real \( x \) and imaginary \( y \) parts:
2426     *
2427     * <p>\[ \tan(x + iy) = \frac{\sinh(2x)}{\cosh(2x)+\cos(2y)} + i \frac{\sin(2y)}{\cosh(2x)+\cos(2y)} \]
2428     *
2429     * <p>The implementation uses double-angle identities to avoid overflow of {@code 2x}
2430     * and {@code 2y}.
2431     *
2432     * @return The hyperbolic tangent of this complex number.
2433     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Tanh/">Tanh</a>
2434     */
2435    public Complex tanh() {
2436        return tanh(real, imaginary, Complex::ofCartesian);
2437    }
2438
2439    /**
2440     * Returns the hyperbolic tangent of this complex number.
2441     *
2442     * <p>This function exists to allow implementation of the identity
2443     * {@code tan(z) = -i tanh(iz)}.<p>
2444     *
2445     * @param real Real part.
2446     * @param imaginary Imaginary part.
2447     * @param constructor Constructor.
2448     * @return The hyperbolic tangent of the complex number.
2449     */
2450    private static Complex tanh(double real, double imaginary, ComplexConstructor constructor) {
2451        // Cache the absolute real value
2452        final double x = Math.abs(real);
2453
2454        // Handle inf or nan.
2455        if (!isPosFinite(x) || !Double.isFinite(imaginary)) {
2456            if (isPosInfinite(x)) {
2457                if (Double.isFinite(imaginary)) {
2458                    // The sign is copied from sin(2y)
2459                    // The identity sin(2a) = 2 sin(a) cos(a) is used for consistency
2460                    // with the computation below. Only the magnitude is important
2461                    // so drop the 2. When |y| is small sign(sin(2y)) = sign(y).
2462                    final double sign = Math.abs(imaginary) < PI_OVER_2 ?
2463                                        imaginary :
2464                                        Math.sin(imaginary) * Math.cos(imaginary);
2465                    return constructor.create(Math.copySign(1, real),
2466                                              Math.copySign(0, sign));
2467                }
2468                // imaginary is infinite or NaN
2469                return constructor.create(Math.copySign(1, real), Math.copySign(0, imaginary));
2470            }
2471            // Remaining cases:
2472            // (0 + i inf), returns (0 + i NaN)
2473            // (0 + i NaN), returns (0 + i NaN)
2474            // (x + i inf), returns (NaN + i NaN) for non-zero x (including infinite)
2475            // (x + i NaN), returns (NaN + i NaN) for non-zero x (including infinite)
2476            // (NaN + i 0), returns (NaN + i 0)
2477            // (NaN + i y), returns (NaN + i NaN) for non-zero y (including infinite)
2478            // (NaN + i NaN), returns (NaN + i NaN)
2479            return constructor.create(real == 0 ? real : Double.NaN,
2480                                      imaginary == 0 ? imaginary : Double.NaN);
2481        }
2482
2483        // Finite components
2484        // tanh(x+iy) = (sinh(2x) + i sin(2y)) / (cosh(2x) + cos(2y))
2485
2486        if (real == 0) {
2487            // Imaginary-only tanh(iy) = i tan(y)
2488            // Identity: sin 2y / (1 + cos 2y) = tan(y)
2489            return constructor.create(real, Math.tan(imaginary));
2490        }
2491        if (imaginary == 0) {
2492            // Identity: sinh 2x / (1 + cosh 2x) = tanh(x)
2493            return constructor.create(Math.tanh(real), imaginary);
2494        }
2495
2496        // The double angles can be avoided using the identities:
2497        // sinh(2x) = 2 sinh(x) cosh(x)
2498        // sin(2y) = 2 sin(y) cos(y)
2499        // cosh(2x) = 2 sinh^2(x) + 1
2500        // cos(2y) = 2 cos^2(y) - 1
2501        // tanh(x+iy) = (sinh(x)cosh(x) + i sin(y)cos(y)) / (sinh^2(x) + cos^2(y))
2502        // To avoid a junction when swapping between the double angles and the identities
2503        // the identities are used in all cases.
2504
2505        if (x > SAFE_EXP / 2) {
2506            // Potential overflow in sinh/cosh(2x).
2507            // Approximate sinh/cosh using exp^x.
2508            // Ignore cos^2(y) in the divisor as it is insignificant.
2509            // real = sinh(x)cosh(x) / sinh^2(x) = +/-1
2510            final double re = Math.copySign(1, real);
2511            // imag = sin(2y) / 2 sinh^2(x)
2512            // sinh(x) -> sign(x) * e^|x| / 2 when x is large.
2513            // sinh^2(x) -> e^2|x| / 4 when x is large.
2514            // imag = sin(2y) / 2 (e^2|x| / 4) = 2 sin(2y) / e^2|x|
2515            //      = 4 * sin(y) cos(y) / e^2|x|
2516            // Underflow safe divide as e^2|x| may overflow:
2517            // imag = 4 * sin(y) cos(y) / e^m / e^(2|x| - m)
2518            // (|im| is a maximum of 2)
2519            double im = Math.sin(imaginary) * Math.cos(imaginary);
2520            if (x > SAFE_EXP) {
2521                // e^2|x| > e^m * e^m
2522                // This will underflow 2.0 / e^m / e^m
2523                im = Math.copySign(0.0, im);
2524            } else {
2525                // e^2|x| = e^m * e^(2|x| - m)
2526                im = 4 * im / EXP_M / Math.exp(2 * x - SAFE_EXP);
2527            }
2528            return constructor.create(re, im);
2529        }
2530
2531        // No overflow of sinh(2x) and cosh(2x)
2532
2533        // Note: This does not use the definitional formula but uses the identity:
2534        // tanh(x+iy) = (sinh(x)cosh(x) + i sin(y)cos(y)) / (sinh^2(x) + cos^2(y))
2535
2536        final double sinhx = Math.sinh(real);
2537        final double coshx = Math.cosh(real);
2538        final double siny = Math.sin(imaginary);
2539        final double cosy = Math.cos(imaginary);
2540        final double divisor = sinhx * sinhx + cosy * cosy;
2541        return constructor.create(sinhx * coshx / divisor,
2542                                  siny * cosy / divisor);
2543    }
2544
2545    /**
2546     * Returns the
2547     * <a href="http://mathworld.wolfram.com/InverseHyperbolicSine.html">
2548     * inverse hyperbolic sine</a> of this complex number.
2549     *
2550     * <p>\[ \sinh^{-1}(z) = \ln \left(z + \sqrt{1 + z^2} \right) \]
2551     *
2552     * <p>The inverse hyperbolic sine of \( z \) is unbounded along the real axis and
2553     * in the range \( [-\pi, \pi] \) along the imaginary axis. Special cases:
2554     *
2555     * <ul>
2556     * <li>{@code z.conj().asinh() == z.asinh().conj()}.
2557     * <li>This is an odd function: \( \sinh^{-1}(z) = -\sinh^{-1}(-z) \).
2558     * <li>If {@code z} is +0 + i0, returns 0 + i0.
2559     * <li>If {@code z} is x + i∞ for positive-signed finite x, returns +∞ + iπ/2.
2560     * <li>If {@code z} is x + iNaN for finite x, returns NaN + iNaN ("invalid" floating-point operation).
2561     * <li>If {@code z} is +∞ + iy for positive-signed finite y, returns +∞ + i0.
2562     * <li>If {@code z} is +∞ + i∞, returns +∞ + iπ/4.
2563     * <li>If {@code z} is +∞ + iNaN, returns +∞ + iNaN.
2564     * <li>If {@code z} is NaN + i0, returns NaN + i0.
2565     * <li>If {@code z} is NaN + iy for finite nonzero y, returns NaN + iNaN ("invalid" floating-point operation).
2566     * <li>If {@code z} is NaN + i∞, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified).
2567     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
2568     * </ul>
2569     *
2570     * <p>The inverse hyperbolic sine is a multivalued function and requires a branch cut in
2571     * the complex plane; the cut is conventionally placed at the line segments
2572     * \( (-i \infty,-i) \) and \( (i,i \infty) \) of the imaginary axis.
2573     *
2574     * <p>This function is computed using the trigonomic identity:
2575     *
2576     * <p>\[ \sinh^{-1}(z) = -i \sin^{-1}(iz) \]
2577     *
2578     * @return The inverse hyperbolic sine of this complex number.
2579     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcSinh/">ArcSinh</a>
2580     */
2581    public Complex asinh() {
2582        // Define in terms of asin
2583        // asinh(z) = -i asin(iz)
2584        // Note: This is the opposite to the identity defined in the C99 standard:
2585        // asin(z) = -i asinh(iz)
2586        // Multiply this number by I, compute asin, then multiply by back
2587        return asin(-imaginary, real, Complex::multiplyNegativeI);
2588    }
2589
2590    /**
2591     * Returns the
2592     * <a href="http://mathworld.wolfram.com/InverseHyperbolicCosine.html">
2593     * inverse hyperbolic cosine</a> of this complex number.
2594     *
2595     * <p>\[ \cosh^{-1}(z) = \ln \left(z + \sqrt{z + 1} \sqrt{z - 1} \right) \]
2596     *
2597     * <p>The inverse hyperbolic cosine of \( z \) is in the range \( [0, \infty) \) along the
2598     * real axis and in the range \( [-\pi, \pi] \) along the imaginary axis. Special cases:
2599     *
2600     * <ul>
2601     * <li>{@code z.conj().acosh() == z.acosh().conj()}.
2602     * <li>If {@code z} is ±0 + i0, returns +0 + iπ/2.
2603     * <li>If {@code z} is x + i∞ for finite x, returns +∞ + iπ/2.
2604     * <li>If {@code z} is 0 + iNaN, returns NaN + iπ/2 <sup>[1]</sup>.
2605     * <li>If {@code z} is x + iNaN for finite non-zero x, returns NaN + iNaN ("invalid" floating-point operation).
2606     * <li>If {@code z} is −∞ + iy for positive-signed finite y, returns +∞ + iπ.
2607     * <li>If {@code z} is +∞ + iy for positive-signed finite y, returns +∞ + i0.
2608     * <li>If {@code z} is −∞ + i∞, returns +∞ + i3π/4.
2609     * <li>If {@code z} is +∞ + i∞, returns +∞ + iπ/4.
2610     * <li>If {@code z} is ±∞ + iNaN, returns +∞ + iNaN.
2611     * <li>If {@code z} is NaN + iy for finite y, returns NaN + iNaN ("invalid" floating-point operation).
2612     * <li>If {@code z} is NaN + i∞, returns +∞ + iNaN.
2613     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
2614     * </ul>
2615     *
2616     * <p>Special cases include the technical corrigendum
2617     * <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471">
2618     * DR 471: Complex math functions cacosh and ctanh</a>.
2619     *
2620     * <p>The inverse hyperbolic cosine is a multivalued function and requires a branch cut in
2621     * the complex plane; the cut is conventionally placed at the line segment
2622     * \( (-\infty,-1) \) of the real axis.
2623     *
2624     * <p>This function is computed using the trigonomic identity:
2625     *
2626     * <p>\[ \cosh^{-1}(z) = \pm i \cos^{-1}(z) \]
2627     *
2628     * <p>The sign of the multiplier is chosen to give {@code z.acosh().real() >= 0}
2629     * and compatibility with the C99 standard.
2630     *
2631     * @return The inverse hyperbolic cosine of this complex number.
2632     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcCosh/">ArcCosh</a>
2633     */
2634    public Complex acosh() {
2635        // Define in terms of acos
2636        // acosh(z) = +-i acos(z)
2637        // Note the special case:
2638        // acos(+-0 + iNaN) = π/2 + iNaN
2639        // acosh(0 + iNaN) = NaN + iπ/2
2640        // will not appropriately multiply by I to maintain positive imaginary if
2641        // acos() imaginary computes as NaN. So do this explicitly.
2642        if (Double.isNaN(imaginary) && real == 0) {
2643            return new Complex(Double.NaN, PI_OVER_2);
2644        }
2645        return acos(real, imaginary, (re, im) ->
2646            // Set the sign appropriately for real >= 0
2647            (negative(im)) ?
2648                // Multiply by I
2649                new Complex(-im, re) :
2650                // Multiply by -I
2651                new Complex(im, -re)
2652        );
2653    }
2654
2655    /**
2656     * Returns the
2657     * <a href="http://mathworld.wolfram.com/InverseHyperbolicTangent.html">
2658     * inverse hyperbolic tangent</a> of this complex number.
2659     *
2660     * <p>\[ \tanh^{-1}(z) = \frac{1}{2} \ln \left( \frac{1 + z}{1 - z} \right) \]
2661     *
2662     * <p>The inverse hyperbolic tangent of \( z \) is unbounded along the real axis and
2663     * in the range \( [-\pi/2, \pi/2] \) along the imaginary axis. Special cases:
2664     *
2665     * <ul>
2666     * <li>{@code z.conj().atanh() == z.atanh().conj()}.
2667     * <li>This is an odd function: \( \tanh^{-1}(z) = -\tanh^{-1}(-z) \).
2668     * <li>If {@code z} is +0 + i0, returns +0 + i0.
2669     * <li>If {@code z} is +0 + iNaN, returns +0 + iNaN.
2670     * <li>If {@code z} is +1 + i0, returns +∞ + i0 ("divide-by-zero" floating-point operation).
2671     * <li>If {@code z} is x + i∞ for finite positive-signed x, returns +0 + iπ/2.
2672     * <li>If {@code z} is x+iNaN for nonzero finite x, returns NaN+iNaN ("invalid" floating-point operation).
2673     * <li>If {@code z} is +∞ + iy for finite positive-signed y, returns +0 + iπ/2.
2674     * <li>If {@code z} is +∞ + i∞, returns +0 + iπ/2.
2675     * <li>If {@code z} is +∞ + iNaN, returns +0 + iNaN.
2676     * <li>If {@code z} is NaN+iy for finite y, returns NaN+iNaN ("invalid" floating-point operation).
2677     * <li>If {@code z} is NaN + i∞, returns ±0 + iπ/2 (where the sign of the real part of the result is unspecified).
2678     * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
2679     * </ul>
2680     *
2681     * <p>The inverse hyperbolic tangent is a multivalued function and requires a branch cut in
2682     * the complex plane; the cut is conventionally placed at the line segments
2683     * \( (\infty,-1] \) and \( [1,\infty) \) of the real axis.
2684     *
2685     * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
2686     *
2687     * <p>\[ \tanh^{-1}(z) = \frac{1}{4} \ln \left(1 + \frac{4x}{(1-x)^2+y^2} \right) + \\
2688     *                     i \frac{1}{2} \left( \tan^{-1} \left(\frac{2y}{1-x^2-y^2} \right) + \frac{\pi}{2} \left(\text{sgn}(x^2+y^2-1)+1 \right) \text{sgn}(y) \right) \]
2689     *
2690     * <p>The imaginary part is computed using {@link Math#atan2(double, double)} to ensure the
2691     * correct quadrant is returned from \( \tan^{-1} \left(\frac{2y}{1-x^2-y^2} \right) \).
2692     *
2693     * <p>The code has been adapted from the <a href="https://www.boost.org/">Boost</a>
2694     * {@code c++} implementation {@code <boost/math/complex/atanh.hpp>}.
2695     *
2696     * @return The inverse hyperbolic tangent of this complex number.
2697     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcTanh/">ArcTanh</a>
2698     */
2699    public Complex atanh() {
2700        return atanh(real, imaginary, Complex::ofCartesian);
2701    }
2702
2703    /**
2704     * Returns the inverse hyperbolic tangent of this complex number.
2705     *
2706     * <p>This function exists to allow implementation of the identity
2707     * {@code atan(z) = -i atanh(iz)}.
2708     *
2709     * <p>Adapted from {@code <boost/math/complex/atanh.hpp>}. This method only (and not
2710     * invoked methods within) is distributed under the Boost Software License V1.0.
2711     * The original notice is shown below and the licence is shown in full in LICENSE:
2712     * <pre>
2713     * (C) Copyright John Maddock 2005.
2714     * Distributed under the Boost Software License, Version 1.0. (See accompanying
2715     * file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
2716     * </pre>
2717     *
2718     * @param real Real part.
2719     * @param imaginary Imaginary part.
2720     * @param constructor Constructor.
2721     * @return The inverse hyperbolic tangent of the complex number.
2722     */
2723    private static Complex atanh(final double real, final double imaginary,
2724                                 final ComplexConstructor constructor) {
2725        // Compute with positive values and determine sign at the end
2726        double x = Math.abs(real);
2727        double y = Math.abs(imaginary);
2728        // The result (without sign correction)
2729        double re;
2730        double im;
2731
2732        // Handle C99 special cases
2733        if (Double.isNaN(x)) {
2734            if (isPosInfinite(y)) {
2735                // The sign of the real part of the result is unspecified
2736                return constructor.create(0, Math.copySign(PI_OVER_2, imaginary));
2737            }
2738            // No-use of the input constructor.
2739            // Optionally raises the ‘‘invalid’’ floating-point exception, for finite y.
2740            return NAN;
2741        } else if (Double.isNaN(y)) {
2742            if (isPosInfinite(x)) {
2743                return constructor.create(Math.copySign(0, real), Double.NaN);
2744            }
2745            if (x == 0) {
2746                return constructor.create(real, Double.NaN);
2747            }
2748            // No-use of the input constructor
2749            return NAN;
2750        } else {
2751            // x && y are finite or infinite.
2752
2753            // Check the safe region.
2754            // The lower and upper bounds have been copied from boost::math::atanh.
2755            // They are different from the safe region for asin and acos.
2756            // x >= SAFE_UPPER: (1-x) == -x
2757            // x <= SAFE_LOWER: 1 - x^2 = 1
2758
2759            if (inRegion(x, y, SAFE_LOWER, SAFE_UPPER)) {
2760                // Normal computation within a safe region.
2761
2762                // minus x plus 1: (-x+1)
2763                final double mxp1 = 1 - x;
2764                final double yy = y * y;
2765                // The definition of real component is:
2766                // real = log( ((x+1)^2+y^2) / ((1-x)^2+y^2) ) / 4
2767                // This simplifies by adding 1 and subtracting 1 as a fraction:
2768                //      = log(1 + ((x+1)^2+y^2) / ((1-x)^2+y^2) - ((1-x)^2+y^2)/((1-x)^2+y^2) ) / 4
2769                //
2770                // real(atanh(z)) == log(1 + 4*x / ((1-x)^2+y^2)) / 4
2771                // imag(atanh(z)) == tan^-1 (2y, (1-x)(1+x) - y^2) / 2
2772                // imag(atanh(z)) == tan^-1 (2y, (1 - x^2 - y^2) / 2
2773                // The division is done at the end of the function.
2774                re = Math.log1p(4 * x / (mxp1 * mxp1 + yy));
2775                // Modified from boost which does not switch the magnitude of x and y.
2776                // The denominator for atan2 is 1 - x^2 - y^2.
2777                // This can be made more precise if |x| > |y|.
2778                final double numerator = 2 * y;
2779                double denominator;
2780                if (x < y) {
2781                    final double tmp = x;
2782                    x = y;
2783                    y = tmp;
2784                }
2785                // 1 - x is precise if |x| >= 1
2786                if (x >= 1) {
2787                    denominator = (1 - x) * (1 + x) - y * y;
2788                } else {
2789                    // |x| < 1: Use high precision if possible:
2790                    // 1 - x^2 - y^2 = -(x^2 + y^2 - 1)
2791                    // Modified from boost to use the custom high precision method.
2792                    denominator = -x2y2m1(x, y);
2793                }
2794                im = Math.atan2(numerator, denominator);
2795            } else {
2796                // This section handles exception cases that would normally cause
2797                // underflow or overflow in the main formulas.
2798
2799                // C99. G.7: Special case for imaginary only numbers
2800                if (x == 0) {
2801                    if (imaginary == 0) {
2802                        return constructor.create(real, imaginary);
2803                    }
2804                    // atanh(iy) = i atan(y)
2805                    return constructor.create(real, Math.atan(imaginary));
2806                }
2807
2808                // Real part:
2809                // real = Math.log1p(4x / ((1-x)^2 + y^2))
2810                // real = Math.log1p(4x / (1 - 2x + x^2 + y^2))
2811                // real = Math.log1p(4x / (1 + x(x-2) + y^2))
2812                // without either overflow or underflow in the squared terms.
2813                if (x >= SAFE_UPPER) {
2814                    // (1-x) = -x to machine precision:
2815                    // log1p(4x / (x^2 + y^2))
2816                    if (isPosInfinite(x) || isPosInfinite(y)) {
2817                        re = 0;
2818                    } else if (y >= SAFE_UPPER) {
2819                        // Big x and y: divide by x*y
2820                        re = Math.log1p((4 / y) / (x / y + y / x));
2821                    } else if (y > 1) {
2822                        // Big x: divide through by x:
2823                        re = Math.log1p(4 / (x + y * y / x));
2824                    } else {
2825                        // Big x small y, as above but neglect y^2/x:
2826                        re = Math.log1p(4 / x);
2827                    }
2828                } else if (y >= SAFE_UPPER) {
2829                    if (x > 1) {
2830                        // Big y, medium x, divide through by y:
2831                        final double mxp1 = 1 - x;
2832                        re = Math.log1p((4 * x / y) / (mxp1 * mxp1 / y + y));
2833                    } else {
2834                        // Big y, small x, as above but neglect (1-x)^2/y:
2835                        // Note: log1p(v) == v - v^2/2 + v^3/3 ... Taylor series when v is small.
2836                        // Here v is so small only the first term matters.
2837                        re = 4 * x / y / y;
2838                    }
2839                } else if (x == 1) {
2840                    // x = 1, small y:
2841                    // Special case when x == 1 as (1-x) is invalid.
2842                    // Simplify the following formula:
2843                    // real = log( sqrt((x+1)^2+y^2) ) / 2 - log( sqrt((1-x)^2+y^2) ) / 2
2844                    //      = log( sqrt(4+y^2) ) / 2 - log(y) / 2
2845                    // if: 4+y^2 -> 4
2846                    //      = log( 2 ) / 2 - log(y) / 2
2847                    //      = (log(2) - log(y)) / 2
2848                    // Multiply by 2 as it will be divided by 4 at the end.
2849                    // C99: if y=0 raises the ‘‘divide-by-zero’’ floating-point exception.
2850                    re = 2 * (LN_2 - Math.log(y));
2851                } else {
2852                    // Modified from boost which checks y > SAFE_LOWER.
2853                    // if y*y -> 0 it will be ignored so always include it.
2854                    final double mxp1 = 1 - x;
2855                    re = Math.log1p((4 * x) / (mxp1 * mxp1 + y * y));
2856                }
2857
2858                // Imaginary part:
2859                // imag = atan2(2y, (1-x)(1+x) - y^2)
2860                // if x or y are large, then the formula:
2861                //   atan2(2y, (1-x)(1+x) - y^2)
2862                // evaluates to +(PI - theta) where theta is negligible compared to PI.
2863                if ((x >= SAFE_UPPER) || (y >= SAFE_UPPER)) {
2864                    im = Math.PI;
2865                } else if (x <= SAFE_LOWER) {
2866                    // (1-x)^2 -> 1
2867                    if (y <= SAFE_LOWER) {
2868                        // 1 - y^2 -> 1
2869                        im = Math.atan2(2 * y, 1);
2870                    } else {
2871                        im = Math.atan2(2 * y, 1 - y * y);
2872                    }
2873                } else {
2874                    // Medium x, small y.
2875                    // Modified from boost which checks (y == 0) && (x == 1) and sets re = 0.
2876                    // This is same as the result from calling atan2(0, 0) so exclude this case.
2877                    // 1 - y^2 = 1 so ignore subtracting y^2
2878                    im = Math.atan2(2 * y, (1 - x) * (1 + x));
2879                }
2880            }
2881        }
2882
2883        re /= 4;
2884        im /= 2;
2885        return constructor.create(changeSign(re, real),
2886                                  changeSign(im, imaginary));
2887    }
2888
2889    /**
2890     * Compute {@code x^2 + y^2 - 1} in high precision.
2891     * Assumes that the values x and y can be multiplied without overflow; that
2892     * {@code x >= y}; and both values are positive.
2893     *
2894     * @param x the x value
2895     * @param y the y value
2896     * @return {@code x^2 + y^2 - 1}.
2897     */
2898    private static double x2y2m1(double x, double y) {
2899        // Hull et al used (x-1)*(x+1)+y*y.
2900        // From the paper on page 236:
2901
2902        // If x == 1 there is no cancellation.
2903
2904        // If x > 1, there is also no cancellation, but the argument is now accurate
2905        // only to within a factor of 1 + 3 EPSILSON (note that x – 1 is exact),
2906        // so that error = 3 EPSILON.
2907
2908        // If x < 1, there can be serious cancellation:
2909
2910        // If 4 y^2 < |x^2 – 1| the cancellation is not serious ... the argument is accurate
2911        // only to within a factor of 1 + 4 EPSILSON so that error = 4 EPSILON.
2912
2913        // Otherwise there can be serious cancellation and the relative error in the real part
2914        // could be enormous.
2915
2916        final double xx = x * x;
2917        final double yy = y * y;
2918        // Modify to use high precision before the threshold set by Hull et al.
2919        // This is to preserve the monotonic output of the computation at the switch.
2920        // Set the threshold when x^2 + y^2 is above 0.5 thus subtracting 1 results in a number
2921        // that can be expressed with a higher precision than any number in the range 0.5-1.0
2922        // due to the variable exponent used below 0.5.
2923        if (x < 1 && xx + yy > 0.5) {
2924            // Large relative error.
2925            // This does not use o.a.c.numbers.LinearCombination.value(x, x, y, y, 1, -1).
2926            // It is optimised knowing that:
2927            // - the products are squares
2928            // - the final term is -1 (which does not require split multiplication and addition)
2929            // - The answer will not be NaN as the terms are not NaN components
2930            // - The order is known to be 1 > |x| >= |y|
2931            // The squares are computed using a split multiply algorithm and
2932            // the summation using an extended precision summation algorithm.
2933
2934            // Split x and y as one 26 bits number and one 27 bits number
2935            final double xHigh = splitHigh(x);
2936            final double xLow  = x - xHigh;
2937            final double yHigh = splitHigh(y);
2938            final double yLow  = y - yHigh;
2939
2940            // Accurate split multiplication x * x and y * y
2941            final double x2Low = squareLow(xLow, xHigh, xx);
2942            final double y2Low = squareLow(yLow, yHigh, yy);
2943
2944            return sumx2y2m1(xx, x2Low, yy, y2Low);
2945        }
2946        return (x - 1) * (x + 1) + yy;
2947    }
2948
2949    /**
2950     * Implement Dekker's method to split a value into two parts. Multiplying by (2^s + 1) create
2951     * a big value from which to derive the two split parts.
2952     * <pre>
2953     * c = (2^s + 1) * a
2954     * a_big = c - a
2955     * a_hi = c - a_big
2956     * a_lo = a - a_hi
2957     * a = a_hi + a_lo
2958     * </pre>
2959     *
2960     * <p>The multiplicand must be odd allowing a p-bit value to be split into
2961     * (p-s)-bit value {@code a_hi} and a non-overlapping (s-1)-bit value {@code a_lo}.
2962     * Combined they have (p􏰔-1) bits of significand but the sign bit of {@code a_lo}
2963     * contains a bit of information.
2964     *
2965     * @param a Value.
2966     * @return the high part of the value.
2967     * @see <a href="https://doi.org/10.1007/BF01397083">
2968     * Dekker (1971) A floating-point technique for extending the available precision</a>
2969     */
2970    private static double splitHigh(double a) {
2971        final double c = MULTIPLIER * a;
2972        return c - (c - a);
2973    }
2974
2975    /**
2976     * Compute the round-off from the square of a split number with {@code low} and {@code high}
2977     * components. Uses Dekker's algorithm for split multiplication modified for a square product.
2978     *
2979     * <p>Note: This is candidate to be replaced with {@code Math.fma(x, x, -x * x)} to compute
2980     * the round-off from the square product {@code x * x}. This would remove the requirement
2981     * to compute the split number and make this method redundant. {@code Math.fma} requires
2982     * JDK 9 and FMA hardware support.
2983     *
2984     * @param low Low part of number.
2985     * @param high High part of number.
2986     * @param square Square of the number.
2987     * @return <code>low * low - (((product - high * high) - low * high) - high * low)</code>
2988     * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
2989     * Shewchuk (1997) Theorum 18</a>
2990     */
2991    private static double squareLow(double low, double high, double square) {
2992        final double lh = low * high;
2993        return low * low - (((square - high * high) - lh) - lh);
2994    }
2995
2996    /**
2997     * Compute the round-off from the sum of two numbers {@code a} and {@code b} using
2998     * Dekker's two-sum algorithm. The values are required to be ordered by magnitude:
2999     * {@code |a| >= |b|}.
3000     *
3001     * @param a First part of sum.
3002     * @param b Second part of sum.
3003     * @param x Sum.
3004     * @return <code>b - (x - a)</code>
3005     * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
3006     * Shewchuk (1997) Theorum 6</a>
3007     */
3008    private static double fastSumLow(double a, double b, double x) {
3009        // x = a + b
3010        // bVirtual = x - a
3011        // y = b - bVirtual
3012        return b - (x - a);
3013    }
3014
3015    /**
3016     * Compute the round-off from the sum of two numbers {@code a} and {@code b} using
3017     * Knuth's two-sum algorithm. The values are not required to be ordered by magnitude.
3018     *
3019     * @param a First part of sum.
3020     * @param b Second part of sum.
3021     * @param x Sum.
3022     * @return <code>(a - (x - (x - a))) + (b - (x - a))</code>
3023     * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
3024     * Shewchuk (1997) Theorum 7</a>
3025     */
3026    private static double sumLow(double a, double b, double x) {
3027        // x = a + b
3028        // bVirtual = x - a
3029        // aVirtual = x - bVirtual
3030        // bRoundoff = b - bVirtual
3031        // aRoundoff = a - aVirtual
3032        // y = aRoundoff + bRoundoff
3033        final double bVirtual = x - a;
3034        return (a - (x - bVirtual)) + (b - bVirtual);
3035    }
3036
3037    /**
3038     * Sum x^2 + y^2 - 1. It is assumed that {@code y <= x < 1}.
3039     *
3040     * <p>Implement Shewchuk's expansion-sum algorithm: [x2Low, x2High] + [-1] + [y2Low, y2High].
3041     *
3042     * @param x2High High part of x^2.
3043     * @param x2Low Low part of x^2.
3044     * @param y2High High part of y^2.
3045     * @param y2Low Low part of y^2.
3046     * @return x^2 + y^2 - 1
3047     * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
3048     * Shewchuk (1997) Theorum 12</a>
3049     */
3050    private static double sumx2y2m1(double x2High, double x2Low, double y2High, double y2Low) {
3051        // Let e and f be non-overlapping expansions of components of length m and n.
3052        // The following algorithm will produce a non-overlapping expansion h where the
3053        // sum h_i = e + f and components of h are in increasing order of magnitude.
3054
3055        // Expansion-sum proceeds by a grow-expansion of the first part from one expansion
3056        // into the other, extending its length by 1. The process repeats for the next part
3057        // but the grow-expansion starts at the previous merge position + 1.
3058        // Thus expansion-sum requires mn two-sum operations to merge length m into length n
3059        // resulting in length m+n-1.
3060
3061        // Variables numbered from 1 as per Figure 7 (p.12). The output expansion h is placed
3062        // into e increasing its length for each grow expansion.
3063
3064        // We have two expansions for x^2 and y^2 and the whole number -1.
3065        // Expecting (x^2 + y^2) close to 1 we generate first the intermediate expansion
3066        // (x^2 - 1) moving the result away from 1 where there are sparse floating point
3067        // representations. This is then added to a similar magnitude y^2. Leaving the -1
3068        // until last suffers from 1 ulp rounding errors more often and the requirement
3069        // for a distillation sum to reduce rounding error frequency.
3070
3071        // Note: Do not use the alternative fast-expansion-sum of the parts sorted by magnitude.
3072        // The parts can be ordered with a single comparison into:
3073        // [y2Low, (y2High|x2Low), x2High, -1]
3074        // The fast-two-sum saves 1 fast-two-sum and 3 two-sum operations (21 additions) and
3075        // adds a penalty of a single branch condition.
3076        // However the order in not "strongly non-overlapping" and the fast-expansion-sum
3077        // output will not be strongly non-overlapping. The sum of the output has 1 ulp error
3078        // on random cis numbers approximately 1 in 160 events. This can be removed by a
3079        // distillation two-sum pass over the final expansion as a cost of 1 fast-two-sum and
3080        // 3 two-sum operations! So we use the expansion sum with the same operations and
3081        // no branches.
3082
3083        // q=running sum
3084        double q = x2Low - 1;
3085        double e1 = fastSumLow(-1, x2Low, q);
3086        double e3 = q + x2High;
3087        double e2 = sumLow(q, x2High, e3);
3088
3089        final double f1 = y2Low;
3090        final double f2 = y2High;
3091
3092        // Grow expansion of f1 into e
3093        q = f1 + e1;
3094        e1 = sumLow(f1, e1, q);
3095        double p = q + e2;
3096        e2 = sumLow(q, e2, p);
3097        double e4 = p + e3;
3098        e3 = sumLow(p, e3, e4);
3099
3100        // Grow expansion of f2 into e (only required to start at e2)
3101        q = f2 + e2;
3102        e2 = sumLow(f2, e2, q);
3103        p = q + e3;
3104        e3 = sumLow(q, e3, p);
3105        final double e5 = p + e4;
3106        e4 = sumLow(p, e4, e5);
3107
3108        // Final summation:
3109        // The sum of the parts is within 1 ulp of the true expansion value e:
3110        // |e - sum| < ulp(sum).
3111        // To achieve the exact result requires iteration of a distillation two-sum through
3112        // the expansion until convergence, i.e. no smaller term changes higher terms.
3113        // This requires (n-1) iterations for length n. Here we neglect this as
3114        // although the method is not ensured to be exact is it robust on random
3115        // cis numbers.
3116        return e1 + e2 + e3 + e4 + e5;
3117    }
3118
3119    /**
3120     * Returns the n-th roots of this complex number.
3121     * The nth roots are defined by the formula:
3122     *
3123     * <p>\[ z_k = |z|^{\frac{1}{n}} \left( \cos \left(\phi + \frac{2\pi k}{n} \right) + i \sin \left(\phi + \frac{2\pi k}{n} \right) \right) \]
3124     *
3125     * <p>for \( k=0, 1, \ldots, n-1 \), where \( |z| \) and \( \phi \)
3126     * are respectively the {@link #abs() modulus} and
3127     * {@link #arg() argument} of this complex number.
3128     *
3129     * <p>If one or both parts of this complex number is NaN, a list with all
3130     * all elements set to {@code NaN + i NaN} is returned.</p>
3131     *
3132     * @param n Degree of root.
3133     * @return A list of all {@code n}-th roots of this complex number.
3134     * @throws IllegalArgumentException if {@code n} is zero.
3135     * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Root/">Root</a>
3136     */
3137    public List<Complex> nthRoot(int n) {
3138        if (n == 0) {
3139            throw new IllegalArgumentException("cannot compute zeroth root");
3140        }
3141
3142        final List<Complex> result = new ArrayList<>();
3143
3144        // nth root of abs -- faster / more accurate to use a solver here?
3145        final double nthRootOfAbs = Math.pow(abs(), 1.0 / n);
3146
3147        // Compute nth roots of complex number with k = 0, 1, ... n-1
3148        final double nthPhi = arg() / n;
3149        final double slice = 2 * Math.PI / n;
3150        double innerPart = nthPhi;
3151        for (int k = 0; k < Math.abs(n); k++) {
3152            // inner part
3153            final double realPart = nthRootOfAbs *  Math.cos(innerPart);
3154            final double imaginaryPart = nthRootOfAbs *  Math.sin(innerPart);
3155            result.add(ofCartesian(realPart, imaginaryPart));
3156            innerPart += slice;
3157        }
3158
3159        return result;
3160    }
3161
3162    /**
3163     * Test for equality with another object. If the other object is a {@code Complex} then a
3164     * comparison is made of the real and imaginary parts; otherwise {@code false} is returned.
3165     *
3166     * <p>If both the real and imaginary parts of two complex numbers
3167     * are exactly the same the two {@code Complex} objects are considered to be equal.
3168     * For this purpose, two {@code double} values are considered to be
3169     * the same if and only if the method {@link Double #doubleToLongBits(double)}
3170     * returns the identical {@code long} value when applied to each.
3171     *
3172     * <p>Note that in most cases, for two instances of class
3173     * {@code Complex}, {@code c1} and {@code c2}, the
3174     * value of {@code c1.equals(c2)} is {@code true} if and only if
3175     *
3176     * <pre>
3177     *  {@code c1.getReal() == c2.getReal() && c1.getImaginary() == c2.getImaginary()}</pre>
3178     *
3179     * <p>also has the value {@code true}. However, there are exceptions:
3180     *
3181     * <ul>
3182     *  <li>
3183     *   Instances that contain {@code NaN} values in the same part
3184     *   are considered to be equal for that part, even though {@code Double.NaN == Double.NaN}
3185     *   has the value {@code false}.
3186     *  </li>
3187     *  <li>
3188     *   Instances that share a {@code NaN} value in one part
3189     *   but have different values in the other part are <em>not</em> considered equal.
3190     *  </li>
3191     *  <li>
3192     *   Instances that contain different representations of zero in the same part
3193     *   are <em>not</em> considered to be equal for that part, even though {@code -0.0 == 0.0}
3194     *   has the value {@code true}.
3195     *  </li>
3196     * </ul>
3197     *
3198     * <p>The behavior is the same as if the components of the two complex numbers were passed
3199     * to {@link java.util.Arrays#equals(double[], double[]) Arrays.equals(double[], double[])}:
3200     *
3201     * <pre>
3202     *  Arrays.equals(new double[]{c1.getReal(), c1.getImaginary()},
3203     *                new double[]{c2.getReal(), c2.getImaginary()}); </pre>
3204     *
3205     * @param other Object to test for equality with this instance.
3206     * @return {@code true} if the objects are equal, {@code false} if object
3207     * is {@code null}, not an instance of {@code Complex}, or not equal to
3208     * this instance.
3209     * @see java.lang.Double#doubleToLongBits(double)
3210     * @see java.util.Arrays#equals(double[], double[])
3211     */
3212    @Override
3213    public boolean equals(Object other) {
3214        if (this == other) {
3215            return true;
3216        }
3217        if (other instanceof Complex) {
3218            final Complex c = (Complex) other;
3219            return equals(real, c.real) &&
3220                equals(imaginary, c.imaginary);
3221        }
3222        return false;
3223    }
3224
3225    /**
3226     * Gets a hash code for the complex number.
3227     *
3228     * <p>The behavior is the same as if the components of the complex number were passed
3229     * to {@link java.util.Arrays#hashCode(double[]) Arrays.hashCode(double[])}:
3230     *
3231     * <pre>
3232     *  {@code Arrays.hashCode(new double[] {getReal(), getImaginary()})}</pre>
3233     *
3234     * @return A hash code value for this object.
3235     * @see java.util.Arrays#hashCode(double[]) Arrays.hashCode(double[])
3236     */
3237    @Override
3238    public int hashCode() {
3239        return 31 * (31 + Double.hashCode(real)) + Double.hashCode(imaginary);
3240    }
3241
3242    /**
3243     * Returns a string representation of the complex number.
3244     *
3245     * <p>The string will represent the numeric values of the real and imaginary parts.
3246     * The values are split by a separator and surrounded by parentheses.
3247     * The string can be {@link #parse(String) parsed} to obtain an instance with the same value.
3248     *
3249     * <p>The format for complex number \( x + i y \) is {@code "(x,y)"}, with \( x \) and
3250     * \( y \) converted as if using {@link Double#toString(double)}.
3251     *
3252     * @return A string representation of the complex number.
3253     * @see #parse(String)
3254     * @see Double#toString(double)
3255     */
3256    @Override
3257    public String toString() {
3258        return new StringBuilder(TO_STRING_SIZE)
3259            .append(FORMAT_START)
3260            .append(real).append(FORMAT_SEP)
3261            .append(imaginary)
3262            .append(FORMAT_END)
3263            .toString();
3264    }
3265
3266    /**
3267     * Returns {@code true} if the values are equal according to semantics of
3268     * {@link Double#equals(Object)}.
3269     *
3270     * @param x Value
3271     * @param y Value
3272     * @return {@code Double.valueof(x).equals(Double.valueOf(y))}.
3273     */
3274    private static boolean equals(double x, double y) {
3275        return Double.doubleToLongBits(x) == Double.doubleToLongBits(y);
3276    }
3277
3278    /**
3279     * Check that a value is negative. It must meet all the following conditions:
3280     * <ul>
3281     *  <li>it is not {@code NaN},</li>
3282     *  <li>it is negative signed,</li>
3283     * </ul>
3284     *
3285     * <p>Note: This is true for negative zero.</p>
3286     *
3287     * @param d Value.
3288     * @return {@code true} if {@code d} is negative.
3289     */
3290    private static boolean negative(double d) {
3291        return d < 0 || Double.doubleToLongBits(d) == NEGATIVE_ZERO_LONG_BITS;
3292    }
3293
3294    /**
3295     * Check that a value is positive infinity. Used to replace {@link Double#isInfinite()}
3296     * when the input value is known to be positive (i.e. in the case where it has been
3297     * set using {@link Math#abs(double)}).
3298     *
3299     * @param d Value.
3300     * @return {@code true} if {@code d} is +inf.
3301     */
3302    private static boolean isPosInfinite(double d) {
3303        return d == Double.POSITIVE_INFINITY;
3304    }
3305
3306    /**
3307     * Check that an absolute value is finite. Used to replace {@link Double#isFinite()}
3308     * when the input value is known to be positive (i.e. in the case where it has been
3309     * set using {@link Math#abs(double)}).
3310     *
3311     * @param d Value.
3312     * @return {@code true} if {@code d} is +finite.
3313     */
3314    private static boolean isPosFinite(double d) {
3315        return d <= Double.MAX_VALUE;
3316    }
3317
3318    /**
3319     * Create a complex number given the real and imaginary parts, then multiply by {@code -i}.
3320     * This is used in functions that implement trigonomic identities. It is the functional
3321     * equivalent of:
3322     *
3323     * <pre>
3324     *  z = new Complex(real, imaginary).multiplyImaginary(-1);</pre>
3325     *
3326     * @param real Real part.
3327     * @param imaginary Imaginary part.
3328     * @return {@code Complex} object.
3329     */
3330    private static Complex multiplyNegativeI(double real, double imaginary) {
3331        return new Complex(imaginary, -real);
3332    }
3333
3334    /**
3335     * Change the sign of the magnitude based on the signed value.
3336     *
3337     * <p>If the signed value is negative then the result is {@code -magnitude}; otherwise
3338     * return {@code magnitude}.
3339     *
3340     * <p>A signed value of {@code -0.0} is treated as negative. A signed value of {@code NaN}
3341     * is treated as positive.
3342     *
3343     * <p>This is not the same as {@link Math#copySign(double, double)} as this method
3344     * will change the sign based on the signed value rather than copy the sign.
3345     *
3346     * @param magnitude the magnitude
3347     * @param signedValue the signed value
3348     * @return magnitude or -magnitude.
3349     * @see #negative(double)
3350     */
3351    private static double changeSign(double magnitude, double signedValue) {
3352        return negative(signedValue) ? -magnitude : magnitude;
3353    }
3354
3355    /**
3356     * Returns a scale suitable for use with {@link Math#scalb(double, int)} to normalise
3357     * the number to the interval {@code [1, 2)}.
3358     *
3359     * <p>The scale is typically the largest unbiased exponent used in the representation of the
3360     * two numbers. In contrast to {@link Math#getExponent(double)} this handles
3361     * sub-normal numbers by computing the number of leading zeros in the mantissa
3362     * and shifting the unbiased exponent. The result is that for all finite, non-zero,
3363     * numbers {@code a, b}, the magnitude of {@code scalb(x, -getScale(a, b))} is
3364     * always in the range {@code [1, 2)}, where {@code x = max(|a|, |b|)}.
3365     *
3366     * <p>This method is a functional equivalent of the c function ilogb(double) adapted for
3367     * two input arguments.
3368     *
3369     * <p>The result is to be used to scale a complex number using {@link Math#scalb(double, int)}.
3370     * Hence the special case of both zero arguments is handled using the return value for NaN
3371     * as zero cannot be scaled. This is different from {@link Math#getExponent(double)}
3372     * or {@link #getMaxExponent(double, double)}.
3373     *
3374     * <p>Special cases:
3375     *
3376     * <ul>
3377     * <li>If either argument is NaN or infinite, then the result is
3378     * {@link Double#MAX_EXPONENT} + 1.
3379     * <li>If both arguments are zero, then the result is
3380     * {@link Double#MAX_EXPONENT} + 1.
3381     * </ul>
3382     *
3383     * @param a the first value
3384     * @param b the second value
3385     * @return The maximum unbiased exponent of the values to be used for scaling
3386     * @see Math#getExponent(double)
3387     * @see Math#scalb(double, int)
3388     * @see <a href="http://www.cplusplus.com/reference/cmath/ilogb/">ilogb</a>
3389     */
3390    private static int getScale(double a, double b) {
3391        // Only interested in the exponent and mantissa so remove the sign bit
3392        final long x = Double.doubleToRawLongBits(a) & UNSIGN_MASK;
3393        final long y = Double.doubleToRawLongBits(b) & UNSIGN_MASK;
3394        // Only interested in the maximum
3395        final long bits = Math.max(x, y);
3396        // Get the unbiased exponent
3397        int exp = ((int) (bits >>> 52)) - EXPONENT_OFFSET;
3398
3399        // No case to distinguish nan/inf
3400        // Handle sub-normal numbers
3401        if (exp == Double.MIN_EXPONENT - 1) {
3402            // Special case for zero, return as nan/inf to indicate scaling is not possible
3403            if (bits == 0) {
3404                return Double.MAX_EXPONENT + 1;
3405            }
3406            // A sub-normal number has an exponent below -1022. The amount below
3407            // is defined by the number of shifts of the most significant bit in
3408            // the mantissa that is required to get a 1 at position 53 (i.e. as
3409            // if it were a normal number with assumed leading bit)
3410            final long mantissa = bits & MANTISSA_MASK;
3411            exp -= Long.numberOfLeadingZeros(mantissa << 12);
3412        }
3413        return exp;
3414    }
3415
3416    /**
3417     * Returns the largest unbiased exponent used in the representation of the
3418     * two numbers. Special cases:
3419     *
3420     * <ul>
3421     * <li>If either argument is NaN or infinite, then the result is
3422     * {@link Double#MAX_EXPONENT} + 1.
3423     * <li>If both arguments are zero or subnormal, then the result is
3424     * {@link Double#MIN_EXPONENT} -1.
3425     * </ul>
3426     *
3427     * <p>This is used by {@link #divide(double, double, double, double)} as
3428     * a simple detection that a number may overflow if multiplied
3429     * by a value in the interval [1, 2).
3430     *
3431     * @param a the first value
3432     * @param b the second value
3433     * @return The maximum unbiased exponent of the values.
3434     * @see Math#getExponent(double)
3435     * @see #divide(double, double, double, double)
3436     */
3437    private static int getMaxExponent(double a, double b) {
3438        // This could return:
3439        // Math.getExponent(Math.max(Math.abs(a), Math.abs(b)))
3440        // A speed test is required to determine performance.
3441        return Math.max(Math.getExponent(a), Math.getExponent(b));
3442    }
3443
3444    /**
3445     * Checks if both x and y are in the region defined by the minimum and maximum.
3446     *
3447     * @param x x value.
3448     * @param y y value.
3449     * @param min the minimum (exclusive).
3450     * @param max the maximum (exclusive).
3451     * @return true if inside the region.
3452     */
3453    private static boolean inRegion(double x, double y, double min, double max) {
3454        return (x < max) && (x > min) && (y < max) && (y > min);
3455    }
3456
3457    /**
3458     * Returns {@code sqrt(x^2 + y^2)} without intermediate overflow or underflow.
3459     *
3460     * <p>Special cases:
3461     * <ul>
3462     * <li>If either argument is infinite, then the result is positive infinity.
3463     * <li>If either argument is NaN and neither argument is infinite, then the result is NaN.
3464     * </ul>
3465     *
3466     * <p>The computed result is expected to be within 1 ulp of the exact result.
3467     *
3468     * <p>This method is a replacement for {@link Math#hypot(double, double)}. There
3469     * will be differences between this method and {@code Math.hypot(double, double)} due
3470     * to the use of a different algorithm to compute the high precision sum of
3471     * {@code x^2 + y^2}. This method has been tested to have a lower maximum error from
3472     * the exact result; any differences are expected to be 1 ULP indicating a rounding
3473     * change in the sum.
3474     *
3475     * <p>JDK9 ported the hypot function to Java for bug JDK-7130085 due to the slow performance
3476     * of the method as a native function. Benchmarks of the Complex class for functions that
3477     * use hypot confirm this is slow pre-Java 9. This implementation outperforms the new faster
3478     * {@code Math.hypot(double, double)} on JDK 11 (LTS). See the Commons numbers examples JMH
3479     * module for benchmarks. Comparisons with alternative implementations indicate
3480     * performance gains are related to edge case handling and elimination of an unpredictable
3481     * branch in the computation of {@code x^2 + y^2}.
3482     *
3483     * <p>This port was adapted from the "Freely Distributable Math Library" hypot function.
3484     * This method only (and not invoked methods within) is distributed under the terms of the
3485     * original notice as shown below:
3486     * <pre>
3487     * ====================================================
3488     * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
3489     *
3490     * Developed at SunSoft, a Sun Microsystems, Inc. business.
3491     * Permission to use, copy, modify, and distribute this
3492     * software is freely granted, provided that this notice
3493     * is preserved.
3494     * ====================================================
3495     * </pre>
3496     *
3497     * <p>Note: The fdlibm c code makes use of the language ability to read and write directly
3498     * to the upper and lower 32-bits of the 64-double. The function performs
3499     * checking on the upper 32-bits for the magnitude of the two numbers by accessing
3500     * the exponent and 20 most significant bits of the mantissa. These upper bits
3501     * are manipulated during scaling and then used to perform extended precision
3502     * computation of the sum {@code x^2 + y^2} where the high part of the number has 20-bit
3503     * precision. Manipulation of direct bits has no equivalent in Java
3504     * other than use of {@link Double#doubleToLongBits(double)} and
3505     * {@link Double#longBitsToDouble(long)}. To avoid conversion to and from long and double
3506     * representations this implementation only scales the double representation. The high
3507     * and low parts of a double for the extended precision computation are extracted
3508     * using the method of Dekker (1971) to create two 26-bit numbers. This works for sub-normal
3509     * numbers and reduces the maximum error in comparison to fdlibm hypot which does not
3510     * use a split number algorithm for sub-normal numbers.
3511     *
3512     * @param x Value x
3513     * @param y Value y
3514     * @return sqrt(x^2 + y^2)
3515     * @see Math#hypot(double, double)
3516     * @see <a href="https://www.netlib.org/fdlibm/e_hypot.c">fdlibm e_hypot.c</a>
3517     * @see <a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=7130085">JDK-7130085 : Port fdlibm hypot to Java</a>
3518     */
3519    private static double hypot(double x, double y) {
3520        // Differences to the fdlibm reference:
3521        //
3522        // 1. fdlibm orders the two parts using the magnitude of the upper 32-bits.
3523        // This incorrectly orders numbers which differ only in the lower 32-bits.
3524        // This invalidates hypot(x, y) = hypot(y, x) for small sub-normal numbers and a minority
3525        // of cases of normal numbers. This implementation forces the |x| >= |y| order
3526        // using the entire 63-bits of the unsigned doubles to ensure the function
3527        // is commutative.
3528        //
3529        // 2. fdlibm computed scaling by directly writing changes to the exponent bits
3530        // and maintained the high part (ha) during scaling for use in the high
3531        // precision sum x^2 + y^2. Since exponent scaling cannot be applied to sub-normals
3532        // the original version dropped the split number representation for sub-normals
3533        // and can produce maximum errors above 1 ULP for sub-normal numbers.
3534        // This version uses Dekker's method to split the number. This can be applied to
3535        // sub-normals and allows dropping the condition to check for sub-normal numbers
3536        // since all small numbers are handled with a single scaling factor.
3537        // The effect is increased precision for the majority of sub-normal cases where
3538        // the implementations compute a different result.
3539        //
3540        // 3. An alteration is done here to add an 'else if' instead of a second
3541        // 'if' statement. Thus you cannot scale down and up at the same time.
3542        //
3543        // 4. There is no use of the absolute double value. The magnitude comparison is
3544        // performed using the long bit representation. The computation x^2+y^2 is
3545        // insensitive to the sign bit. Thus use of Math.abs(double) is only in edge-case
3546        // branches.
3547        //
3548        // 5. The exponent different to ignore the smaller component has changed from 60 to 54.
3549        //
3550        // Original comments from fdlibm are in c style: /* */
3551        // Extra comments added for reference.
3552        //
3553        // Note that the high 32-bits are compared to constants.
3554        // The lowest 20-bits are the upper bits of the 52-bit mantissa.
3555        // The next 11-bits are the biased exponent. The sign bit has been cleared.
3556        // Scaling factors are powers of two for exact scaling.
3557        // For clarity the values have been refactored to named constants.
3558
3559        // The mask is used to remove the sign bit.
3560        final long xbits = Double.doubleToRawLongBits(x) & UNSIGN_MASK;
3561        final long ybits = Double.doubleToRawLongBits(y) & UNSIGN_MASK;
3562
3563        // Order by magnitude: |a| >= |b|
3564        double a;
3565        double b;
3566        /* High word of x & y */
3567        int ha;
3568        int hb;
3569        if (ybits > xbits) {
3570            a = y;
3571            b = x;
3572            ha = (int) (ybits >>> 32);
3573            hb = (int) (xbits >>> 32);
3574        } else {
3575            a = x;
3576            b = y;
3577            ha = (int) (xbits >>> 32);
3578            hb = (int) (ybits >>> 32);
3579        }
3580
3581        // Check if the smaller part is significant.
3582        // a^2 is computed in extended precision for an effective mantissa of 106-bits.
3583        // An exponent difference of 54 is where b^2 will not overlap a^2.
3584        if ((ha - hb) > EXP_54) {
3585            /* a/b > 2**54 */
3586            // or a is Inf or NaN.
3587            // No addition of a + b for sNaN.
3588            return Math.abs(a);
3589        }
3590
3591        double rescale = 1.0;
3592        if (ha > EXP_500) {
3593            /* a > 2^500 */
3594            if (ha >= EXP_1024) {
3595                /* Inf or NaN */
3596                // Check b is infinite for the IEEE754 result.
3597                // No addition of a + b for sNaN.
3598                return Math.abs(b) == Double.POSITIVE_INFINITY ?
3599                    Double.POSITIVE_INFINITY :
3600                    Math.abs(a);
3601            }
3602            /* scale a and b by 2^-600 */
3603            // Before scaling: a in [2^500, 2^1023].
3604            // After scaling: a in [2^-100, 2^423].
3605            // After scaling: b in [2^-154, 2^423].
3606            a *= TWO_POW_NEG_600;
3607            b *= TWO_POW_NEG_600;
3608            rescale = TWO_POW_600;
3609        } else if (hb < EXP_NEG_500) {
3610            // No special handling of sub-normals.
3611            // These do not matter when we do not manipulate the exponent bits
3612            // for scaling the split representation.
3613
3614            // Intentional comparison with zero.
3615            if (b == 0) {
3616                return Math.abs(a);
3617            }
3618
3619            /* scale a and b by 2^600 */
3620            // Effective min exponent of a sub-normal = -1022 - 52 = -1074.
3621            // Before scaling: b in [2^-1074, 2^-501].
3622            // After scaling: b in [2^-474, 2^99].
3623            // After scaling: a in [2^-474, 2^153].
3624            a *= TWO_POW_600;
3625            b *= TWO_POW_600;
3626            rescale = TWO_POW_NEG_600;
3627        }
3628
3629        // High precision x^2 + y^2
3630        return Math.sqrt(x2y2(a, b)) * rescale;
3631    }
3632
3633    /**
3634     * Return {@code x^2 + y^2} with high accuracy.
3635     *
3636     * <p>It is assumed that {@code 2^500 > |x| >= |y| > 2^-500}. Thus there will be no
3637     * overflow or underflow of the result. The inputs are not assumed to be unsigned.
3638     *
3639     * <p>The computation is performed using Dekker's method for extended precision
3640     * multiplication of x and y and then summation of the extended precision squares.
3641     *
3642     * @param x Value x.
3643     * @param y Value y
3644     * @return x^2 + y^2
3645     * @see <a href="https://doi.org/10.1007/BF01397083">
3646     * Dekker (1971) A floating-point technique for extending the available precision</a>
3647     */
3648    private static double x2y2(double x, double y) {
3649        // Note:
3650        // This method is different from the high-accuracy summation used in fdlibm for hypot.
3651        // The summation could be any valid computation of x^2+y^2. However since this follows
3652        // the re-scaling logic in hypot(x, y) the use of high precision has relatively
3653        // less performance overhead than if used without scaling.
3654        // The Dekker algorithm is branchless for better performance
3655        // than the fdlibm method with a maximum ULP error of approximately 0.86.
3656        //
3657        // See NUMBERS-143 for analysis.
3658
3659        // Do a Dekker summation of double length products x*x and y*y
3660        // (10 multiply and 20 additions).
3661        final double xx = x * x;
3662        final double yy = y * y;
3663        // Compute the round-off from the products.
3664        // With FMA hardware support in JDK 9+ this can be replaced with the much faster:
3665        // xxLow = Math.fma(x, x, -xx)
3666        // yyLow = Math.fma(y, y, -yy)
3667        // Dekker mul12
3668        final double xHigh = splitHigh(x);
3669        final double xLow = x - xHigh;
3670        final double xxLow = squareLow(xLow, xHigh, xx);
3671        // Dekker mul12
3672        final double yHigh = splitHigh(y);
3673        final double yLow = y - yHigh;
3674        final double yyLow = squareLow(yLow, yHigh, yy);
3675        // Dekker add2
3676        final double r = xx + yy;
3677        // Note: The order is important. Assume xx > yy and drop Dekker's conditional
3678        // check for which is the greater magnitude.
3679        // s = xx - r + yy + yyLow + xxLow
3680        // z = r + s
3681        // zz = r - z + s
3682        // Here we compute z inline and ignore computing the round-off zz.
3683        // Note: The round-off could be used with Dekker's sqrt2 method.
3684        // That adds 7 multiply, 1 division and 19 additions doubling the cost
3685        // and reducing error to < 0.5 ulp for the final sqrt.
3686        return xx - r + yy + yyLow + xxLow + r;
3687    }
3688}