Complex.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.numbers.complex;

  18. import java.io.Serializable;
  19. import java.util.ArrayList;
  20. import java.util.List;
  21. import java.util.function.DoubleUnaryOperator;

  22. /**
  23.  * Cartesian representation of a complex number. The complex number is expressed
  24.  * in the form \( a + ib \) where \( a \) and \( b \) are real numbers and \( i \)
  25.  * is the imaginary unit which satisfies the equation \( i^2 = -1 \). For the
  26.  * complex number \( a + ib \), \( a \) is called the <em>real part</em> and
  27.  * \( b \) is called the <em>imaginary part</em>.
  28.  *
  29.  * <p>This class is immutable. All arithmetic will create a new instance for the
  30.  * result.</p>
  31.  *
  32.  * <p>Arithmetic in this class conforms to the C99 standard for complex numbers
  33.  * defined in ISO/IEC 9899, Annex G. Methods have been named using the equivalent
  34.  * method in ISO C99. The behavior for special cases is listed as defined in C99.</p>
  35.  *
  36.  * <p>For functions \( f \) which obey the conjugate equality \( conj(f(z)) = f(conj(z)) \),
  37.  * the specifications for the upper half-plane imply the specifications for the lower
  38.  * half-plane.</p>
  39.  *
  40.  * <p>For functions that are either odd, \( f(z) = -f(-z) \), or even, \( f(z) =  f(-z) \),
  41.  * the specifications for the first quadrant imply the specifications for the other three
  42.  * quadrants.</p>
  43.  *
  44.  * <p>Special cases of <a href="http://mathworld.wolfram.com/BranchCut.html">branch cuts</a>
  45.  * for multivalued functions adopt the principle value convention from C99. Specials cases
  46.  * from C99 that raise the "invalid" or "divide-by-zero"
  47.  * <a href="https://en.cppreference.com/w/c/numeric/fenv/FE_exceptions">floating-point
  48.  * exceptions</a> return the documented value without an explicit mechanism to notify
  49.  * of the exception case, that is no exceptions are thrown during computations in-line with
  50.  * the convention of the corresponding single-valued functions in
  51.  * {@link Math Math}.
  52.  * These cases are documented in the method special cases as "invalid" or "divide-by-zero"
  53.  * floating-point operation.
  54.  * Note: Invalid floating-point exception cases will result in a complex number where the
  55.  * cardinality of NaN component parts has increased as a real or imaginary part could
  56.  * not be computed and is set to NaN.
  57.  *
  58.  * @see <a href="http://www.open-std.org/JTC1/SC22/WG14/www/standards">
  59.  *    ISO/IEC 9899 - Programming languages - C</a>
  60.  */
  61. public final class Complex implements Serializable  {
  62.     /**
  63.      * A complex number representing \( i \), the square root of \( -1 \).
  64.      *
  65.      * <p>\( (0 + i 1) \).
  66.      */
  67.     public static final Complex I = new Complex(0, 1);
  68.     /**
  69.      * A complex number representing one.
  70.      *
  71.      * <p>\( (1 + i 0) \).
  72.      */
  73.     public static final Complex ONE = new Complex(1, 0);
  74.     /**
  75.      * A complex number representing zero.
  76.      *
  77.      * <p>\( (0 + i 0) \).
  78.      */
  79.     public static final Complex ZERO = new Complex(0, 0);

  80.     /** A complex number representing {@code NaN + i NaN}. */
  81.     private static final Complex NAN = new Complex(Double.NaN, Double.NaN);
  82.     /** &pi;/2. */
  83.     private static final double PI_OVER_2 = 0.5 * Math.PI;
  84.     /** &pi;/4. */
  85.     private static final double PI_OVER_4 = 0.25 * Math.PI;
  86.     /** Natural logarithm of 2 (ln(2)). */
  87.     private static final double LN_2 = Math.log(2);
  88.     /** Base 10 logarithm of 10 divided by 2 (log10(e)/2). */
  89.     private static final double LOG_10E_O_2 = Math.log10(Math.E) / 2;
  90.     /** Base 10 logarithm of 2 (log10(2)). */
  91.     private static final double LOG10_2 = Math.log10(2);
  92.     /** {@code 1/2}. */
  93.     private static final double HALF = 0.5;
  94.     /** {@code sqrt(2)}. */
  95.     private static final double ROOT2 = 1.4142135623730951;
  96.     /** {@code 1.0 / sqrt(2)}.
  97.      * This is pre-computed to the closest double from the exact result.
  98.      * It is 1 ULP different from 1.0 / Math.sqrt(2) but equal to Math.sqrt(2) / 2.
  99.      */
  100.     private static final double ONE_OVER_ROOT2 = 0.7071067811865476;
  101.     /** The bit representation of {@code -0.0}. */
  102.     private static final long NEGATIVE_ZERO_LONG_BITS = Double.doubleToLongBits(-0.0);
  103.     /** Exponent offset in IEEE754 representation. */
  104.     private static final int EXPONENT_OFFSET = 1023;
  105.     /**
  106.      * Largest double-precision floating-point number such that
  107.      * {@code 1 + EPSILON} is numerically equal to 1. This value is an upper
  108.      * bound on the relative error due to rounding real numbers to double
  109.      * precision floating-point numbers.
  110.      *
  111.      * <p>In IEEE 754 arithmetic, this is 2<sup>-53</sup>.
  112.      * Copied from o.a.c.numbers.Precision.
  113.      *
  114.      * @see <a href="http://en.wikipedia.org/wiki/Machine_epsilon">Machine epsilon</a>
  115.      */
  116.     private static final double EPSILON = Double.longBitsToDouble((EXPONENT_OFFSET - 53L) << 52);
  117.     /** Mask to remove the sign bit from a long. */
  118.     private static final long UNSIGN_MASK = 0x7fff_ffff_ffff_ffffL;
  119.     /** Mask to extract the 52-bit mantissa from a long representation of a double. */
  120.     private static final long MANTISSA_MASK = 0x000f_ffff_ffff_ffffL;
  121.     /** The multiplier used to split the double value into hi and low parts. This must be odd
  122.      * and a value of 2^s + 1 in the range {@code p/2 <= s <= p-1} where p is the number of
  123.      * bits of precision of the floating point number. Here {@code s = 27}.*/
  124.     private static final double MULTIPLIER = 1.34217729E8;

  125.     /**
  126.      * Crossover point to switch computation for asin/acos factor A.
  127.      * This has been updated from the 1.5 value used by Hull et al to 10
  128.      * as used in boost::math::complex.
  129.      * @see <a href="https://svn.boost.org/trac/boost/ticket/7290">Boost ticket 7290</a>
  130.      */
  131.     private static final double A_CROSSOVER = 10.0;
  132.     /** Crossover point to switch computation for asin/acos factor B. */
  133.     private static final double B_CROSSOVER = 0.6471;
  134.     /**
  135.      * The safe maximum double value {@code x} to avoid loss of precision in asin/acos.
  136.      * Equal to sqrt(M) / 8 in Hull, et al (1997) with M the largest normalised floating-point value.
  137.      */
  138.     private static final double SAFE_MAX = Math.sqrt(Double.MAX_VALUE) / 8;
  139.     /**
  140.      * The safe minimum double value {@code x} to avoid loss of precision/underflow in asin/acos.
  141.      * Equal to sqrt(u) * 4 in Hull, et al (1997) with u the smallest normalised floating-point value.
  142.      */
  143.     private static final double SAFE_MIN = Math.sqrt(Double.MIN_NORMAL) * 4;
  144.     /**
  145.      * The safe maximum double value {@code x} to avoid loss of precision in atanh.
  146.      * Equal to sqrt(M) / 2 with M the largest normalised floating-point value.
  147.      */
  148.     private static final double SAFE_UPPER = Math.sqrt(Double.MAX_VALUE) / 2;
  149.     /**
  150.      * The safe minimum double value {@code x} to avoid loss of precision/underflow in atanh.
  151.      * Equal to sqrt(u) * 2 with u the smallest normalised floating-point value.
  152.      */
  153.     private static final double SAFE_LOWER = Math.sqrt(Double.MIN_NORMAL) * 2;
  154.     /** The safe maximum double value {@code x} to avoid overflow in sqrt. */
  155.     private static final double SQRT_SAFE_UPPER = Double.MAX_VALUE / 8;
  156.     /**
  157.      * A safe maximum double value {@code m} where {@code e^m} is not infinite.
  158.      * This can be used when functions require approximations of sinh(x) or cosh(x)
  159.      * when x is large using exp(x):
  160.      * <pre>
  161.      * sinh(x) = (e^x - e^-x) / 2 = sign(x) * e^|x| / 2
  162.      * cosh(x) = (e^x + e^-x) / 2 = e^|x| / 2 </pre>
  163.      *
  164.      * <p>This value can be used to approximate e^x using a product:
  165.      *
  166.      * <pre>
  167.      * e^x = product_n (e^m) * e^(x-nm)
  168.      * n = (int) x/m
  169.      * e.g. e^2000 = e^m * e^m * e^(2000 - 2m) </pre>
  170.      *
  171.      * <p>The value should be below ln(max_value) ~ 709.783.
  172.      * The value m is set to an integer for less error when subtracting m and chosen as
  173.      * even (m=708) as it is used as a threshold in tanh with m/2.
  174.      *
  175.      * <p>The value is used to compute e^x multiplied by a small number avoiding
  176.      * overflow (sinh/cosh) or a small number divided by e^x without underflow due to
  177.      * infinite e^x (tanh). The following conditions are used:
  178.      * <pre>
  179.      * 0.5 * e^m * Double.MIN_VALUE * e^m * e^m = Infinity
  180.      * 2.0 / e^m / e^m = 0.0 </pre>
  181.      */
  182.     private static final double SAFE_EXP = 708;
  183.     /**
  184.      * The value of Math.exp(SAFE_EXP): e^708.
  185.      * To be used in overflow/underflow safe products of e^m to approximate e^x where {@code x > m}.
  186.      */
  187.     private static final double EXP_M = Math.exp(SAFE_EXP);

  188.     /** 54 shifted 20-bits to align with the exponent of the upper 32-bits of a double. */
  189.     private static final int EXP_54 = 0x36_00000;
  190.     /** Represents an exponent of 500 in unbiased form shifted 20-bits to align with the upper 32-bits of a double. */
  191.     private static final int EXP_500 = 0x5f3_00000;
  192.     /** Represents an exponent of 1024 in unbiased form (infinite or nan)
  193.      * shifted 20-bits to align with the upper 32-bits of a double. */
  194.     private static final int EXP_1024 = 0x7ff_00000;
  195.     /** Represents an exponent of -500 in unbiased form shifted 20-bits to align with the upper 32-bits of a double. */
  196.     private static final int EXP_NEG_500 = 0x20b_00000;
  197.     /** 2^600. */
  198.     private static final double TWO_POW_600 = 0x1.0p+600;
  199.     /** 2^-600. */
  200.     private static final double TWO_POW_NEG_600 = 0x1.0p-600;

  201.     /** Serializable version identifier. */
  202.     private static final long serialVersionUID = 20180201L;

  203.     /**
  204.      * The size of the buffer for {@link #toString()}.
  205.      *
  206.      * <p>The longest double will require a sign, a maximum of 17 digits, the decimal place
  207.      * and the exponent, e.g. for max value this is 24 chars: -1.7976931348623157e+308.
  208.      * Set the buffer size to twice this and round up to a power of 2 thus
  209.      * allowing for formatting characters. The size is 64.
  210.      */
  211.     private static final int TO_STRING_SIZE = 64;
  212.     /** The minimum number of characters in the format. This is 5, e.g. {@code "(0,0)"}. */
  213.     private static final int FORMAT_MIN_LEN = 5;
  214.     /** {@link #toString() String representation}. */
  215.     private static final char FORMAT_START = '(';
  216.     /** {@link #toString() String representation}. */
  217.     private static final char FORMAT_END = ')';
  218.     /** {@link #toString() String representation}. */
  219.     private static final char FORMAT_SEP = ',';
  220.     /** The minimum number of characters before the separator. This is 2, e.g. {@code "(0"}. */
  221.     private static final int BEFORE_SEP = 2;

  222.     /** The imaginary part. */
  223.     private final double imaginary;
  224.     /** The real part. */
  225.     private final double real;

  226.     /**
  227.      * Define a constructor for a Complex.
  228.      * This is used in functions that implement trigonomic identities.
  229.      */
  230.     @FunctionalInterface
  231.     private interface ComplexConstructor {
  232.         /**
  233.          * Create a complex number given the real and imaginary parts.
  234.          *
  235.          * @param real Real part.
  236.          * @param imaginary Imaginary part.
  237.          * @return {@code Complex} object.
  238.          */
  239.         Complex create(double real, double imaginary);
  240.     }

  241.     /**
  242.      * Private default constructor.
  243.      *
  244.      * @param real Real part.
  245.      * @param imaginary Imaginary part.
  246.      */
  247.     private Complex(double real, double imaginary) {
  248.         this.real = real;
  249.         this.imaginary = imaginary;
  250.     }

  251.     /**
  252.      * Create a complex number given the real and imaginary parts.
  253.      *
  254.      * @param real Real part.
  255.      * @param imaginary Imaginary part.
  256.      * @return {@code Complex} number.
  257.      */
  258.     public static Complex ofCartesian(double real, double imaginary) {
  259.         return new Complex(real, imaginary);
  260.     }

  261.     /**
  262.      * Creates a complex number from its polar representation using modulus {@code rho} (\( \rho \))
  263.      * and phase angle {@code theta} (\( \theta \)).
  264.      *
  265.      * \[ \begin{aligned}
  266.      *    x &amp;= \rho \cos(\theta) \\
  267.      *    y &amp;= \rho \sin(\theta) \end{aligned} \]
  268.      *
  269.      * <p>Requires that {@code rho} is non-negative and non-NaN and {@code theta} is finite;
  270.      * otherwise returns a complex with NaN real and imaginary parts. A {@code rho} value of
  271.      * {@code -0.0} is considered negative and an invalid modulus.
  272.      *
  273.      * <p>A non-NaN complex number constructed using this method will satisfy the following
  274.      * to within floating-point error when {@code theta} is in the range
  275.      * \( -\pi\ \lt \theta \leq \pi \):
  276.      *
  277.      * <pre>
  278.      *  Complex.ofPolar(rho, theta).abs() == rho
  279.      *  Complex.ofPolar(rho, theta).arg() == theta</pre>
  280.      *
  281.      * <p>If {@code rho} is infinite then the resulting parts may be infinite or NaN
  282.      * following the rules for double arithmetic, for example:</p>
  283.      *
  284.      * <ul>
  285.      * <li>{@code ofPolar(}\( -0.0 \){@code , }\( 0 \){@code ) = }\( \text{NaN} + i \text{NaN} \)
  286.      * <li>{@code ofPolar(}\( 0.0 \){@code , }\( 0 \){@code ) = }\( 0 + i 0 \)
  287.      * <li>{@code ofPolar(}\( 1 \){@code , }\( 0 \){@code ) = }\( 1 + i 0 \)
  288.      * <li>{@code ofPolar(}\( 1 \){@code , }\( \pi \){@code ) = }\( -1 + i \sin(\pi) \)
  289.      * <li>{@code ofPolar(}\( \infty \){@code , }\( \pi \){@code ) = }\( -\infty + i \infty \)
  290.      * <li>{@code ofPolar(}\( \infty \){@code , }\( 0 \){@code ) = }\( -\infty + i \text{NaN} \)
  291.      * <li>{@code ofPolar(}\( \infty \){@code , }\( -\frac{\pi}{4} \){@code ) = }\( \infty - i \infty \)
  292.      * <li>{@code ofPolar(}\( \infty \){@code , }\( 5\frac{\pi}{4} \){@code ) = }\( -\infty - i \infty \)
  293.      * </ul>
  294.      *
  295.      * <p>This method is the functional equivalent of the C++ method {@code std::polar}.
  296.      *
  297.      * @param rho The modulus of the complex number.
  298.      * @param theta The argument of the complex number.
  299.      * @return {@code Complex} number.
  300.      * @see <a href="http://mathworld.wolfram.com/PolarCoordinates.html">Polar Coordinates</a>
  301.      */
  302.     public static Complex ofPolar(double rho, double theta) {
  303.         // Require finite theta and non-negative, non-nan rho
  304.         if (!Double.isFinite(theta) || negative(rho) || Double.isNaN(rho)) {
  305.             return NAN;
  306.         }
  307.         final double x = rho * Math.cos(theta);
  308.         final double y = rho * Math.sin(theta);
  309.         return new Complex(x, y);
  310.     }

  311.     /**
  312.      * Create a complex cis number. This is also known as the complex exponential:
  313.      *
  314.      * \[ \text{cis}(x) = e^{ix} = \cos(x) + i \sin(x) \]
  315.      *
  316.      * @param x {@code double} to build the cis number.
  317.      * @return {@code Complex} cis number.
  318.      * @see <a href="http://mathworld.wolfram.com/Cis.html">Cis</a>
  319.      */
  320.     public static Complex ofCis(double x) {
  321.         return new Complex(Math.cos(x), Math.sin(x));
  322.     }

  323.     /**
  324.      * Returns a {@code Complex} instance representing the specified string {@code s}.
  325.      *
  326.      * <p>If {@code s} is {@code null}, then a {@code NullPointerException} is thrown.
  327.      *
  328.      * <p>The string must be in a format compatible with that produced by
  329.      * {@link #toString() Complex.toString()}.
  330.      * The format expects a start and end parentheses surrounding two numeric parts split
  331.      * by a separator. Leading and trailing spaces are allowed around each numeric part.
  332.      * Each numeric part is parsed using {@link Double#parseDouble(String)}. The parts
  333.      * are interpreted as the real and imaginary parts of the complex number.
  334.      *
  335.      * <p>Examples of valid strings and the equivalent {@code Complex} are shown below:
  336.      *
  337.      * <pre>
  338.      * "(0,0)"             = Complex.ofCartesian(0, 0)
  339.      * "(0.0,0.0)"         = Complex.ofCartesian(0, 0)
  340.      * "(-0.0, 0.0)"       = Complex.ofCartesian(-0.0, 0)
  341.      * "(-1.23, 4.56)"     = Complex.ofCartesian(-1.23, 4.56)
  342.      * "(1e300,-1.1e-2)"   = Complex.ofCartesian(1e300, -1.1e-2)</pre>
  343.      *
  344.      * @param s String representation.
  345.      * @return {@code Complex} number.
  346.      * @throws NullPointerException if the string is null.
  347.      * @throws NumberFormatException if the string does not contain a parsable complex number.
  348.      * @see Double#parseDouble(String)
  349.      * @see #toString()
  350.      */
  351.     public static Complex parse(String s) {
  352.         final int len = s.length();
  353.         if (len < FORMAT_MIN_LEN) {
  354.             throw new NumberFormatException(
  355.                 parsingExceptionMsg("Input too short, expected format",
  356.                                     FORMAT_START + "x" + FORMAT_SEP + "y" + FORMAT_END, s));
  357.         }

  358.         // Confirm start: '('
  359.         if (s.charAt(0) != FORMAT_START) {
  360.             throw new NumberFormatException(
  361.                 parsingExceptionMsg("Expected start delimiter", FORMAT_START, s));
  362.         }

  363.         // Confirm end: ')'
  364.         if (s.charAt(len - 1) != FORMAT_END) {
  365.             throw new NumberFormatException(
  366.                 parsingExceptionMsg("Expected end delimiter", FORMAT_END, s));
  367.         }

  368.         // Confirm separator ',' is between at least 2 characters from
  369.         // either end: "(x,x)"
  370.         // Count back from the end ignoring the last 2 characters.
  371.         final int sep = s.lastIndexOf(FORMAT_SEP, len - 3);
  372.         if (sep < BEFORE_SEP) {
  373.             throw new NumberFormatException(
  374.                 parsingExceptionMsg("Expected separator between two numbers", FORMAT_SEP, s));
  375.         }

  376.         // Should be no more separators
  377.         if (s.indexOf(FORMAT_SEP, sep + 1) != -1) {
  378.             throw new NumberFormatException(
  379.                 parsingExceptionMsg("Incorrect number of parts, expected only 2 using separator",
  380.                                     FORMAT_SEP, s));
  381.         }

  382.         // Try to parse the parts

  383.         final String rePart = s.substring(1, sep);
  384.         final double re;
  385.         try {
  386.             re = Double.parseDouble(rePart);
  387.         } catch (final NumberFormatException ex) {
  388.             throw new NumberFormatException(
  389.                 parsingExceptionMsg("Could not parse real part", rePart, s));
  390.         }

  391.         final String imPart = s.substring(sep + 1, len - 1);
  392.         final double im;
  393.         try {
  394.             im = Double.parseDouble(imPart);
  395.         } catch (final NumberFormatException ex) {
  396.             throw new NumberFormatException(
  397.                 parsingExceptionMsg("Could not parse imaginary part", imPart, s));
  398.         }

  399.         return ofCartesian(re, im);
  400.     }

  401.     /**
  402.      * Creates an exception message.
  403.      *
  404.      * @param message Message prefix.
  405.      * @param error Input that caused the error.
  406.      * @param s String representation.
  407.      * @return A message.
  408.      */
  409.     private static String parsingExceptionMsg(String message,
  410.                                               Object error,
  411.                                               String s) {
  412.         final StringBuilder sb = new StringBuilder(100)
  413.             .append(message)
  414.             .append(" '").append(error)
  415.             .append("' for input \"").append(s).append('"');
  416.         return sb.toString();
  417.     }

  418.     /**
  419.      * Gets the real part \( a \) of this complex number \( (a + i b) \).
  420.      *
  421.      * @return The real part.
  422.      */
  423.     public double getReal() {
  424.         return real;
  425.     }

  426.     /**
  427.      * Gets the real part \( a \) of this complex number \( (a + i b) \).
  428.      *
  429.      * <p>This method is the equivalent of the C++ method {@code std::complex::real}.
  430.      *
  431.      * @return The real part.
  432.      * @see #getReal()
  433.      */
  434.     public double real() {
  435.         return getReal();
  436.     }

  437.     /**
  438.      * Gets the imaginary part \( b \) of this complex number \( (a + i b) \).
  439.      *
  440.      * @return The imaginary part.
  441.      */
  442.     public double getImaginary() {
  443.         return imaginary;
  444.     }

  445.     /**
  446.      * Gets the imaginary part \( b \) of this complex number \( (a + i b) \).
  447.      *
  448.      * <p>This method is the equivalent of the C++ method {@code std::complex::imag}.
  449.      *
  450.      * @return The imaginary part.
  451.      * @see #getImaginary()
  452.      */
  453.     public double imag() {
  454.         return getImaginary();
  455.     }

  456.     /**
  457.      * Returns the absolute value of this complex number. This is also called complex norm, modulus,
  458.      * or magnitude.
  459.      *
  460.      * <p>\[ \text{abs}(x + i y) = \sqrt{(x^2 + y^2)} \]
  461.      *
  462.      * <p>Special cases:
  463.      *
  464.      * <ul>
  465.      * <li>{@code abs(x + iy) == abs(y + ix) == abs(x - iy)}.
  466.      * <li>If {@code z} is ±∞ + iy for any y, returns +∞.
  467.      * <li>If {@code z} is x + iNaN for non-infinite x, returns NaN.
  468.      * <li>If {@code z} is x + i0, returns |x|.
  469.      * </ul>
  470.      *
  471.      * <p>The cases ensure that if either component is infinite then the result is positive
  472.      * infinity. If either component is NaN and this is not {@link #isInfinite() infinite} then
  473.      * the result is NaN.
  474.      *
  475.      * <p>This method follows the
  476.      * <a href="http://www.iso-9899.info/wiki/The_Standard">ISO C Standard</a>, Annex G,
  477.      * in calculating the returned value without intermediate overflow or underflow.
  478.      *
  479.      * <p>The computed result will be within 1 ulp of the exact result.
  480.      *
  481.      * @return The absolute value.
  482.      * @see #isInfinite()
  483.      * @see #isNaN()
  484.      * @see <a href="http://mathworld.wolfram.com/ComplexModulus.html">Complex modulus</a>
  485.      */
  486.     public double abs() {
  487.         return abs(real, imaginary);
  488.     }

  489.     /**
  490.      * Returns the absolute value of the complex number.
  491.      * <pre>abs(x + i y) = sqrt(x^2 + y^2)</pre>
  492.      *
  493.      * <p>This should satisfy the special cases of the hypot function in ISO C99 F.9.4.3:
  494.      * "The hypot functions compute the square root of the sum of the squares of x and y,
  495.      * without undue overflow or underflow."
  496.      *
  497.      * <ul>
  498.      * <li>hypot(x, y), hypot(y, x), and hypot(x, −y) are equivalent.
  499.      * <li>hypot(x, ±0) is equivalent to |x|.
  500.      * <li>hypot(±∞, y) returns +∞, even if y is a NaN.
  501.      * </ul>
  502.      *
  503.      * <p>This method is called by all methods that require the absolute value of the complex
  504.      * number, e.g. abs(), sqrt() and log().
  505.      *
  506.      * @param real Real part.
  507.      * @param imaginary Imaginary part.
  508.      * @return The absolute value.
  509.      */
  510.     private static double abs(double real, double imaginary) {
  511.         // Specialised implementation of hypot.
  512.         // See NUMBERS-143
  513.         return hypot(real, imaginary);
  514.     }

  515.     /**
  516.      * Returns the argument of this complex number.
  517.      *
  518.      * <p>The argument is the angle phi between the positive real axis and
  519.      * the point representing this number in the complex plane.
  520.      * The value returned is between \( -\pi \) (not inclusive)
  521.      * and \( \pi \) (inclusive), with negative values returned for numbers with
  522.      * negative imaginary parts.
  523.      *
  524.      * <p>If either real or imaginary part (or both) is NaN, then the result is NaN.
  525.      * Infinite parts are handled as {@linkplain Math#atan2} handles them,
  526.      * essentially treating finite parts as zero in the presence of an
  527.      * infinite coordinate and returning a multiple of \( \frac{\pi}{4} \) depending on
  528.      * the signs of the infinite parts.
  529.      *
  530.      * <p>This code follows the
  531.      * <a href="http://www.iso-9899.info/wiki/The_Standard">ISO C Standard</a>, Annex G,
  532.      * in calculating the returned value using the {@code atan2(y, x)} method for complex
  533.      * \( x + iy \).
  534.      *
  535.      * @return The argument of this complex number.
  536.      * @see Math#atan2(double, double)
  537.      */
  538.     public double arg() {
  539.         // Delegate
  540.         return Math.atan2(imaginary, real);
  541.     }

  542.     /**
  543.      * Returns the squared norm value of this complex number. This is also called the absolute
  544.      * square.
  545.      *
  546.      * <p>\[ \text{norm}(x + i y) = x^2 + y^2 \]
  547.      *
  548.      * <p>If either component is infinite then the result is positive infinity. If either
  549.      * component is NaN and this is not {@link #isInfinite() infinite} then the result is NaN.
  550.      *
  551.      * <p>Note: This method may not return the same value as the square of {@link #abs()} as
  552.      * that method uses an extended precision computation.
  553.      *
  554.      * <p>{@code norm()} can be used as a faster alternative than {@code abs()} for ranking by
  555.      * magnitude. If used for ranking any overflow to infinity will create an equal ranking for
  556.      * values that may be still distinguished by {@code abs()}.
  557.      *
  558.      * @return The square norm value.
  559.      * @see #isInfinite()
  560.      * @see #isNaN()
  561.      * @see #abs()
  562.      * @see <a href="http://mathworld.wolfram.com/AbsoluteSquare.html">Absolute square</a>
  563.      */
  564.     public double norm() {
  565.         if (isInfinite()) {
  566.             return Double.POSITIVE_INFINITY;
  567.         }
  568.         return real * real + imaginary * imaginary;
  569.     }

  570.     /**
  571.      * Returns {@code true} if either the real <em>or</em> imaginary component of the complex number is NaN
  572.      * <em>and</em> the complex number is not infinite.
  573.      *
  574.      * <p>Note that:
  575.      * <ul>
  576.      *   <li>There is more than one complex number that can return {@code true}.
  577.      *   <li>Different representations of NaN can be distinguished by the
  578.      *       {@link #equals(Object) Complex.equals(Object)} method.
  579.      * </ul>
  580.      *
  581.      * @return {@code true} if this instance contains NaN and no infinite parts.
  582.      * @see Double#isNaN(double)
  583.      * @see #isInfinite()
  584.      * @see #equals(Object) Complex.equals(Object)
  585.      */
  586.     public boolean isNaN() {
  587.         if (Double.isNaN(real) || Double.isNaN(imaginary)) {
  588.             return !isInfinite();
  589.         }
  590.         return false;
  591.     }

  592.     /**
  593.      * Returns {@code true} if either real or imaginary component of the complex number is infinite.
  594.      *
  595.      * <p>Note: A complex number with at least one infinite part is regarded
  596.      * as an infinity (even if its other part is a NaN).
  597.      *
  598.      * @return {@code true} if this instance contains an infinite value.
  599.      * @see Double#isInfinite(double)
  600.      */
  601.     public boolean isInfinite() {
  602.         return Double.isInfinite(real) || Double.isInfinite(imaginary);
  603.     }

  604.     /**
  605.      * Returns {@code true} if both real and imaginary component of the complex number are finite.
  606.      *
  607.      * @return {@code true} if this instance contains finite values.
  608.      * @see Double#isFinite(double)
  609.      */
  610.     public boolean isFinite() {
  611.         return Double.isFinite(real) && Double.isFinite(imaginary);
  612.     }

  613.     /**
  614.      * Returns the
  615.      * <a href="http://mathworld.wolfram.com/ComplexConjugate.html">conjugate</a>
  616.      * \( \overline{z} \) of this complex number \( z \).
  617.      *
  618.      * <p>\[ \begin{aligned}
  619.      *                z  &amp;= a + i b \\
  620.      *      \overline{z} &amp;= a - i b \end{aligned}\]
  621.      *
  622.      * @return The conjugate (\( \overline{z} \)) of this complex number.
  623.      */
  624.     public Complex conj() {
  625.         return new Complex(real, -imaginary);
  626.     }

  627.     /**
  628.      * Returns a {@code Complex} whose value is the negation of both the real and imaginary parts
  629.      * of complex number \( z \).
  630.      *
  631.      * <p>\[ \begin{aligned}
  632.      *       z  &amp;=  a + i b \\
  633.      *      -z  &amp;= -a - i b \end{aligned} \]
  634.      *
  635.      * @return \( -z \).
  636.      */
  637.     public Complex negate() {
  638.         return new Complex(-real, -imaginary);
  639.     }

  640.     /**
  641.      * Returns the projection of this complex number onto the Riemann sphere.
  642.      *
  643.      * <p>\( z \) projects to \( z \), except that all complex infinities (even those
  644.      * with one infinite part and one NaN part) project to positive infinity on the real axis.
  645.      *
  646.      * If \( z \) has an infinite part, then {@code z.proj()} shall be equivalent to:
  647.      *
  648.      * <pre>return Complex.ofCartesian(Double.POSITIVE_INFINITY, Math.copySign(0.0, z.imag());</pre>
  649.      *
  650.      * @return \( z \) projected onto the Riemann sphere.
  651.      * @see #isInfinite()
  652.      * @see <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/cproj.html">
  653.      * IEEE and ISO C standards: cproj</a>
  654.      */
  655.     public Complex proj() {
  656.         if (isInfinite()) {
  657.             return new Complex(Double.POSITIVE_INFINITY, Math.copySign(0.0, imaginary));
  658.         }
  659.         return this;
  660.     }

  661.     /**
  662.      * Returns a {@code Complex} whose value is {@code (this + addend)}.
  663.      * Implements the formula:
  664.      *
  665.      * <p>\[ (a + i b) + (c + i d) = (a + c) + i (b + d) \]
  666.      *
  667.      * @param  addend Value to be added to this complex number.
  668.      * @return {@code this + addend}.
  669.      * @see <a href="http://mathworld.wolfram.com/ComplexAddition.html">Complex Addition</a>
  670.      */
  671.     public Complex add(Complex addend) {
  672.         return new Complex(real + addend.real,
  673.                            imaginary + addend.imaginary);
  674.     }

  675.     /**
  676.      * Returns a {@code Complex} whose value is {@code (this + addend)},
  677.      * with {@code addend} interpreted as a real number.
  678.      * Implements the formula:
  679.      *
  680.      * <p>\[ (a + i b) + c = (a + c) + i b \]
  681.      *
  682.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  683.      * real-only and complex numbers.</p>
  684.      *
  685.      * <p>Note: This method preserves the sign of the imaginary component \( b \) if it is {@code -0.0}.
  686.      * The sign would be lost if adding \( (c + i 0) \) using
  687.      * {@link #add(Complex) add(Complex.ofCartesian(addend, 0))} since
  688.      * {@code -0.0 + 0.0 = 0.0}.
  689.      *
  690.      * @param addend Value to be added to this complex number.
  691.      * @return {@code this + addend}.
  692.      * @see #add(Complex)
  693.      * @see #ofCartesian(double, double)
  694.      */
  695.     public Complex add(double addend) {
  696.         return new Complex(real + addend, imaginary);
  697.     }

  698.     /**
  699.      * Returns a {@code Complex} whose value is {@code (this + addend)},
  700.      * with {@code addend} interpreted as an imaginary number.
  701.      * Implements the formula:
  702.      *
  703.      * <p>\[ (a + i b) + i d = a + i (b + d) \]
  704.      *
  705.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  706.      * imaginary-only and complex numbers.</p>
  707.      *
  708.      * <p>Note: This method preserves the sign of the real component \( a \) if it is {@code -0.0}.
  709.      * The sign would be lost if adding \( (0 + i d) \) using
  710.      * {@link #add(Complex) add(Complex.ofCartesian(0, addend))} since
  711.      * {@code -0.0 + 0.0 = 0.0}.
  712.      *
  713.      * @param addend Value to be added to this complex number.
  714.      * @return {@code this + addend}.
  715.      * @see #add(Complex)
  716.      * @see #ofCartesian(double, double)
  717.      */
  718.     public Complex addImaginary(double addend) {
  719.         return new Complex(real, imaginary + addend);
  720.     }

  721.     /**
  722.      * Returns a {@code Complex} whose value is {@code (this - subtrahend)}.
  723.      * Implements the formula:
  724.      *
  725.      * <p>\[ (a + i b) - (c + i d) = (a - c) + i (b - d) \]
  726.      *
  727.      * @param  subtrahend Value to be subtracted from this complex number.
  728.      * @return {@code this - subtrahend}.
  729.      * @see <a href="http://mathworld.wolfram.com/ComplexSubtraction.html">Complex Subtraction</a>
  730.      */
  731.     public Complex subtract(Complex subtrahend) {
  732.         return new Complex(real - subtrahend.real,
  733.                            imaginary - subtrahend.imaginary);
  734.     }

  735.     /**
  736.      * Returns a {@code Complex} whose value is {@code (this - subtrahend)},
  737.      * with {@code subtrahend} interpreted as a real number.
  738.      * Implements the formula:
  739.      *
  740.      * <p>\[ (a + i b) - c = (a - c) + i b \]
  741.      *
  742.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  743.      * real-only and complex numbers.</p>
  744.      *
  745.      * @param  subtrahend Value to be subtracted from this complex number.
  746.      * @return {@code this - subtrahend}.
  747.      * @see #subtract(Complex)
  748.      */
  749.     public Complex subtract(double subtrahend) {
  750.         return new Complex(real - subtrahend, imaginary);
  751.     }

  752.     /**
  753.      * Returns a {@code Complex} whose value is {@code (this - subtrahend)},
  754.      * with {@code subtrahend} interpreted as an imaginary number.
  755.      * Implements the formula:
  756.      *
  757.      * <p>\[ (a + i b) - i d = a + i (b - d) \]
  758.      *
  759.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  760.      * imaginary-only and complex numbers.</p>
  761.      *
  762.      * @param  subtrahend Value to be subtracted from this complex number.
  763.      * @return {@code this - subtrahend}.
  764.      * @see #subtract(Complex)
  765.      */
  766.     public Complex subtractImaginary(double subtrahend) {
  767.         return new Complex(real, imaginary - subtrahend);
  768.     }

  769.     /**
  770.      * Returns a {@code Complex} whose value is {@code (minuend - this)},
  771.      * with {@code minuend} interpreted as a real number.
  772.      * Implements the formula:
  773.      * \[ c - (a + i b) = (c - a) - i b \]
  774.      *
  775.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  776.      * real-only and complex numbers.</p>
  777.      *
  778.      * <p>Note: This method inverts the sign of the imaginary component \( b \) if it is {@code 0.0}.
  779.      * The sign would not be inverted if subtracting from \( c + i 0 \) using
  780.      * {@link #subtract(Complex) Complex.ofCartesian(minuend, 0).subtract(this)} since
  781.      * {@code 0.0 - 0.0 = 0.0}.
  782.      *
  783.      * @param  minuend Value this complex number is to be subtracted from.
  784.      * @return {@code minuend - this}.
  785.      * @see #subtract(Complex)
  786.      * @see #ofCartesian(double, double)
  787.      */
  788.     public Complex subtractFrom(double minuend) {
  789.         return new Complex(minuend - real, -imaginary);
  790.     }

  791.     /**
  792.      * Returns a {@code Complex} whose value is {@code (this - subtrahend)},
  793.      * with {@code minuend} interpreted as an imaginary number.
  794.      * Implements the formula:
  795.      * \[ i d - (a + i b) = -a + i (d - b) \]
  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.      * <p>Note: This method inverts the sign of the real component \( a \) if it is {@code 0.0}.
  801.      * The sign would not be inverted if subtracting from \( 0 + i d \) using
  802.      * {@link #subtract(Complex) Complex.ofCartesian(0, minuend).subtract(this)} since
  803.      * {@code 0.0 - 0.0 = 0.0}.
  804.      *
  805.      * @param  minuend Value this complex number is to be subtracted from.
  806.      * @return {@code this - subtrahend}.
  807.      * @see #subtract(Complex)
  808.      * @see #ofCartesian(double, double)
  809.      */
  810.     public Complex subtractFromImaginary(double minuend) {
  811.         return new Complex(-real, minuend - imaginary);
  812.     }

  813.     /**
  814.      * Returns a {@code Complex} whose value is {@code this * factor}.
  815.      * Implements the formula:
  816.      *
  817.      * <p>\[ (a + i b)(c + i d) = (ac - bd) + i (ad + bc) \]
  818.      *
  819.      * <p>Recalculates to recover infinities as specified in C99 standard G.5.1.
  820.      *
  821.      * @param  factor Value to be multiplied by this complex number.
  822.      * @return {@code this * factor}.
  823.      * @see <a href="http://mathworld.wolfram.com/ComplexMultiplication.html">Complex Muliplication</a>
  824.      */
  825.     public Complex multiply(Complex factor) {
  826.         return multiply(real, imaginary, factor.real, factor.imaginary);
  827.     }

  828.     /**
  829.      * Returns a {@code Complex} whose value is:
  830.      * <pre>
  831.      *  (a + i b)(c + i d) = (ac - bd) + i (ad + bc)</pre>
  832.      *
  833.      * <p>Recalculates to recover infinities as specified in C99 standard G.5.1.
  834.      *
  835.      * @param re1 Real component of first number.
  836.      * @param im1 Imaginary component of first number.
  837.      * @param re2 Real component of second number.
  838.      * @param im2 Imaginary component of second number.
  839.      * @return (a + b i)(c + d i).
  840.      */
  841.     private static Complex multiply(double re1, double im1, double re2, double im2) {
  842.         double a = re1;
  843.         double b = im1;
  844.         double c = re2;
  845.         double d = im2;
  846.         final double ac = a * c;
  847.         final double bd = b * d;
  848.         final double ad = a * d;
  849.         final double bc = b * c;
  850.         double x = ac - bd;
  851.         double y = ad + bc;

  852.         // --------------
  853.         // NaN can occur if:
  854.         // - any of (a,b,c,d) are NaN (for NaN or Infinite complex numbers)
  855.         // - a multiplication of infinity by zero (ac,bd,ad,bc).
  856.         // - a subtraction of infinity from infinity (e.g. ac - bd)
  857.         //   Note that (ac,bd,ad,bc) can be infinite due to overflow.
  858.         //
  859.         // Detect a NaN result and perform correction.
  860.         //
  861.         // Modification from the listing in ISO C99 G.5.1 (6)
  862.         // Do not correct infinity multiplied by zero. This is left as NaN.
  863.         // --------------

  864.         if (Double.isNaN(x) && Double.isNaN(y)) {
  865.             // Recover infinities that computed as NaN+iNaN ...
  866.             boolean recalc = false;
  867.             if ((Double.isInfinite(a) || Double.isInfinite(b)) &&
  868.                 isNotZero(c, d)) {
  869.                 // This complex is infinite.
  870.                 // "Box" the infinity and change NaNs in the other factor to 0.
  871.                 a = boxInfinity(a);
  872.                 b = boxInfinity(b);
  873.                 c = changeNaNtoZero(c);
  874.                 d = changeNaNtoZero(d);
  875.                 recalc = true;
  876.             }
  877.             if ((Double.isInfinite(c) || Double.isInfinite(d)) &&
  878.                 isNotZero(a, b)) {
  879.                 // The other complex is infinite.
  880.                 // "Box" the infinity and change NaNs in the other factor to 0.
  881.                 c = boxInfinity(c);
  882.                 d = boxInfinity(d);
  883.                 a = changeNaNtoZero(a);
  884.                 b = changeNaNtoZero(b);
  885.                 recalc = true;
  886.             }
  887.             if (!recalc && (Double.isInfinite(ac) || Double.isInfinite(bd) ||
  888.                             Double.isInfinite(ad) || Double.isInfinite(bc))) {
  889.                 // The result overflowed to infinity.
  890.                 // Recover infinities from overflow by changing NaNs to 0 ...
  891.                 a = changeNaNtoZero(a);
  892.                 b = changeNaNtoZero(b);
  893.                 c = changeNaNtoZero(c);
  894.                 d = changeNaNtoZero(d);
  895.                 recalc = true;
  896.             }
  897.             if (recalc) {
  898.                 x = Double.POSITIVE_INFINITY * (a * c - b * d);
  899.                 y = Double.POSITIVE_INFINITY * (a * d + b * c);
  900.             }
  901.         }
  902.         return new Complex(x, y);
  903.     }

  904.     /**
  905.      * Box values for the real or imaginary component of an infinite complex number.
  906.      * Any infinite value will be returned as one. Non-infinite values will be returned as zero.
  907.      * The sign is maintained.
  908.      *
  909.      * <pre>
  910.      *  inf  =  1
  911.      * -inf  = -1
  912.      *  x    =  0
  913.      * -x    = -0
  914.      * </pre>
  915.      *
  916.      * @param component the component
  917.      * @return The boxed value
  918.      */
  919.     private static double boxInfinity(double component) {
  920.         return Math.copySign(Double.isInfinite(component) ? 1.0 : 0.0, component);
  921.     }

  922.     /**
  923.      * Checks if the complex number is not zero.
  924.      *
  925.      * @param real the real component
  926.      * @param imaginary the imaginary component
  927.      * @return true if the complex is not zero
  928.      */
  929.     private static boolean isNotZero(double real, double imaginary) {
  930.         // The use of equals is deliberate.
  931.         // This method must distinguish NaN from zero thus ruling out:
  932.         // (real != 0.0 || imaginary != 0.0)
  933.         return !(real == 0.0 && imaginary == 0.0);
  934.     }

  935.     /**
  936.      * Change NaN to zero preserving the sign; otherwise return the value.
  937.      *
  938.      * @param value the value
  939.      * @return The new value
  940.      */
  941.     private static double changeNaNtoZero(double value) {
  942.         return Double.isNaN(value) ? Math.copySign(0.0, value) : value;
  943.     }

  944.     /**
  945.      * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor}
  946.      * interpreted as a real number.
  947.      * Implements the formula:
  948.      *
  949.      * <p>\[ (a + i b) c =  (ac) + i (bc) \]
  950.      *
  951.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  952.      * real-only and complex numbers.</p>
  953.      *
  954.      * <p>Note: This method should be preferred over using
  955.      * {@link #multiply(Complex) multiply(Complex.ofCartesian(factor, 0))}. Multiplication
  956.      * can generate signed zeros if either {@code this} complex has zeros for the real
  957.      * and/or imaginary component, or if the factor is zero. The summation of signed zeros
  958.      * in {@link #multiply(Complex)} may create zeros in the result that differ in sign
  959.      * from the equivalent call to multiply by a real-only number.
  960.      *
  961.      * @param  factor Value to be multiplied by this complex number.
  962.      * @return {@code this * factor}.
  963.      * @see #multiply(Complex)
  964.      */
  965.     public Complex multiply(double factor) {
  966.         return new Complex(real * factor, imaginary * factor);
  967.     }

  968.     /**
  969.      * Returns a {@code Complex} whose value is {@code this * factor}, with {@code factor}
  970.      * interpreted as an imaginary number.
  971.      * Implements the formula:
  972.      *
  973.      * <p>\[ (a + i b) id = (-bd) + i (ad) \]
  974.      *
  975.      * <p>This method can be used to compute the multiplication of this complex number \( z \)
  976.      * by \( i \) using a factor with magnitude 1.0. This should be used in preference to
  977.      * {@link #multiply(Complex) multiply(Complex.I)} with or without {@link #negate() negation}:</p>
  978.      *
  979.      * \[ \begin{aligned}
  980.      *    iz &amp;= (-b + i a) \\
  981.      *   -iz &amp;= (b - i a) \end{aligned} \]
  982.      *
  983.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  984.      * imaginary-only and complex numbers.</p>
  985.      *
  986.      * <p>Note: This method should be preferred over using
  987.      * {@link #multiply(Complex) multiply(Complex.ofCartesian(0, factor))}. Multiplication
  988.      * can generate signed zeros if either {@code this} complex has zeros for the real
  989.      * and/or imaginary component, or if the factor is zero. The summation of signed zeros
  990.      * in {@link #multiply(Complex)} may create zeros in the result that differ in sign
  991.      * from the equivalent call to multiply by an imaginary-only number.
  992.      *
  993.      * @param  factor Value to be multiplied by this complex number.
  994.      * @return {@code this * factor}.
  995.      * @see #multiply(Complex)
  996.      */
  997.     public Complex multiplyImaginary(double factor) {
  998.         return new Complex(-imaginary * factor, real * factor);
  999.     }

  1000.     /**
  1001.      * Returns a {@code Complex} whose value is {@code (this / divisor)}.
  1002.      * Implements the formula:
  1003.      *
  1004.      * <p>\[ \frac{a + i b}{c + i d} = \frac{(ac + bd) + i (bc - ad)}{c^2+d^2} \]
  1005.      *
  1006.      * <p>Re-calculates NaN result values to recover infinities as specified in C99 standard G.5.1.
  1007.      *
  1008.      * @param divisor Value by which this complex number is to be divided.
  1009.      * @return {@code this / divisor}.
  1010.      * @see <a href="http://mathworld.wolfram.com/ComplexDivision.html">Complex Division</a>
  1011.      */
  1012.     public Complex divide(Complex divisor) {
  1013.         return divide(real, imaginary, divisor.real, divisor.imaginary);
  1014.     }

  1015.     /**
  1016.      * Returns a {@code Complex} whose value is:
  1017.      * <pre>
  1018.      * <code>
  1019.      *   a + i b     (ac + bd) + i (bc - ad)
  1020.      *   -------  =  -----------------------
  1021.      *   c + i d            c<sup>2</sup> + d<sup>2</sup>
  1022.      * </code>
  1023.      * </pre>
  1024.      *
  1025.      * <p>Recalculates to recover infinities as specified in C99
  1026.      * standard G.5.1. Method is fully in accordance with
  1027.      * C++11 standards for complex numbers.</p>
  1028.      *
  1029.      * <p>Note: In the event of divide by zero this method produces the same result
  1030.      * as dividing by a real-only zero using {@link #divide(double)}.
  1031.      *
  1032.      * @param re1 Real component of first number.
  1033.      * @param im1 Imaginary component of first number.
  1034.      * @param re2 Real component of second number.
  1035.      * @param im2 Imaginary component of second number.
  1036.      * @return (a + i b) / (c + i d).
  1037.      * @see <a href="http://mathworld.wolfram.com/ComplexDivision.html">Complex Division</a>
  1038.      * @see #divide(double)
  1039.      */
  1040.     private static Complex divide(double re1, double im1, double re2, double im2) {
  1041.         double a = re1;
  1042.         double b = im1;
  1043.         double c = re2;
  1044.         double d = im2;
  1045.         int ilogbw = 0;
  1046.         // Get the exponent to scale the divisor parts to the range [1, 2).
  1047.         final int exponent = getScale(c, d);
  1048.         if (exponent <= Double.MAX_EXPONENT) {
  1049.             ilogbw = exponent;
  1050.             c = Math.scalb(c, -ilogbw);
  1051.             d = Math.scalb(d, -ilogbw);
  1052.         }
  1053.         final double denom = c * c + d * d;

  1054.         // Note: Modification from the listing in ISO C99 G.5.1 (8):
  1055.         // Avoid overflow if a or b are very big.
  1056.         // Since (c, d) in the range [1, 2) the sum (ac + bd) could overflow
  1057.         // when (a, b) are both above (Double.MAX_VALUE / 4). The same applies to
  1058.         // (bc - ad) with large negative values.
  1059.         // Use the maximum exponent as an approximation to the magnitude.
  1060.         if (getMaxExponent(a, b) > Double.MAX_EXPONENT - 2) {
  1061.             ilogbw -= 2;
  1062.             a /= 4;
  1063.             b /= 4;
  1064.         }

  1065.         double x = Math.scalb((a * c + b * d) / denom, -ilogbw);
  1066.         double y = Math.scalb((b * c - a * d) / denom, -ilogbw);
  1067.         // Recover infinities and zeros that computed as NaN+iNaN
  1068.         // the only cases are nonzero/zero, infinite/finite, and finite/infinite, ...
  1069.         if (Double.isNaN(x) && Double.isNaN(y)) {
  1070.             if (denom == 0.0 &&
  1071.                     (!Double.isNaN(a) || !Double.isNaN(b))) {
  1072.                 // nonzero/zero
  1073.                 // This case produces the same result as divide by a real-only zero
  1074.                 // using Complex.divide(+/-0.0)
  1075.                 x = Math.copySign(Double.POSITIVE_INFINITY, c) * a;
  1076.                 y = Math.copySign(Double.POSITIVE_INFINITY, c) * b;
  1077.             } else if ((Double.isInfinite(a) || Double.isInfinite(b)) &&
  1078.                     Double.isFinite(c) && Double.isFinite(d)) {
  1079.                 // infinite/finite
  1080.                 a = boxInfinity(a);
  1081.                 b = boxInfinity(b);
  1082.                 x = Double.POSITIVE_INFINITY * (a * c + b * d);
  1083.                 y = Double.POSITIVE_INFINITY * (b * c - a * d);
  1084.             } else if ((Double.isInfinite(c) || Double.isInfinite(d)) &&
  1085.                     Double.isFinite(a) && Double.isFinite(b)) {
  1086.                 // finite/infinite
  1087.                 c = boxInfinity(c);
  1088.                 d = boxInfinity(d);
  1089.                 x = 0.0 * (a * c + b * d);
  1090.                 y = 0.0 * (b * c - a * d);
  1091.             }
  1092.         }
  1093.         return new Complex(x, y);
  1094.     }

  1095.     /**
  1096.      * Returns a {@code Complex} whose value is {@code (this / divisor)},
  1097.      * with {@code divisor} interpreted as a real number.
  1098.      * Implements the formula:
  1099.      *
  1100.      * <p>\[ \frac{a + i b}{c} = \frac{a}{c} + i \frac{b}{c} \]
  1101.      *
  1102.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  1103.      * real-only and complex numbers.</p>
  1104.      *
  1105.      * <p>Note: This method should be preferred over using
  1106.      * {@link #divide(Complex) divide(Complex.ofCartesian(divisor, 0))}. Division
  1107.      * can generate signed zeros if {@code this} complex has zeros for the real
  1108.      * and/or imaginary component, or the divisor is infinite. The summation of signed zeros
  1109.      * in {@link #divide(Complex)} may create zeros in the result that differ in sign
  1110.      * from the equivalent call to divide by a real-only number.
  1111.      *
  1112.      * @param  divisor Value by which this complex number is to be divided.
  1113.      * @return {@code this / divisor}.
  1114.      * @see #divide(Complex)
  1115.      */
  1116.     public Complex divide(double divisor) {
  1117.         return new Complex(real / divisor, imaginary / divisor);
  1118.     }

  1119.     /**
  1120.      * Returns a {@code Complex} whose value is {@code (this / divisor)},
  1121.      * with {@code divisor} interpreted as an imaginary number.
  1122.      * Implements the formula:
  1123.      *
  1124.      * <p>\[ \frac{a + i b}{id} = \frac{b}{d} - i \frac{a}{d} \]
  1125.      *
  1126.      * <p>This method is included for compatibility with ISO C99 which defines arithmetic between
  1127.      * imaginary-only and complex numbers.</p>
  1128.      *
  1129.      * <p>Note: This method should be preferred over using
  1130.      * {@link #divide(Complex) divide(Complex.ofCartesian(0, divisor))}. Division
  1131.      * can generate signed zeros if {@code this} complex has zeros for the real
  1132.      * and/or imaginary component, or the divisor is infinite. The summation of signed zeros
  1133.      * in {@link #divide(Complex)} may create zeros in the result that differ in sign
  1134.      * from the equivalent call to divide by an imaginary-only number.
  1135.      *
  1136.      * <p>Warning: This method will generate a different result from
  1137.      * {@link #divide(Complex) divide(Complex.ofCartesian(0, divisor))} if the divisor is zero.
  1138.      * In this case the divide method using a zero-valued Complex will produce the same result
  1139.      * as dividing by a real-only zero. The output from dividing by imaginary zero will create
  1140.      * infinite and NaN values in the same component parts as the output from
  1141.      * {@code this.divide(Complex.ZERO).multiplyImaginary(1)}, however the sign
  1142.      * of some infinite values may be negated.
  1143.      *
  1144.      * @param  divisor Value by which this complex number is to be divided.
  1145.      * @return {@code this / divisor}.
  1146.      * @see #divide(Complex)
  1147.      * @see #divide(double)
  1148.      */
  1149.     public Complex divideImaginary(double divisor) {
  1150.         return new Complex(imaginary / divisor, -real / divisor);
  1151.     }

  1152.     /**
  1153.      * Returns the
  1154.      * <a href="http://mathworld.wolfram.com/ExponentialFunction.html">
  1155.      * exponential function</a> of this complex number.
  1156.      *
  1157.      * <p>\[ \exp(z) = e^z \]
  1158.      *
  1159.      * <p>The exponential function of \( z \) is an entire function in the complex plane.
  1160.      * Special cases:
  1161.      *
  1162.      * <ul>
  1163.      * <li>{@code z.conj().exp() == z.exp().conj()}.
  1164.      * <li>If {@code z} is ±0 + i0, returns 1 + i0.
  1165.      * <li>If {@code z} is x + i∞ for finite x, returns NaN + iNaN ("invalid" floating-point operation).
  1166.      * <li>If {@code z} is x + iNaN for finite x, returns NaN + iNaN ("invalid" floating-point operation).
  1167.      * <li>If {@code z} is +∞ + i0, returns +∞ + i0.
  1168.      * <li>If {@code z} is −∞ + iy for finite y, returns +0 cis(y) (see {@link #ofCis(double)}).
  1169.      * <li>If {@code z} is +∞ + iy for finite nonzero y, returns +∞ cis(y).
  1170.      * <li>If {@code z} is −∞ + i∞, returns ±0 ± i0 (where the signs of the real and imaginary parts of the result are unspecified).
  1171.      * <li>If {@code z} is +∞ + i∞, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified; "invalid" floating-point operation).
  1172.      * <li>If {@code z} is −∞ + iNaN, returns ±0 ± i0 (where the signs of the real and imaginary parts of the result are unspecified).
  1173.      * <li>If {@code z} is +∞ + iNaN, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified).
  1174.      * <li>If {@code z} is NaN + i0, returns NaN + i0.
  1175.      * <li>If {@code z} is NaN + iy for all nonzero numbers y, returns NaN + iNaN ("invalid" floating-point operation).
  1176.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  1177.      * </ul>
  1178.      *
  1179.      * <p>Implements the formula:
  1180.      *
  1181.      * <p>\[ \exp(x + iy) = e^x (\cos(y) + i \sin(y)) \]
  1182.      *
  1183.      * @return The exponential of this complex number.
  1184.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Exp/">Exp</a>
  1185.      */
  1186.     public Complex exp() {
  1187.         if (Double.isInfinite(real)) {
  1188.             // Set the scale factor applied to cis(y)
  1189.             final double zeroOrInf;
  1190.             if (real < 0) {
  1191.                 if (!Double.isFinite(imaginary)) {
  1192.                     // (−∞ + i∞) or (−∞ + iNaN) returns (±0 ± i0) (where the signs of the
  1193.                     // real and imaginary parts of the result are unspecified).
  1194.                     // Here we preserve the conjugate equality.
  1195.                     return new Complex(0, Math.copySign(0, imaginary));
  1196.                 }
  1197.                 // (−∞ + iy) returns +0 cis(y), for finite y
  1198.                 zeroOrInf = 0;
  1199.             } else {
  1200.                 // (+∞ + i0) returns +∞ + i0.
  1201.                 if (imaginary == 0) {
  1202.                     return this;
  1203.                 }
  1204.                 // (+∞ + i∞) or (+∞ + iNaN) returns (±∞ + iNaN) and raises the invalid
  1205.                 // floating-point exception (where the sign of the real part of the
  1206.                 // result is unspecified).
  1207.                 if (!Double.isFinite(imaginary)) {
  1208.                     return new Complex(real, Double.NaN);
  1209.                 }
  1210.                 // (+∞ + iy) returns (+∞ cis(y)), for finite nonzero y.
  1211.                 zeroOrInf = real;
  1212.             }
  1213.             return new Complex(zeroOrInf * Math.cos(imaginary),
  1214.                                zeroOrInf * Math.sin(imaginary));
  1215.         } else if (Double.isNaN(real)) {
  1216.             // (NaN + i0) returns (NaN + i0)
  1217.             // (NaN + iy) returns (NaN + iNaN) and optionally raises the invalid floating-point exception
  1218.             // (NaN + iNaN) returns (NaN + iNaN)
  1219.             return imaginary == 0 ? this : NAN;
  1220.         } else if (!Double.isFinite(imaginary)) {
  1221.             // (x + i∞) or (x + iNaN) returns (NaN + iNaN) and raises the invalid
  1222.             // floating-point exception, for finite x.
  1223.             return NAN;
  1224.         }
  1225.         // real and imaginary are finite.
  1226.         // Compute e^a * (cos(b) + i sin(b)).

  1227.         // Special case:
  1228.         // (±0 + i0) returns (1 + i0)
  1229.         final double exp = Math.exp(real);
  1230.         if (imaginary == 0) {
  1231.             return new Complex(exp, imaginary);
  1232.         }
  1233.         return new Complex(exp * Math.cos(imaginary),
  1234.                            exp * Math.sin(imaginary));
  1235.     }

  1236.     /**
  1237.      * Returns the
  1238.      * <a href="http://mathworld.wolfram.com/NaturalLogarithm.html">
  1239.      * natural logarithm</a> of this complex number.
  1240.      *
  1241.      * <p>The natural logarithm of \( z \) is unbounded along the real axis and
  1242.      * in the range \( [-\pi, \pi] \) along the imaginary axis. The imaginary part of the
  1243.      * natural logarithm has a branch cut along the negative real axis \( (-infty,0] \).
  1244.      * Special cases:
  1245.      *
  1246.      * <ul>
  1247.      * <li>{@code z.conj().log() == z.log().conj()}.
  1248.      * <li>If {@code z} is −0 + i0, returns −∞ + iπ ("divide-by-zero" floating-point operation).
  1249.      * <li>If {@code z} is +0 + i0, returns −∞ + i0 ("divide-by-zero" floating-point operation).
  1250.      * <li>If {@code z} is x + i∞ for finite x, returns +∞ + iπ/2.
  1251.      * <li>If {@code z} is x + iNaN for finite x, returns NaN + iNaN ("invalid" floating-point operation).
  1252.      * <li>If {@code z} is −∞ + iy for finite positive-signed y, returns +∞ + iπ.
  1253.      * <li>If {@code z} is +∞ + iy for finite positive-signed y, returns +∞ + i0.
  1254.      * <li>If {@code z} is −∞ + i∞, returns +∞ + i3π/4.
  1255.      * <li>If {@code z} is +∞ + i∞, returns +∞ + iπ/4.
  1256.      * <li>If {@code z} is ±∞ + iNaN, returns +∞ + iNaN.
  1257.      * <li>If {@code z} is NaN + iy for finite y, returns NaN + iNaN ("invalid" floating-point operation).
  1258.      * <li>If {@code z} is NaN + i∞, returns +∞ + iNaN.
  1259.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  1260.      * </ul>
  1261.      *
  1262.      * <p>Implements the formula:
  1263.      *
  1264.      * <p>\[ \ln(z) = \ln |z| + i \arg(z) \]
  1265.      *
  1266.      * <p>where \( |z| \) is the absolute and \( \arg(z) \) is the argument.
  1267.      *
  1268.      * <p>The implementation is based on the method described in:</p>
  1269.      * <blockquote>
  1270.      * T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang (1994)
  1271.      * Implementing complex elementary functions using exception handling.
  1272.      * ACM Transactions on Mathematical Software, Vol 20, No 2, pp 215-244.
  1273.      * </blockquote>
  1274.      *
  1275.      * @return The natural logarithm of this complex number.
  1276.      * @see Math#log(double)
  1277.      * @see #abs()
  1278.      * @see #arg()
  1279.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Log/">Log</a>
  1280.      */
  1281.     public Complex log() {
  1282.         return log(Math::log, HALF, LN_2, Complex::ofCartesian);
  1283.     }

  1284.     /**
  1285.      * Returns the base 10
  1286.      * <a href="http://mathworld.wolfram.com/CommonLogarithm.html">
  1287.      * common logarithm</a> of this complex number.
  1288.      *
  1289.      * <p>The common logarithm of \( z \) is unbounded along the real axis and
  1290.      * in the range \( [-\pi, \pi] \) along the imaginary axis. The imaginary part of the
  1291.      * common logarithm has a branch cut along the negative real axis \( (-infty,0] \).
  1292.      * Special cases are as defined in the {@link #log() natural logarithm}:
  1293.      *
  1294.      * <p>Implements the formula:
  1295.      *
  1296.      * <p>\[ \log_{10}(z) = \log_{10} |z| + i \arg(z) \]
  1297.      *
  1298.      * <p>where \( |z| \) is the absolute and \( \arg(z) \) is the argument.
  1299.      *
  1300.      * @return The base 10 logarithm of this complex number.
  1301.      * @see Math#log10(double)
  1302.      * @see #abs()
  1303.      * @see #arg()
  1304.      */
  1305.     public Complex log10() {
  1306.         return log(Math::log10, LOG_10E_O_2, LOG10_2, Complex::ofCartesian);
  1307.     }

  1308.     /**
  1309.      * Returns the logarithm of this complex number using the provided function.
  1310.      * Implements the formula:
  1311.      *
  1312.      * <pre>
  1313.      *   log(x + i y) = log(|x + i y|) + i arg(x + i y)</pre>
  1314.      *
  1315.      * <p>Warning: The argument {@code logOf2} must be equal to {@code log(2)} using the
  1316.      * provided log function otherwise scaling using powers of 2 in the case of overflow
  1317.      * will be incorrect. This is provided as an internal optimisation.
  1318.      *
  1319.      * @param log Log function.
  1320.      * @param logOfeOver2 The log function applied to e, then divided by 2.
  1321.      * @param logOf2 The log function applied to 2.
  1322.      * @param constructor Constructor for the returned complex.
  1323.      * @return The logarithm of this complex number.
  1324.      * @see #abs()
  1325.      * @see #arg()
  1326.      */
  1327.     private Complex log(DoubleUnaryOperator log, double logOfeOver2, double logOf2, ComplexConstructor constructor) {
  1328.         // Handle NaN
  1329.         if (Double.isNaN(real) || Double.isNaN(imaginary)) {
  1330.             // Return NaN unless infinite
  1331.             if (isInfinite()) {
  1332.                 return constructor.create(Double.POSITIVE_INFINITY, Double.NaN);
  1333.             }
  1334.             // No-use of the input constructor
  1335.             return NAN;
  1336.         }

  1337.         // Returns the real part:
  1338.         // log(sqrt(x^2 + y^2))
  1339.         // log(x^2 + y^2) / 2

  1340.         // Compute with positive values
  1341.         double x = Math.abs(real);
  1342.         double y = Math.abs(imaginary);

  1343.         // Find the larger magnitude.
  1344.         if (x < y) {
  1345.             final double tmp = x;
  1346.             x = y;
  1347.             y = tmp;
  1348.         }

  1349.         if (x == 0) {
  1350.             // Handle zero: raises the ‘‘divide-by-zero’’ floating-point exception.
  1351.             return constructor.create(Double.NEGATIVE_INFINITY,
  1352.                                       negative(real) ? Math.copySign(Math.PI, imaginary) : imaginary);
  1353.         }

  1354.         double re;

  1355.         // This alters the implementation of Hull et al (1994) which used a standard
  1356.         // precision representation of |z|: sqrt(x*x + y*y).
  1357.         // This formula should use the same definition of the magnitude returned
  1358.         // by Complex.abs() which is a high precision computation with scaling.
  1359.         // The checks for overflow thus only require ensuring the output of |z|
  1360.         // will not overflow or underflow.

  1361.         if (x > HALF && x < ROOT2) {
  1362.             // x^2+y^2 close to 1. Use log1p(x^2+y^2 - 1) / 2.
  1363.             re = Math.log1p(x2y2m1(x, y)) * logOfeOver2;
  1364.         } else {
  1365.             // Check for over/underflow in |z|
  1366.             // When scaling:
  1367.             // log(a / b) = log(a) - log(b)
  1368.             // So initialize the result with the log of the scale factor.
  1369.             re = 0;
  1370.             if (x > Double.MAX_VALUE / 2) {
  1371.                 // Potential overflow.
  1372.                 if (isPosInfinite(x)) {
  1373.                     // Handle infinity
  1374.                     return constructor.create(x, arg());
  1375.                 }
  1376.                 // Scale down.
  1377.                 x /= 2;
  1378.                 y /= 2;
  1379.                 // log(2)
  1380.                 re = logOf2;
  1381.             } else if (y < Double.MIN_NORMAL) {
  1382.                 // Potential underflow.
  1383.                 if (y == 0) {
  1384.                     // Handle real only number
  1385.                     return constructor.create(log.applyAsDouble(x), arg());
  1386.                 }
  1387.                 // Scale up sub-normal numbers to make them normal by scaling by 2^54,
  1388.                 // i.e. more than the mantissa digits.
  1389.                 x *= 0x1.0p54;
  1390.                 y *= 0x1.0p54;
  1391.                 // log(2^-54) = -54 * log(2)
  1392.                 re = -54 * logOf2;
  1393.             }
  1394.             re += log.applyAsDouble(abs(x, y));
  1395.         }

  1396.         // All ISO C99 edge cases for the imaginary are satisfied by the Math library.
  1397.         return constructor.create(re, arg());
  1398.     }

  1399.     /**
  1400.      * Returns the complex power of this complex number raised to the power of {@code x}.
  1401.      * Implements the formula:
  1402.      *
  1403.      * <p>\[ z^x = e^{x \ln(z)} \]
  1404.      *
  1405.      * <p>If this complex number is zero then this method returns zero if {@code x} is positive
  1406.      * in the real component and zero in the imaginary component;
  1407.      * otherwise it returns NaN + iNaN.
  1408.      *
  1409.      * @param  x The exponent to which this complex number is to be raised.
  1410.      * @return This complex number raised to the power of {@code x}.
  1411.      * @see #log()
  1412.      * @see #multiply(Complex)
  1413.      * @see #exp()
  1414.      * @see <a href="http://mathworld.wolfram.com/ComplexExponentiation.html">Complex exponentiation</a>
  1415.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Power/">Power</a>
  1416.      */
  1417.     public Complex pow(Complex x) {
  1418.         if (real == 0 &&
  1419.             imaginary == 0) {
  1420.             // This value is zero. Test the other.
  1421.             if (x.real > 0 &&
  1422.                 x.imaginary == 0) {
  1423.                 // 0 raised to positive number is 0
  1424.                 return ZERO;
  1425.             }
  1426.             // 0 raised to anything else is NaN
  1427.             return NAN;
  1428.         }
  1429.         return log().multiply(x).exp();
  1430.     }

  1431.     /**
  1432.      * Returns the complex power of this complex number raised to the power of {@code x},
  1433.      * with {@code x} interpreted as a real number.
  1434.      * Implements the formula:
  1435.      *
  1436.      * <p>\[ z^x = e^{x \ln(z)} \]
  1437.      *
  1438.      * <p>If this complex number is zero then this method returns zero if {@code x} is positive;
  1439.      * otherwise it returns NaN + iNaN.
  1440.      *
  1441.      * @param  x The exponent to which this complex number is to be raised.
  1442.      * @return This complex number raised to the power of {@code x}.
  1443.      * @see #log()
  1444.      * @see #multiply(double)
  1445.      * @see #exp()
  1446.      * @see #pow(Complex)
  1447.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Power/">Power</a>
  1448.      */
  1449.     public Complex pow(double x) {
  1450.         if (real == 0 &&
  1451.             imaginary == 0) {
  1452.             // This value is zero. Test the other.
  1453.             if (x > 0) {
  1454.                 // 0 raised to positive number is 0
  1455.                 return ZERO;
  1456.             }
  1457.             // 0 raised to anything else is NaN
  1458.             return NAN;
  1459.         }
  1460.         return log().multiply(x).exp();
  1461.     }

  1462.     /**
  1463.      * Returns the
  1464.      * <a href="http://mathworld.wolfram.com/SquareRoot.html">
  1465.      * square root</a> of this complex number.
  1466.      *
  1467.      * <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) \]
  1468.      *
  1469.      * <p>The square root of \( z \) is in the range \( [0, +\infty) \) along the real axis and
  1470.      * is unbounded along the imaginary axis. The imaginary part of the square root has a
  1471.      * branch cut along the negative real axis \( (-infty,0) \). Special cases:
  1472.      *
  1473.      * <ul>
  1474.      * <li>{@code z.conj().sqrt() == z.sqrt().conj()}.
  1475.      * <li>If {@code z} is ±0 + i0, returns +0 + i0.
  1476.      * <li>If {@code z} is x + i∞ for all x (including NaN), returns +∞ + i∞.
  1477.      * <li>If {@code z} is x + iNaN for finite x, returns NaN + iNaN ("invalid" floating-point operation).
  1478.      * <li>If {@code z} is −∞ + iy for finite positive-signed y, returns +0 + i∞.
  1479.      * <li>If {@code z} is +∞ + iy for finite positive-signed y, returns +∞ + i0.
  1480.      * <li>If {@code z} is −∞ + iNaN, returns NaN ± i∞ (where the sign of the imaginary part of the result is unspecified).
  1481.      * <li>If {@code z} is +∞ + iNaN, returns +∞ + iNaN.
  1482.      * <li>If {@code z} is NaN + iy for finite y, returns NaN + iNaN ("invalid" floating-point operation).
  1483.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  1484.      * </ul>
  1485.      *
  1486.      * <p>Implements the following algorithm to compute \( \sqrt{x + iy} \):
  1487.      * <ol>
  1488.      * <li>Let \( t = \sqrt{2 (|x| + |x + iy|)} \)
  1489.      * <li>if \( x \geq 0 \) return \( \frac{t}{2} + i \frac{y}{t} \)
  1490.      * <li>else return \( \frac{|y|}{t} + i\ \text{sgn}(y) \frac{t}{2} \)
  1491.      * </ol>
  1492.      * where:
  1493.      * <ul>
  1494.      * <li>\( |x| =\ \){@link Math#abs(double) abs}(x)
  1495.      * <li>\( |x + y i| =\ \){@link Complex#abs}
  1496.      * <li>\( \text{sgn}(y) =\ \){@link Math#copySign(double,double) copySign}(1.0, y)
  1497.      * </ul>
  1498.      *
  1499.      * <p>The implementation is overflow and underflow safe based on the method described in:</p>
  1500.      * <blockquote>
  1501.      * T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang (1994)
  1502.      * Implementing complex elementary functions using exception handling.
  1503.      * ACM Transactions on Mathematical Software, Vol 20, No 2, pp 215-244.
  1504.      * </blockquote>
  1505.      *
  1506.      * @return The square root of this complex number.
  1507.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Sqrt/">Sqrt</a>
  1508.      */
  1509.     public Complex sqrt() {
  1510.         return sqrt(real, imaginary);
  1511.     }

  1512.     /**
  1513.      * Returns the square root of the complex number {@code sqrt(x + i y)}.
  1514.      *
  1515.      * @param real Real component.
  1516.      * @param imaginary Imaginary component.
  1517.      * @return The square root of the complex number.
  1518.      */
  1519.     private static Complex sqrt(double real, double imaginary) {
  1520.         // Handle NaN
  1521.         if (Double.isNaN(real) || Double.isNaN(imaginary)) {
  1522.             // Check for infinite
  1523.             if (Double.isInfinite(imaginary)) {
  1524.                 return new Complex(Double.POSITIVE_INFINITY, imaginary);
  1525.             }
  1526.             if (Double.isInfinite(real)) {
  1527.                 if (real == Double.NEGATIVE_INFINITY) {
  1528.                     return new Complex(Double.NaN, Math.copySign(Double.POSITIVE_INFINITY, imaginary));
  1529.                 }
  1530.                 return new Complex(Double.POSITIVE_INFINITY, Double.NaN);
  1531.             }
  1532.             return NAN;
  1533.         }

  1534.         // Compute with positive values and determine sign at the end
  1535.         final double x = Math.abs(real);
  1536.         final double y = Math.abs(imaginary);

  1537.         // Compute
  1538.         final double t;

  1539.         // This alters the implementation of Hull et al (1994) which used a standard
  1540.         // precision representation of |z|: sqrt(x*x + y*y).
  1541.         // This formula should use the same definition of the magnitude returned
  1542.         // by Complex.abs() which is a high precision computation with scaling.
  1543.         // Worry about overflow if 2 * (|z| + |x|) will overflow.
  1544.         // Worry about underflow if |z| or |x| are sub-normal components.

  1545.         if (inRegion(x, y, Double.MIN_NORMAL, SQRT_SAFE_UPPER)) {
  1546.             // No over/underflow
  1547.             t = Math.sqrt(2 * (abs(x, y) + x));
  1548.         } else {
  1549.             // Potential over/underflow. First check infinites and real/imaginary only.

  1550.             // Check for infinite
  1551.             if (isPosInfinite(y)) {
  1552.                 return new Complex(Double.POSITIVE_INFINITY, imaginary);
  1553.             } else if (isPosInfinite(x)) {
  1554.                 if (real == Double.NEGATIVE_INFINITY) {
  1555.                     return new Complex(0, Math.copySign(Double.POSITIVE_INFINITY, imaginary));
  1556.                 }
  1557.                 return new Complex(Double.POSITIVE_INFINITY, Math.copySign(0, imaginary));
  1558.             } else if (y == 0) {
  1559.                 // Real only
  1560.                 final double sqrtAbs = Math.sqrt(x);
  1561.                 if (real < 0) {
  1562.                     return new Complex(0, Math.copySign(sqrtAbs, imaginary));
  1563.                 }
  1564.                 return new Complex(sqrtAbs, imaginary);
  1565.             } else if (x == 0) {
  1566.                 // Imaginary only. This sets the two components to the same magnitude.
  1567.                 // Note: In polar coordinates this does not happen:
  1568.                 // real = sqrt(abs()) * Math.cos(arg() / 2)
  1569.                 // imag = sqrt(abs()) * Math.sin(arg() / 2)
  1570.                 // arg() / 2 = pi/4 and cos and sin should both return sqrt(2)/2 but
  1571.                 // are different by 1 ULP.
  1572.                 final double sqrtAbs = Math.sqrt(y) * ONE_OVER_ROOT2;
  1573.                 return new Complex(sqrtAbs, Math.copySign(sqrtAbs, imaginary));
  1574.             } else {
  1575.                 // Over/underflow.
  1576.                 // Full scaling is not required as this is done in the hypotenuse function.
  1577.                 // Keep the number as big as possible for maximum precision in the second sqrt.
  1578.                 // Note if we scale by an even power of 2, we can re-scale by sqrt of the number.
  1579.                 // a = sqrt(b)
  1580.                 // a = sqrt(b/4) * sqrt(4)

  1581.                 final double rescale;
  1582.                 final double sx;
  1583.                 final double sy;
  1584.                 if (Math.max(x, y) > SQRT_SAFE_UPPER) {
  1585.                     // Overflow. Scale down by 16 and rescale by sqrt(16).
  1586.                     sx = x / 16;
  1587.                     sy = y / 16;
  1588.                     rescale = 4;
  1589.                 } else {
  1590.                     // Sub-normal numbers. Make them normal by scaling by 2^54,
  1591.                     // i.e. more than the mantissa digits, and rescale by sqrt(2^54) = 2^27.
  1592.                     sx = x * 0x1.0p54;
  1593.                     sy = y * 0x1.0p54;
  1594.                     rescale = 0x1.0p-27;
  1595.                 }
  1596.                 t = rescale * Math.sqrt(2 * (abs(sx, sy) + sx));
  1597.             }
  1598.         }

  1599.         if (real >= 0) {
  1600.             return new Complex(t / 2, imaginary / t);
  1601.         }
  1602.         return new Complex(y / t, Math.copySign(t / 2, imaginary));
  1603.     }

  1604.     /**
  1605.      * Returns the
  1606.      * <a href="http://mathworld.wolfram.com/Sine.html">
  1607.      * sine</a> of this complex number.
  1608.      *
  1609.      * <p>\[ \sin(z) = \frac{1}{2} i \left( e^{-iz} - e^{iz} \right) \]
  1610.      *
  1611.      * <p>This is an odd function: \( \sin(z) = -\sin(-z) \).
  1612.      * The sine is an entire function and requires no branch cuts.
  1613.      *
  1614.      * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
  1615.      *
  1616.      * <p>\[ \sin(x + iy) = \sin(x)\cosh(y) + i \cos(x)\sinh(y) \]
  1617.      *
  1618.      * <p>As per the C99 standard this function is computed using the trigonomic identity:
  1619.      *
  1620.      * <p>\[ \sin(z) = -i \sinh(iz) \]
  1621.      *
  1622.      * @return The sine of this complex number.
  1623.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Sin/">Sin</a>
  1624.      */
  1625.     public Complex sin() {
  1626.         // Define in terms of sinh
  1627.         // sin(z) = -i sinh(iz)
  1628.         // Multiply this number by I, compute sinh, then multiply by back
  1629.         return sinh(-imaginary, real, Complex::multiplyNegativeI);
  1630.     }

  1631.     /**
  1632.      * Returns the
  1633.      * <a href="http://mathworld.wolfram.com/Cosine.html">
  1634.      * cosine</a> of this complex number.
  1635.      *
  1636.      * <p>\[ \cos(z) = \frac{1}{2} \left( e^{iz} + e^{-iz} \right) \]
  1637.      *
  1638.      * <p>This is an even function: \( \cos(z) = \cos(-z) \).
  1639.      * The cosine is an entire function and requires no branch cuts.
  1640.      *
  1641.      * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
  1642.      *
  1643.      * <p>\[ \cos(x + iy) = \cos(x)\cosh(y) - i \sin(x)\sinh(y) \]
  1644.      *
  1645.      * <p>As per the C99 standard this function is computed using the trigonomic identity:
  1646.      *
  1647.      * <p>\[ cos(z) = cosh(iz) \]
  1648.      *
  1649.      * @return The cosine of this complex number.
  1650.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Cos/">Cos</a>
  1651.      */
  1652.     public Complex cos() {
  1653.         // Define in terms of cosh
  1654.         // cos(z) = cosh(iz)
  1655.         // Multiply this number by I and compute cosh.
  1656.         return cosh(-imaginary, real, Complex::ofCartesian);
  1657.     }

  1658.     /**
  1659.      * Returns the
  1660.      * <a href="http://mathworld.wolfram.com/Tangent.html">
  1661.      * tangent</a> of this complex number.
  1662.      *
  1663.      * <p>\[ \tan(z) = \frac{i(e^{-iz} - e^{iz})}{e^{-iz} + e^{iz}} \]
  1664.      *
  1665.      * <p>This is an odd function: \( \tan(z) = -\tan(-z) \).
  1666.      * The tangent is an entire function and requires no branch cuts.
  1667.      *
  1668.      * <p>This is implemented using real \( x \) and imaginary \( y \) parts:</p>
  1669.      * \[ \tan(x + iy) = \frac{\sin(2x)}{\cos(2x)+\cosh(2y)} + i \frac{\sinh(2y)}{\cos(2x)+\cosh(2y)} \]
  1670.      *
  1671.      * <p>As per the C99 standard this function is computed using the trigonomic identity:</p>
  1672.      * \[ \tan(z) = -i \tanh(iz) \]
  1673.      *
  1674.      * @return The tangent of this complex number.
  1675.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Tan/">Tangent</a>
  1676.      */
  1677.     public Complex tan() {
  1678.         // Define in terms of tanh
  1679.         // tan(z) = -i tanh(iz)
  1680.         // Multiply this number by I, compute tanh, then multiply by back
  1681.         return tanh(-imaginary, real, Complex::multiplyNegativeI);
  1682.     }

  1683.     /**
  1684.      * Returns the
  1685.      * <a href="http://mathworld.wolfram.com/InverseSine.html">
  1686.      * inverse sine</a> of this complex number.
  1687.      *
  1688.      * <p>\[ \sin^{-1}(z) = - i \left(\ln{iz + \sqrt{1 - z^2}}\right) \]
  1689.      *
  1690.      * <p>The inverse sine of \( z \) is unbounded along the imaginary axis and
  1691.      * in the range \( [-\pi, \pi] \) along the real axis. Special cases are handled
  1692.      * as if the operation is implemented using \( \sin^{-1}(z) = -i \sinh^{-1}(iz) \).
  1693.      *
  1694.      * <p>The inverse sine is a multivalued function and requires a branch cut in
  1695.      * the complex plane; the cut is conventionally placed at the line segments
  1696.      * \( (\infty,-1) \) and \( (1,\infty) \) of the real axis.
  1697.      *
  1698.      * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
  1699.      *
  1700.      * <p>\[ \begin{aligned}
  1701.      *   \sin^{-1}(z) &amp;= \sin^{-1}(B) + i\ \text{sgn}(y)\ln \left(A + \sqrt{A^2-1} \right) \\
  1702.      *   A &amp;= \frac{1}{2} \left[ \sqrt{(x+1)^2+y^2} + \sqrt{(x-1)^2+y^2} \right] \\
  1703.      *   B &amp;= \frac{1}{2} \left[ \sqrt{(x+1)^2+y^2} - \sqrt{(x-1)^2+y^2} \right] \end{aligned} \]
  1704.      *
  1705.      * <p>where \( \text{sgn}(y) \) is the sign function implemented using
  1706.      * {@link Math#copySign(double,double) copySign(1.0, y)}.
  1707.      *
  1708.      * <p>The implementation is based on the method described in:</p>
  1709.      * <blockquote>
  1710.      * T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang (1997)
  1711.      * Implementing the complex Arcsine and Arccosine Functions using Exception Handling.
  1712.      * ACM Transactions on Mathematical Software, Vol 23, No 3, pp 299-335.
  1713.      * </blockquote>
  1714.      *
  1715.      * <p>The code has been adapted from the <a href="https://www.boost.org/">Boost</a>
  1716.      * {@code c++} implementation {@code <boost/math/complex/asin.hpp>}.
  1717.      *
  1718.      * @return The inverse sine of this complex number.
  1719.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcSin/">ArcSin</a>
  1720.      */
  1721.     public Complex asin() {
  1722.         return asin(real, imaginary, Complex::ofCartesian);
  1723.     }

  1724.     /**
  1725.      * Returns the inverse sine of the complex number.
  1726.      *
  1727.      * <p>This function exists to allow implementation of the identity
  1728.      * {@code asinh(z) = -i asin(iz)}.
  1729.      *
  1730.      * <p>Adapted from {@code <boost/math/complex/asin.hpp>}. This method only (and not
  1731.      * invoked methods within) is distributed under the Boost Software License V1.0.
  1732.      * The original notice is shown below and the licence is shown in full in LICENSE:
  1733.      * <pre>
  1734.      * (C) Copyright John Maddock 2005.
  1735.      * Distributed under the Boost Software License, Version 1.0. (See accompanying
  1736.      * file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
  1737.      * </pre>
  1738.      *
  1739.      * @param real Real part.
  1740.      * @param imaginary Imaginary part.
  1741.      * @param constructor Constructor.
  1742.      * @return The inverse sine of this complex number.
  1743.      */
  1744.     private static Complex asin(final double real, final double imaginary,
  1745.                                 final ComplexConstructor constructor) {
  1746.         // Compute with positive values and determine sign at the end
  1747.         final double x = Math.abs(real);
  1748.         final double y = Math.abs(imaginary);
  1749.         // The result (without sign correction)
  1750.         final double re;
  1751.         final double im;

  1752.         // Handle C99 special cases
  1753.         if (Double.isNaN(x)) {
  1754.             if (isPosInfinite(y)) {
  1755.                 re = x;
  1756.                 im = y;
  1757.             } else {
  1758.                 // No-use of the input constructor
  1759.                 return NAN;
  1760.             }
  1761.         } else if (Double.isNaN(y)) {
  1762.             if (x == 0) {
  1763.                 re = 0;
  1764.                 im = y;
  1765.             } else if (isPosInfinite(x)) {
  1766.                 re = y;
  1767.                 im = x;
  1768.             } else {
  1769.                 // No-use of the input constructor
  1770.                 return NAN;
  1771.             }
  1772.         } else if (isPosInfinite(x)) {
  1773.             re = isPosInfinite(y) ? PI_OVER_4 : PI_OVER_2;
  1774.             im = x;
  1775.         } else if (isPosInfinite(y)) {
  1776.             re = 0;
  1777.             im = y;
  1778.         } else {
  1779.             // Special case for real numbers:
  1780.             if (y == 0 && x <= 1) {
  1781.                 return constructor.create(Math.asin(real), imaginary);
  1782.             }

  1783.             final double xp1 = x + 1;
  1784.             final double xm1 = x - 1;

  1785.             if (inRegion(x, y, SAFE_MIN, SAFE_MAX)) {
  1786.                 final double yy = y * y;
  1787.                 final double r = Math.sqrt(xp1 * xp1 + yy);
  1788.                 final double s = Math.sqrt(xm1 * xm1 + yy);
  1789.                 final double a = 0.5 * (r + s);
  1790.                 final double b = x / a;

  1791.                 if (b <= B_CROSSOVER) {
  1792.                     re = Math.asin(b);
  1793.                 } else {
  1794.                     final double apx = a + x;
  1795.                     if (x <= 1) {
  1796.                         re = Math.atan(x / Math.sqrt(0.5 * apx * (yy / (r + xp1) + (s - xm1))));
  1797.                     } else {
  1798.                         re = Math.atan(x / (y * Math.sqrt(0.5 * (apx / (r + xp1) + apx / (s + xm1)))));
  1799.                     }
  1800.                 }

  1801.                 if (a <= A_CROSSOVER) {
  1802.                     final double am1;
  1803.                     if (x < 1) {
  1804.                         am1 = 0.5 * (yy / (r + xp1) + yy / (s - xm1));
  1805.                     } else {
  1806.                         am1 = 0.5 * (yy / (r + xp1) + (s + xm1));
  1807.                     }
  1808.                     im = Math.log1p(am1 + Math.sqrt(am1 * (a + 1)));
  1809.                 } else {
  1810.                     im = Math.log(a + Math.sqrt(a * a - 1));
  1811.                 }
  1812.             } else {
  1813.                 // Hull et al: Exception handling code from figure 4
  1814.                 if (y <= (EPSILON * Math.abs(xm1))) {
  1815.                     if (x < 1) {
  1816.                         re = Math.asin(x);
  1817.                         im = y / Math.sqrt(xp1 * (1 - x));
  1818.                     } else {
  1819.                         re = PI_OVER_2;
  1820.                         if ((Double.MAX_VALUE / xp1) > xm1) {
  1821.                             // xp1 * xm1 won't overflow:
  1822.                             im = Math.log1p(xm1 + Math.sqrt(xp1 * xm1));
  1823.                         } else {
  1824.                             im = LN_2 + Math.log(x);
  1825.                         }
  1826.                     }
  1827.                 } else if (y <= SAFE_MIN) {
  1828.                     // Hull et al: Assume x == 1.
  1829.                     // True if:
  1830.                     // E^2 > 8*sqrt(u)
  1831.                     //
  1832.                     // E = Machine epsilon: (1 + epsilon) = 1
  1833.                     // u = Double.MIN_NORMAL
  1834.                     re = PI_OVER_2 - Math.sqrt(y);
  1835.                     im = Math.sqrt(y);
  1836.                 } else if (EPSILON * y - 1 >= x) {
  1837.                     // Possible underflow:
  1838.                     re = x / y;
  1839.                     im = LN_2 + Math.log(y);
  1840.                 } else if (x > 1) {
  1841.                     re = Math.atan(x / y);
  1842.                     final double xoy = x / y;
  1843.                     im = LN_2 + Math.log(y) + 0.5 * Math.log1p(xoy * xoy);
  1844.                 } else {
  1845.                     final double a = Math.sqrt(1 + y * y);
  1846.                     // Possible underflow:
  1847.                     re = x / a;
  1848.                     im = 0.5 * Math.log1p(2 * y * (y + a));
  1849.                 }
  1850.             }
  1851.         }

  1852.         return constructor.create(changeSign(re, real),
  1853.                                   changeSign(im, imaginary));
  1854.     }

  1855.     /**
  1856.      * Returns the
  1857.      * <a href="http://mathworld.wolfram.com/InverseCosine.html">
  1858.      * inverse cosine</a> of this complex number.
  1859.      *
  1860.      * <p>\[ \cos^{-1}(z) = \frac{\pi}{2} + i \left(\ln{iz + \sqrt{1 - z^2}}\right) \]
  1861.      *
  1862.      * <p>The inverse cosine of \( z \) is in the range \( [0, \pi) \) along the real axis and
  1863.      * unbounded along the imaginary axis. Special cases:
  1864.      *
  1865.      * <ul>
  1866.      * <li>{@code z.conj().acos() == z.acos().conj()}.
  1867.      * <li>If {@code z} is ±0 + i0, returns π/2 − i0.
  1868.      * <li>If {@code z} is ±0 + iNaN, returns π/2 + iNaN.
  1869.      * <li>If {@code z} is x + i∞ for finite x, returns π/2 − i∞.
  1870.      * <li>If {@code z} is x + iNaN, returns NaN + iNaN ("invalid" floating-point operation).
  1871.      * <li>If {@code z} is −∞ + iy for positive-signed finite y, returns π − i∞.
  1872.      * <li>If {@code z} is +∞ + iy for positive-signed finite y, returns +0 − i∞.
  1873.      * <li>If {@code z} is −∞ + i∞, returns 3π/4 − i∞.
  1874.      * <li>If {@code z} is +∞ + i∞, returns π/4 − i∞.
  1875.      * <li>If {@code z} is ±∞ + iNaN, returns NaN ± i∞ where the sign of the imaginary part of the result is unspecified.
  1876.      * <li>If {@code z} is NaN + iy for finite y, returns NaN + iNaN ("invalid" floating-point operation).
  1877.      * <li>If {@code z} is NaN + i∞, returns NaN − i∞.
  1878.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  1879.      * </ul>
  1880.      *
  1881.      * <p>The inverse cosine is a multivalued function and requires a branch cut in
  1882.      * the complex plane; the cut is conventionally placed at the line segments
  1883.      * \( (-\infty,-1) \) and \( (1,\infty) \) of the real axis.
  1884.      *
  1885.      * <p>This function is implemented using real \( x \) and imaginary \( y \) parts:
  1886.      *
  1887.      * <p>\[ \begin{aligned}
  1888.      *   \cos^{-1}(z) &amp;= \cos^{-1}(B) - i\ \text{sgn}(y) \ln\left(A + \sqrt{A^2-1}\right) \\
  1889.      *   A &amp;= \frac{1}{2} \left[ \sqrt{(x+1)^2+y^2} + \sqrt{(x-1)^2+y^2} \right] \\
  1890.      *   B &amp;= \frac{1}{2} \left[ \sqrt{(x+1)^2+y^2} - \sqrt{(x-1)^2+y^2} \right] \end{aligned} \]
  1891.      *
  1892.      * <p>where \( \text{sgn}(y) \) is the sign function implemented using
  1893.      * {@link Math#copySign(double,double) copySign(1.0, y)}.
  1894.      *
  1895.      * <p>The implementation is based on the method described in:</p>
  1896.      * <blockquote>
  1897.      * T E Hull, Thomas F Fairgrieve and Ping Tak Peter Tang (1997)
  1898.      * Implementing the complex Arcsine and Arccosine Functions using Exception Handling.
  1899.      * ACM Transactions on Mathematical Software, Vol 23, No 3, pp 299-335.
  1900.      * </blockquote>
  1901.      *
  1902.      * <p>The code has been adapted from the <a href="https://www.boost.org/">Boost</a>
  1903.      * {@code c++} implementation {@code <boost/math/complex/acos.hpp>}.
  1904.      *
  1905.      * @return The inverse cosine of this complex number.
  1906.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcCos/">ArcCos</a>
  1907.      */
  1908.     public Complex acos() {
  1909.         return acos(real, imaginary, Complex::ofCartesian);
  1910.     }

  1911.     /**
  1912.      * Returns the inverse cosine of the complex number.
  1913.      *
  1914.      * <p>This function exists to allow implementation of the identity
  1915.      * {@code acosh(z) = +-i acos(z)}.
  1916.      *
  1917.      * <p>Adapted from {@code <boost/math/complex/acos.hpp>}. This method only (and not
  1918.      * invoked methods within) is distributed under the Boost Software License V1.0.
  1919.      * The original notice is shown below and the licence is shown in full in LICENSE:
  1920.      * <pre>
  1921.      * (C) Copyright John Maddock 2005.
  1922.      * Distributed under the Boost Software License, Version 1.0. (See accompanying
  1923.      * file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
  1924.      * </pre>
  1925.      *
  1926.      * @param real Real part.
  1927.      * @param imaginary Imaginary part.
  1928.      * @param constructor Constructor.
  1929.      * @return The inverse cosine of the complex number.
  1930.      */
  1931.     private static Complex acos(final double real, final double imaginary,
  1932.                                 final ComplexConstructor constructor) {
  1933.         // Compute with positive values and determine sign at the end
  1934.         final double x = Math.abs(real);
  1935.         final double y = Math.abs(imaginary);
  1936.         // The result (without sign correction)
  1937.         final double re;
  1938.         final double im;

  1939.         // Handle C99 special cases
  1940.         if (isPosInfinite(x)) {
  1941.             if (isPosInfinite(y)) {
  1942.                 re = PI_OVER_4;
  1943.                 im = y;
  1944.             } else if (Double.isNaN(y)) {
  1945.                 // sign of the imaginary part of the result is unspecified
  1946.                 return constructor.create(imaginary, real);
  1947.             } else {
  1948.                 re = 0;
  1949.                 im = Double.POSITIVE_INFINITY;
  1950.             }
  1951.         } else if (Double.isNaN(x)) {
  1952.             if (isPosInfinite(y)) {
  1953.                 return constructor.create(x, -imaginary);
  1954.             }
  1955.             // No-use of the input constructor
  1956.             return NAN;
  1957.         } else if (isPosInfinite(y)) {
  1958.             re = PI_OVER_2;
  1959.             im = y;
  1960.         } else if (Double.isNaN(y)) {
  1961.             return constructor.create(x == 0 ? PI_OVER_2 : y, y);
  1962.         } else {
  1963.             // Special case for real numbers:
  1964.             if (y == 0 && x <= 1) {
  1965.                 return constructor.create(x == 0 ? PI_OVER_2 : Math.acos(real), -imaginary);
  1966.             }

  1967.             final double xp1 = x + 1;
  1968.             final double xm1 = x - 1;

  1969.             if (inRegion(x, y, SAFE_MIN, SAFE_MAX)) {
  1970.                 final double yy = y * y;
  1971.                 final double r = Math.sqrt(xp1 * xp1 + yy);
  1972.                 final double s = Math.sqrt(xm1 * xm1 + yy);
  1973.                 final double a = 0.5 * (r + s);
  1974.                 final double b = x / a;

  1975.                 if (b <= B_CROSSOVER) {
  1976.                     re = Math.acos(b);
  1977.                 } else {
  1978.                     final double apx = a + x;
  1979.                     if (x <= 1) {
  1980.                         re = Math.atan(Math.sqrt(0.5 * apx * (yy / (r + xp1) + (s - xm1))) / x);
  1981.                     } else {
  1982.                         re = Math.atan((y * Math.sqrt(0.5 * (apx / (r + xp1) + apx / (s + xm1)))) / x);
  1983.                     }
  1984.                 }

  1985.                 if (a <= A_CROSSOVER) {
  1986.                     final double am1;
  1987.                     if (x < 1) {
  1988.                         am1 = 0.5 * (yy / (r + xp1) + yy / (s - xm1));
  1989.                     } else {
  1990.                         am1 = 0.5 * (yy / (r + xp1) + (s + xm1));
  1991.                     }
  1992.                     im = Math.log1p(am1 + Math.sqrt(am1 * (a + 1)));
  1993.                 } else {
  1994.                     im = Math.log(a + Math.sqrt(a * a - 1));
  1995.                 }
  1996.             } else {
  1997.                 // Hull et al: Exception handling code from figure 6
  1998.                 if (y <= (EPSILON * Math.abs(xm1))) {
  1999.                     if (x < 1) {
  2000.                         re = Math.acos(x);
  2001.                         im = y / Math.sqrt(xp1 * (1 - x));
  2002.                     } else {
  2003.                         // This deviates from Hull et al's paper as per
  2004.                         // https://svn.boost.org/trac/boost/ticket/7290
  2005.                         if ((Double.MAX_VALUE / xp1) > xm1) {
  2006.                             // xp1 * xm1 won't overflow:
  2007.                             re = y / Math.sqrt(xm1 * xp1);
  2008.                             im = Math.log1p(xm1 + Math.sqrt(xp1 * xm1));
  2009.                         } else {
  2010.                             re = y / x;
  2011.                             im = LN_2 + Math.log(x);
  2012.                         }
  2013.                     }
  2014.                 } else if (y <= SAFE_MIN) {
  2015.                     // Hull et al: Assume x == 1.
  2016.                     // True if:
  2017.                     // E^2 > 8*sqrt(u)
  2018.                     //
  2019.                     // E = Machine epsilon: (1 + epsilon) = 1
  2020.                     // u = Double.MIN_NORMAL
  2021.                     re = Math.sqrt(y);
  2022.                     im = Math.sqrt(y);
  2023.                 } else if (EPSILON * y - 1 >= x) {
  2024.                     re = PI_OVER_2;
  2025.                     im = LN_2 + Math.log(y);
  2026.                 } else if (x > 1) {
  2027.                     re = Math.atan(y / x);
  2028.                     final double xoy = x / y;
  2029.                     im = LN_2 + Math.log(y) + 0.5 * Math.log1p(xoy * xoy);
  2030.                 } else {
  2031.                     re = PI_OVER_2;
  2032.                     final double a = Math.sqrt(1 + y * y);
  2033.                     im = 0.5 * Math.log1p(2 * y * (y + a));
  2034.                 }
  2035.             }
  2036.         }

  2037.         return constructor.create(negative(real) ? Math.PI - re : re,
  2038.                                   negative(imaginary) ? im : -im);
  2039.     }

  2040.     /**
  2041.      * Returns the
  2042.      * <a href="http://mathworld.wolfram.com/InverseTangent.html">
  2043.      * inverse tangent</a> of this complex number.
  2044.      *
  2045.      * <p>\[ \tan^{-1}(z) = \frac{i}{2} \ln \left( \frac{i + z}{i - z} \right) \]
  2046.      *
  2047.      * <p>The inverse hyperbolic tangent of \( z \) is unbounded along the imaginary axis and
  2048.      * in the range \( [-\pi/2, \pi/2] \) along the real axis.
  2049.      *
  2050.      * <p>The inverse tangent is a multivalued function and requires a branch cut in
  2051.      * the complex plane; the cut is conventionally placed at the line segments
  2052.      * \( (i \infty,-i] \) and \( [i,i \infty) \) of the imaginary axis.
  2053.      *
  2054.      * <p>As per the C99 standard this function is computed using the trigonomic identity:
  2055.      * \[ \tan^{-1}(z) = -i \tanh^{-1}(iz) \]
  2056.      *
  2057.      * @return The inverse tangent of this complex number.
  2058.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcTan/">ArcTan</a>
  2059.      */
  2060.     public Complex atan() {
  2061.         // Define in terms of atanh
  2062.         // atan(z) = -i atanh(iz)
  2063.         // Multiply this number by I, compute atanh, then multiply by back
  2064.         return atanh(-imaginary, real, Complex::multiplyNegativeI);
  2065.     }

  2066.     /**
  2067.      * Returns the
  2068.      * <a href="http://mathworld.wolfram.com/HyperbolicSine.html">
  2069.      * hyperbolic sine</a> of this complex number.
  2070.      *
  2071.      * <p>\[ \sinh(z) = \frac{1}{2} \left( e^{z} - e^{-z} \right) \]
  2072.      *
  2073.      * <p>The hyperbolic sine of \( z \) is an entire function in the complex plane
  2074.      * and is periodic with respect to the imaginary component with period \( 2\pi i \).
  2075.      * Special cases:
  2076.      *
  2077.      * <ul>
  2078.      * <li>{@code z.conj().sinh() == z.sinh().conj()}.
  2079.      * <li>This is an odd function: \( \sinh(z) = -\sinh(-z) \).
  2080.      * <li>If {@code z} is +0 + i0, returns +0 + i0.
  2081.      * <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).
  2082.      * <li>If {@code z} is +0 + iNaN, returns ±0 + iNaN (where the sign of the real part of the result is unspecified).
  2083.      * <li>If {@code z} is x + i∞ for positive finite x, returns NaN + iNaN ("invalid" floating-point operation).
  2084.      * <li>If {@code z} is x + iNaN for finite nonzero x, returns NaN + iNaN ("invalid" floating-point operation).
  2085.      * <li>If {@code z} is +∞ + i0, returns +∞ + i0.
  2086.      * <li>If {@code z} is +∞ + iy for positive finite y, returns +∞ cis(y) (see {@link #ofCis(double)}.
  2087.      * <li>If {@code z} is +∞ + i∞, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified; "invalid" floating-point operation).
  2088.      * <li>If {@code z} is +∞ + iNaN, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified).
  2089.      * <li>If {@code z} is NaN + i0, returns NaN + i0.
  2090.      * <li>If {@code z} is NaN + iy for all nonzero numbers y, returns NaN + iNaN ("invalid" floating-point operation).
  2091.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  2092.      * </ul>
  2093.      *
  2094.      * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
  2095.      *
  2096.      * <p>\[ \sinh(x + iy) = \sinh(x)\cos(y) + i \cosh(x)\sin(y) \]
  2097.      *
  2098.      * @return The hyperbolic sine of this complex number.
  2099.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Sinh/">Sinh</a>
  2100.      */
  2101.     public Complex sinh() {
  2102.         return sinh(real, imaginary, Complex::ofCartesian);
  2103.     }

  2104.     /**
  2105.      * Returns the hyperbolic sine of the complex number.
  2106.      *
  2107.      * <p>This function exists to allow implementation of the identity
  2108.      * {@code sin(z) = -i sinh(iz)}.<p>
  2109.      *
  2110.      * @param real Real part.
  2111.      * @param imaginary Imaginary part.
  2112.      * @param constructor Constructor.
  2113.      * @return The hyperbolic sine of the complex number.
  2114.      */
  2115.     private static Complex sinh(double real, double imaginary, ComplexConstructor constructor) {
  2116.         if (Double.isInfinite(real) && !Double.isFinite(imaginary)) {
  2117.             return constructor.create(real, Double.NaN);
  2118.         }
  2119.         if (real == 0) {
  2120.             // Imaginary-only sinh(iy) = i sin(y).
  2121.             if (Double.isFinite(imaginary)) {
  2122.                 // Maintain periodic property with respect to the imaginary component.
  2123.                 // sinh(+/-0.0) * cos(+/-x) = +/-0 * cos(x)
  2124.                 return constructor.create(changeSign(real, Math.cos(imaginary)),
  2125.                                           Math.sin(imaginary));
  2126.             }
  2127.             // If imaginary is inf/NaN the sign of the real part is unspecified.
  2128.             // Returning the same real value maintains the conjugate equality.
  2129.             // It is not possible to also maintain the odd function (hence the unspecified sign).
  2130.             return constructor.create(real, Double.NaN);
  2131.         }
  2132.         if (imaginary == 0) {
  2133.             // Real-only sinh(x).
  2134.             return constructor.create(Math.sinh(real), imaginary);
  2135.         }
  2136.         final double x = Math.abs(real);
  2137.         if (x > SAFE_EXP) {
  2138.             // Approximate sinh/cosh(x) using exp^|x| / 2
  2139.             return coshsinh(x, real, imaginary, true, constructor);
  2140.         }
  2141.         // No overflow of sinh/cosh
  2142.         return constructor.create(Math.sinh(real) * Math.cos(imaginary),
  2143.                                   Math.cosh(real) * Math.sin(imaginary));
  2144.     }

  2145.     /**
  2146.      * Returns the
  2147.      * <a href="http://mathworld.wolfram.com/HyperbolicCosine.html">
  2148.      * hyperbolic cosine</a> of this complex number.
  2149.      *
  2150.      * <p>\[ \cosh(z) = \frac{1}{2} \left( e^{z} + e^{-z} \right) \]
  2151.      *
  2152.      * <p>The hyperbolic cosine of \( z \) is an entire function in the complex plane
  2153.      * and is periodic with respect to the imaginary component with period \( 2\pi i \).
  2154.      * Special cases:
  2155.      *
  2156.      * <ul>
  2157.      * <li>{@code z.conj().cosh() == z.cosh().conj()}.
  2158.      * <li>This is an even function: \( \cosh(z) = \cosh(-z) \).
  2159.      * <li>If {@code z} is +0 + i0, returns 1 + i0.
  2160.      * <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).
  2161.      * <li>If {@code z} is +0 + iNaN, returns NaN ± i0 (where the sign of the imaginary part of the result is unspecified).
  2162.      * <li>If {@code z} is x + i∞ for finite nonzero x, returns NaN + iNaN ("invalid" floating-point operation).
  2163.      * <li>If {@code z} is x + iNaN for finite nonzero x, returns NaN + iNaN ("invalid" floating-point operation).
  2164.      * <li>If {@code z} is +∞ + i0, returns +∞ + i0.
  2165.      * <li>If {@code z} is +∞ + iy for finite nonzero y, returns +∞ cis(y) (see {@link #ofCis(double)}).
  2166.      * <li>If {@code z} is +∞ + i∞, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified).
  2167.      * <li>If {@code z} is +∞ + iNaN, returns +∞ + iNaN.
  2168.      * <li>If {@code z} is NaN + i0, returns NaN ± i0 (where the sign of the imaginary part of the result is unspecified).
  2169.      * <li>If {@code z} is NaN + iy for all nonzero numbers y, returns NaN + iNaN ("invalid" floating-point operation).
  2170.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  2171.      * </ul>
  2172.      *
  2173.      * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
  2174.      *
  2175.      * <p>\[ \cosh(x + iy) = \cosh(x)\cos(y) + i \sinh(x)\sin(y) \]
  2176.      *
  2177.      * @return The hyperbolic cosine of this complex number.
  2178.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Cosh/">Cosh</a>
  2179.      */
  2180.     public Complex cosh() {
  2181.         return cosh(real, imaginary, Complex::ofCartesian);
  2182.     }

  2183.     /**
  2184.      * Returns the hyperbolic cosine of the complex number.
  2185.      *
  2186.      * <p>This function exists to allow implementation of the identity
  2187.      * {@code cos(z) = cosh(iz)}.<p>
  2188.      *
  2189.      * @param real Real part.
  2190.      * @param imaginary Imaginary part.
  2191.      * @param constructor Constructor.
  2192.      * @return The hyperbolic cosine of the complex number.
  2193.      */
  2194.     private static Complex cosh(double real, double imaginary, ComplexConstructor constructor) {
  2195.         // ISO C99: Preserve the even function by mapping to positive
  2196.         // f(z) = f(-z)
  2197.         if (Double.isInfinite(real) && !Double.isFinite(imaginary)) {
  2198.             return constructor.create(Math.abs(real), Double.NaN);
  2199.         }
  2200.         if (real == 0) {
  2201.             // Imaginary-only cosh(iy) = cos(y).
  2202.             if (Double.isFinite(imaginary)) {
  2203.                 // Maintain periodic property with respect to the imaginary component.
  2204.                 // sinh(+/-0.0) * sin(+/-x) = +/-0 * sin(x)
  2205.                 return constructor.create(Math.cos(imaginary),
  2206.                                           changeSign(real, Math.sin(imaginary)));
  2207.             }
  2208.             // If imaginary is inf/NaN the sign of the imaginary part is unspecified.
  2209.             // Although not required by C99 changing the sign maintains the conjugate equality.
  2210.             // It is not possible to also maintain the even function (hence the unspecified sign).
  2211.             return constructor.create(Double.NaN, changeSign(real, imaginary));
  2212.         }
  2213.         if (imaginary == 0) {
  2214.             // Real-only cosh(x).
  2215.             // Change sign to preserve conjugate equality and even function.
  2216.             // sin(+/-0) * sinh(+/-x) = +/-0 * +/-a (sinh is monotonic and same sign)
  2217.             // => change the sign of imaginary using real. Handles special case of infinite real.
  2218.             // If real is NaN the sign of the imaginary part is unspecified.
  2219.             return constructor.create(Math.cosh(real), changeSign(imaginary, real));
  2220.         }
  2221.         final double x = Math.abs(real);
  2222.         if (x > SAFE_EXP) {
  2223.             // Approximate sinh/cosh(x) using exp^|x| / 2
  2224.             return coshsinh(x, real, imaginary, false, constructor);
  2225.         }
  2226.         // No overflow of sinh/cosh
  2227.         return constructor.create(Math.cosh(real) * Math.cos(imaginary),
  2228.                                   Math.sinh(real) * Math.sin(imaginary));
  2229.     }

  2230.     /**
  2231.      * Compute cosh or sinh when the absolute real component |x| is large. In this case
  2232.      * cosh(x) and sinh(x) can be approximated by exp(|x|) / 2:
  2233.      *
  2234.      * <pre>
  2235.      * cosh(x+iy) real = (e^|x| / 2) * cos(y)
  2236.      * cosh(x+iy) imag = (e^|x| / 2) * sin(y) * sign(x)
  2237.      * sinh(x+iy) real = (e^|x| / 2) * cos(y) * sign(x)
  2238.      * sinh(x+iy) imag = (e^|x| / 2) * sin(y)
  2239.      * </pre>
  2240.      *
  2241.      * @param x Absolute real component |x|.
  2242.      * @param real Real part (x).
  2243.      * @param imaginary Imaginary part (y).
  2244.      * @param sinh Set to true to compute sinh, otherwise cosh.
  2245.      * @param constructor Constructor.
  2246.      * @return The hyperbolic sine/cosine of the complex number.
  2247.      */
  2248.     private static Complex coshsinh(double x, double real, double imaginary, boolean sinh,
  2249.                                     ComplexConstructor constructor) {
  2250.         // Always require the cos and sin.
  2251.         double re = Math.cos(imaginary);
  2252.         double im = Math.sin(imaginary);
  2253.         // Compute the correct function
  2254.         if (sinh) {
  2255.             re = changeSign(re, real);
  2256.         } else {
  2257.             im = changeSign(im, real);
  2258.         }
  2259.         // Multiply by (e^|x| / 2).
  2260.         // Overflow safe computation since sin/cos can be very small allowing a result
  2261.         // when e^x overflows: e^x / 2 = (e^m / 2) * e^m * e^(x-2m)
  2262.         if (x > SAFE_EXP * 3) {
  2263.             // e^x > e^m * e^m * e^m
  2264.             // y * (e^m / 2) * e^m * e^m will overflow when starting with Double.MIN_VALUE.
  2265.             // Note: Do not multiply by +inf to safeguard against sin(y)=0.0 which
  2266.             // will create 0 * inf = nan.
  2267.             re *= Double.MAX_VALUE * Double.MAX_VALUE * Double.MAX_VALUE;
  2268.             im *= Double.MAX_VALUE * Double.MAX_VALUE * Double.MAX_VALUE;
  2269.         } else {
  2270.             // Initial part of (e^x / 2) using (e^m / 2)
  2271.             re *= EXP_M / 2;
  2272.             im *= EXP_M / 2;
  2273.             final double xm;
  2274.             if (x > SAFE_EXP * 2) {
  2275.                 // e^x = e^m * e^m * e^(x-2m)
  2276.                 re *= EXP_M;
  2277.                 im *= EXP_M;
  2278.                 xm = x - SAFE_EXP * 2;
  2279.             } else {
  2280.                 // e^x = e^m * e^(x-m)
  2281.                 xm = x - SAFE_EXP;
  2282.             }
  2283.             final double exp = Math.exp(xm);
  2284.             re *= exp;
  2285.             im *= exp;
  2286.         }
  2287.         return constructor.create(re, im);
  2288.     }

  2289.     /**
  2290.      * Returns the
  2291.      * <a href="http://mathworld.wolfram.com/HyperbolicTangent.html">
  2292.      * hyperbolic tangent</a> of this complex number.
  2293.      *
  2294.      * <p>\[ \tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}} \]
  2295.      *
  2296.      * <p>The hyperbolic tangent of \( z \) is an entire function in the complex plane
  2297.      * and is periodic with respect to the imaginary component with period \( \pi i \)
  2298.      * and has poles of the first order along the imaginary line, at coordinates
  2299.      * \( (0, \pi(\frac{1}{2} + n)) \).
  2300.      * Note that the {@code double} floating-point representation is unable to exactly represent
  2301.      * \( \pi/2 \) and there is no value for which a pole error occurs. Special cases:
  2302.      *
  2303.      * <ul>
  2304.      * <li>{@code z.conj().tanh() == z.tanh().conj()}.
  2305.      * <li>This is an odd function: \( \tanh(z) = -\tanh(-z) \).
  2306.      * <li>If {@code z} is +0 + i0, returns +0 + i0.
  2307.      * <li>If {@code z} is 0 + i∞, returns 0 + iNaN.
  2308.      * <li>If {@code z} is x + i∞ for finite non-zero x, returns NaN + iNaN ("invalid" floating-point operation).
  2309.      * <li>If {@code z} is 0 + iNaN, returns 0 + iNAN.
  2310.      * <li>If {@code z} is x + iNaN for finite non-zero x, returns NaN + iNaN ("invalid" floating-point operation).
  2311.      * <li>If {@code z} is +∞ + iy for positive-signed finite y, returns 1 + i0 sin(2y).
  2312.      * <li>If {@code z} is +∞ + i∞, returns 1 ± i0 (where the sign of the imaginary part of the result is unspecified).
  2313.      * <li>If {@code z} is +∞ + iNaN, returns 1 ± i0 (where the sign of the imaginary part of the result is unspecified).
  2314.      * <li>If {@code z} is NaN + i0, returns NaN + i0.
  2315.      * <li>If {@code z} is NaN + iy for all nonzero numbers y, returns NaN + iNaN ("invalid" floating-point operation).
  2316.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  2317.      * </ul>
  2318.      *
  2319.      * <p>Special cases include the technical corrigendum
  2320.      * <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471">
  2321.      * DR 471: Complex math functions cacosh and ctanh</a>.
  2322.      *
  2323.      * <p>This is defined using real \( x \) and imaginary \( y \) parts:
  2324.      *
  2325.      * <p>\[ \tan(x + iy) = \frac{\sinh(2x)}{\cosh(2x)+\cos(2y)} + i \frac{\sin(2y)}{\cosh(2x)+\cos(2y)} \]
  2326.      *
  2327.      * <p>The implementation uses double-angle identities to avoid overflow of {@code 2x}
  2328.      * and {@code 2y}.
  2329.      *
  2330.      * @return The hyperbolic tangent of this complex number.
  2331.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Tanh/">Tanh</a>
  2332.      */
  2333.     public Complex tanh() {
  2334.         return tanh(real, imaginary, Complex::ofCartesian);
  2335.     }

  2336.     /**
  2337.      * Returns the hyperbolic tangent of this complex number.
  2338.      *
  2339.      * <p>This function exists to allow implementation of the identity
  2340.      * {@code tan(z) = -i tanh(iz)}.<p>
  2341.      *
  2342.      * @param real Real part.
  2343.      * @param imaginary Imaginary part.
  2344.      * @param constructor Constructor.
  2345.      * @return The hyperbolic tangent of the complex number.
  2346.      */
  2347.     private static Complex tanh(double real, double imaginary, ComplexConstructor constructor) {
  2348.         // Cache the absolute real value
  2349.         final double x = Math.abs(real);

  2350.         // Handle inf or nan.
  2351.         if (!isPosFinite(x) || !Double.isFinite(imaginary)) {
  2352.             if (isPosInfinite(x)) {
  2353.                 if (Double.isFinite(imaginary)) {
  2354.                     // The sign is copied from sin(2y)
  2355.                     // The identity sin(2a) = 2 sin(a) cos(a) is used for consistency
  2356.                     // with the computation below. Only the magnitude is important
  2357.                     // so drop the 2. When |y| is small sign(sin(2y)) = sign(y).
  2358.                     final double sign = Math.abs(imaginary) < PI_OVER_2 ?
  2359.                                         imaginary :
  2360.                                         Math.sin(imaginary) * Math.cos(imaginary);
  2361.                     return constructor.create(Math.copySign(1, real),
  2362.                                               Math.copySign(0, sign));
  2363.                 }
  2364.                 // imaginary is infinite or NaN
  2365.                 return constructor.create(Math.copySign(1, real), Math.copySign(0, imaginary));
  2366.             }
  2367.             // Remaining cases:
  2368.             // (0 + i inf), returns (0 + i NaN)
  2369.             // (0 + i NaN), returns (0 + i NaN)
  2370.             // (x + i inf), returns (NaN + i NaN) for non-zero x (including infinite)
  2371.             // (x + i NaN), returns (NaN + i NaN) for non-zero x (including infinite)
  2372.             // (NaN + i 0), returns (NaN + i 0)
  2373.             // (NaN + i y), returns (NaN + i NaN) for non-zero y (including infinite)
  2374.             // (NaN + i NaN), returns (NaN + i NaN)
  2375.             return constructor.create(real == 0 ? real : Double.NaN,
  2376.                                       imaginary == 0 ? imaginary : Double.NaN);
  2377.         }

  2378.         // Finite components
  2379.         // tanh(x+iy) = (sinh(2x) + i sin(2y)) / (cosh(2x) + cos(2y))

  2380.         if (real == 0) {
  2381.             // Imaginary-only tanh(iy) = i tan(y)
  2382.             // Identity: sin 2y / (1 + cos 2y) = tan(y)
  2383.             return constructor.create(real, Math.tan(imaginary));
  2384.         }
  2385.         if (imaginary == 0) {
  2386.             // Identity: sinh 2x / (1 + cosh 2x) = tanh(x)
  2387.             return constructor.create(Math.tanh(real), imaginary);
  2388.         }

  2389.         // The double angles can be avoided using the identities:
  2390.         // sinh(2x) = 2 sinh(x) cosh(x)
  2391.         // sin(2y) = 2 sin(y) cos(y)
  2392.         // cosh(2x) = 2 sinh^2(x) + 1
  2393.         // cos(2y) = 2 cos^2(y) - 1
  2394.         // tanh(x+iy) = (sinh(x)cosh(x) + i sin(y)cos(y)) / (sinh^2(x) + cos^2(y))
  2395.         // To avoid a junction when swapping between the double angles and the identities
  2396.         // the identities are used in all cases.

  2397.         if (x > SAFE_EXP / 2) {
  2398.             // Potential overflow in sinh/cosh(2x).
  2399.             // Approximate sinh/cosh using exp^x.
  2400.             // Ignore cos^2(y) in the divisor as it is insignificant.
  2401.             // real = sinh(x)cosh(x) / sinh^2(x) = +/-1
  2402.             final double re = Math.copySign(1, real);
  2403.             // imag = sin(2y) / 2 sinh^2(x)
  2404.             // sinh(x) -> sign(x) * e^|x| / 2 when x is large.
  2405.             // sinh^2(x) -> e^2|x| / 4 when x is large.
  2406.             // imag = sin(2y) / 2 (e^2|x| / 4) = 2 sin(2y) / e^2|x|
  2407.             //      = 4 * sin(y) cos(y) / e^2|x|
  2408.             // Underflow safe divide as e^2|x| may overflow:
  2409.             // imag = 4 * sin(y) cos(y) / e^m / e^(2|x| - m)
  2410.             // (|im| is a maximum of 2)
  2411.             double im = Math.sin(imaginary) * Math.cos(imaginary);
  2412.             if (x > SAFE_EXP) {
  2413.                 // e^2|x| > e^m * e^m
  2414.                 // This will underflow 2.0 / e^m / e^m
  2415.                 im = Math.copySign(0.0, im);
  2416.             } else {
  2417.                 // e^2|x| = e^m * e^(2|x| - m)
  2418.                 im = 4 * im / EXP_M / Math.exp(2 * x - SAFE_EXP);
  2419.             }
  2420.             return constructor.create(re, im);
  2421.         }

  2422.         // No overflow of sinh(2x) and cosh(2x)

  2423.         // Note: This does not use the definitional formula but uses the identity:
  2424.         // tanh(x+iy) = (sinh(x)cosh(x) + i sin(y)cos(y)) / (sinh^2(x) + cos^2(y))

  2425.         final double sinhx = Math.sinh(real);
  2426.         final double coshx = Math.cosh(real);
  2427.         final double siny = Math.sin(imaginary);
  2428.         final double cosy = Math.cos(imaginary);
  2429.         final double divisor = sinhx * sinhx + cosy * cosy;
  2430.         return constructor.create(sinhx * coshx / divisor,
  2431.                                   siny * cosy / divisor);
  2432.     }

  2433.     /**
  2434.      * Returns the
  2435.      * <a href="http://mathworld.wolfram.com/InverseHyperbolicSine.html">
  2436.      * inverse hyperbolic sine</a> of this complex number.
  2437.      *
  2438.      * <p>\[ \sinh^{-1}(z) = \ln \left(z + \sqrt{1 + z^2} \right) \]
  2439.      *
  2440.      * <p>The inverse hyperbolic sine of \( z \) is unbounded along the real axis and
  2441.      * in the range \( [-\pi, \pi] \) along the imaginary axis. Special cases:
  2442.      *
  2443.      * <ul>
  2444.      * <li>{@code z.conj().asinh() == z.asinh().conj()}.
  2445.      * <li>This is an odd function: \( \sinh^{-1}(z) = -\sinh^{-1}(-z) \).
  2446.      * <li>If {@code z} is +0 + i0, returns 0 + i0.
  2447.      * <li>If {@code z} is x + i∞ for positive-signed finite x, returns +∞ + iπ/2.
  2448.      * <li>If {@code z} is x + iNaN for finite x, returns NaN + iNaN ("invalid" floating-point operation).
  2449.      * <li>If {@code z} is +∞ + iy for positive-signed finite y, returns +∞ + i0.
  2450.      * <li>If {@code z} is +∞ + i∞, returns +∞ + iπ/4.
  2451.      * <li>If {@code z} is +∞ + iNaN, returns +∞ + iNaN.
  2452.      * <li>If {@code z} is NaN + i0, returns NaN + i0.
  2453.      * <li>If {@code z} is NaN + iy for finite nonzero y, returns NaN + iNaN ("invalid" floating-point operation).
  2454.      * <li>If {@code z} is NaN + i∞, returns ±∞ + iNaN (where the sign of the real part of the result is unspecified).
  2455.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  2456.      * </ul>
  2457.      *
  2458.      * <p>The inverse hyperbolic sine is a multivalued function and requires a branch cut in
  2459.      * the complex plane; the cut is conventionally placed at the line segments
  2460.      * \( (-i \infty,-i) \) and \( (i,i \infty) \) of the imaginary axis.
  2461.      *
  2462.      * <p>This function is computed using the trigonomic identity:
  2463.      *
  2464.      * <p>\[ \sinh^{-1}(z) = -i \sin^{-1}(iz) \]
  2465.      *
  2466.      * @return The inverse hyperbolic sine of this complex number.
  2467.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcSinh/">ArcSinh</a>
  2468.      */
  2469.     public Complex asinh() {
  2470.         // Define in terms of asin
  2471.         // asinh(z) = -i asin(iz)
  2472.         // Note: This is the opposite to the identity defined in the C99 standard:
  2473.         // asin(z) = -i asinh(iz)
  2474.         // Multiply this number by I, compute asin, then multiply by back
  2475.         return asin(-imaginary, real, Complex::multiplyNegativeI);
  2476.     }

  2477.     /**
  2478.      * Returns the
  2479.      * <a href="http://mathworld.wolfram.com/InverseHyperbolicCosine.html">
  2480.      * inverse hyperbolic cosine</a> of this complex number.
  2481.      *
  2482.      * <p>\[ \cosh^{-1}(z) = \ln \left(z + \sqrt{z + 1} \sqrt{z - 1} \right) \]
  2483.      *
  2484.      * <p>The inverse hyperbolic cosine of \( z \) is in the range \( [0, \infty) \) along the
  2485.      * real axis and in the range \( [-\pi, \pi] \) along the imaginary axis. Special cases:
  2486.      *
  2487.      * <ul>
  2488.      * <li>{@code z.conj().acosh() == z.acosh().conj()}.
  2489.      * <li>If {@code z} is ±0 + i0, returns +0 + iπ/2.
  2490.      * <li>If {@code z} is x + i∞ for finite x, returns +∞ + iπ/2.
  2491.      * <li>If {@code z} is 0 + iNaN, returns NaN + iπ/2 <sup>[1]</sup>.
  2492.      * <li>If {@code z} is x + iNaN for finite non-zero x, returns NaN + iNaN ("invalid" floating-point operation).
  2493.      * <li>If {@code z} is −∞ + iy for positive-signed finite y, returns +∞ + iπ.
  2494.      * <li>If {@code z} is +∞ + iy for positive-signed finite y, returns +∞ + i0.
  2495.      * <li>If {@code z} is −∞ + i∞, returns +∞ + i3π/4.
  2496.      * <li>If {@code z} is +∞ + i∞, returns +∞ + iπ/4.
  2497.      * <li>If {@code z} is ±∞ + iNaN, returns +∞ + iNaN.
  2498.      * <li>If {@code z} is NaN + iy for finite y, returns NaN + iNaN ("invalid" floating-point operation).
  2499.      * <li>If {@code z} is NaN + i∞, returns +∞ + iNaN.
  2500.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  2501.      * </ul>
  2502.      *
  2503.      * <p>Special cases include the technical corrigendum
  2504.      * <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1892.htm#dr_471">
  2505.      * DR 471: Complex math functions cacosh and ctanh</a>.
  2506.      *
  2507.      * <p>The inverse hyperbolic cosine is a multivalued function and requires a branch cut in
  2508.      * the complex plane; the cut is conventionally placed at the line segment
  2509.      * \( (-\infty,-1) \) of the real axis.
  2510.      *
  2511.      * <p>This function is computed using the trigonomic identity:
  2512.      *
  2513.      * <p>\[ \cosh^{-1}(z) = \pm i \cos^{-1}(z) \]
  2514.      *
  2515.      * <p>The sign of the multiplier is chosen to give {@code z.acosh().real() >= 0}
  2516.      * and compatibility with the C99 standard.
  2517.      *
  2518.      * @return The inverse hyperbolic cosine of this complex number.
  2519.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcCosh/">ArcCosh</a>
  2520.      */
  2521.     public Complex acosh() {
  2522.         // Define in terms of acos
  2523.         // acosh(z) = +-i acos(z)
  2524.         // Note the special case:
  2525.         // acos(+-0 + iNaN) = π/2 + iNaN
  2526.         // acosh(0 + iNaN) = NaN + iπ/2
  2527.         // will not appropriately multiply by I to maintain positive imaginary if
  2528.         // acos() imaginary computes as NaN. So do this explicitly.
  2529.         if (Double.isNaN(imaginary) && real == 0) {
  2530.             return new Complex(Double.NaN, PI_OVER_2);
  2531.         }
  2532.         return acos(real, imaginary, (re, im) ->
  2533.             // Set the sign appropriately for real >= 0
  2534.             negative(im) ?
  2535.                 // Multiply by I
  2536.                 new Complex(-im, re) :
  2537.                 // Multiply by -I
  2538.                 new Complex(im, -re)
  2539.         );
  2540.     }

  2541.     /**
  2542.      * Returns the
  2543.      * <a href="http://mathworld.wolfram.com/InverseHyperbolicTangent.html">
  2544.      * inverse hyperbolic tangent</a> of this complex number.
  2545.      *
  2546.      * <p>\[ \tanh^{-1}(z) = \frac{1}{2} \ln \left( \frac{1 + z}{1 - z} \right) \]
  2547.      *
  2548.      * <p>The inverse hyperbolic tangent of \( z \) is unbounded along the real axis and
  2549.      * in the range \( [-\pi/2, \pi/2] \) along the imaginary axis. Special cases:
  2550.      *
  2551.      * <ul>
  2552.      * <li>{@code z.conj().atanh() == z.atanh().conj()}.
  2553.      * <li>This is an odd function: \( \tanh^{-1}(z) = -\tanh^{-1}(-z) \).
  2554.      * <li>If {@code z} is +0 + i0, returns +0 + i0.
  2555.      * <li>If {@code z} is +0 + iNaN, returns +0 + iNaN.
  2556.      * <li>If {@code z} is +1 + i0, returns +∞ + i0 ("divide-by-zero" floating-point operation).
  2557.      * <li>If {@code z} is x + i∞ for finite positive-signed x, returns +0 + iπ/2.
  2558.      * <li>If {@code z} is x+iNaN for nonzero finite x, returns NaN+iNaN ("invalid" floating-point operation).
  2559.      * <li>If {@code z} is +∞ + iy for finite positive-signed y, returns +0 + iπ/2.
  2560.      * <li>If {@code z} is +∞ + i∞, returns +0 + iπ/2.
  2561.      * <li>If {@code z} is +∞ + iNaN, returns +0 + iNaN.
  2562.      * <li>If {@code z} is NaN+iy for finite y, returns NaN+iNaN ("invalid" floating-point operation).
  2563.      * <li>If {@code z} is NaN + i∞, returns ±0 + iπ/2 (where the sign of the real part of the result is unspecified).
  2564.      * <li>If {@code z} is NaN + iNaN, returns NaN + iNaN.
  2565.      * </ul>
  2566.      *
  2567.      * <p>The inverse hyperbolic tangent is a multivalued function and requires a branch cut in
  2568.      * the complex plane; the cut is conventionally placed at the line segments
  2569.      * \( (\infty,-1] \) and \( [1,\infty) \) of the real axis.
  2570.      *
  2571.      * <p>This is implemented using real \( x \) and imaginary \( y \) parts:
  2572.      *
  2573.      * <p>\[ \tanh^{-1}(z) = \frac{1}{4} \ln \left(1 + \frac{4x}{(1-x)^2+y^2} \right) + \\
  2574.      *                     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) \]
  2575.      *
  2576.      * <p>The imaginary part is computed using {@link Math#atan2(double, double)} to ensure the
  2577.      * correct quadrant is returned from \( \tan^{-1} \left(\frac{2y}{1-x^2-y^2} \right) \).
  2578.      *
  2579.      * <p>The code has been adapted from the <a href="https://www.boost.org/">Boost</a>
  2580.      * {@code c++} implementation {@code <boost/math/complex/atanh.hpp>}.
  2581.      *
  2582.      * @return The inverse hyperbolic tangent of this complex number.
  2583.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/ArcTanh/">ArcTanh</a>
  2584.      */
  2585.     public Complex atanh() {
  2586.         return atanh(real, imaginary, Complex::ofCartesian);
  2587.     }

  2588.     /**
  2589.      * Returns the inverse hyperbolic tangent of this complex number.
  2590.      *
  2591.      * <p>This function exists to allow implementation of the identity
  2592.      * {@code atan(z) = -i atanh(iz)}.
  2593.      *
  2594.      * <p>Adapted from {@code <boost/math/complex/atanh.hpp>}. This method only (and not
  2595.      * invoked methods within) is distributed under the Boost Software License V1.0.
  2596.      * The original notice is shown below and the licence is shown in full in LICENSE:
  2597.      * <pre>
  2598.      * (C) Copyright John Maddock 2005.
  2599.      * Distributed under the Boost Software License, Version 1.0. (See accompanying
  2600.      * file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
  2601.      * </pre>
  2602.      *
  2603.      * @param real Real part.
  2604.      * @param imaginary Imaginary part.
  2605.      * @param constructor Constructor.
  2606.      * @return The inverse hyperbolic tangent of the complex number.
  2607.      */
  2608.     private static Complex atanh(final double real, final double imaginary,
  2609.                                  final ComplexConstructor constructor) {
  2610.         // Compute with positive values and determine sign at the end
  2611.         double x = Math.abs(real);
  2612.         double y = Math.abs(imaginary);
  2613.         // The result (without sign correction)
  2614.         double re;
  2615.         double im;

  2616.         // Handle C99 special cases
  2617.         if (Double.isNaN(x)) {
  2618.             if (isPosInfinite(y)) {
  2619.                 // The sign of the real part of the result is unspecified
  2620.                 return constructor.create(0, Math.copySign(PI_OVER_2, imaginary));
  2621.             }
  2622.             // No-use of the input constructor.
  2623.             // Optionally raises the ‘‘invalid’’ floating-point exception, for finite y.
  2624.             return NAN;
  2625.         } else if (Double.isNaN(y)) {
  2626.             if (isPosInfinite(x)) {
  2627.                 return constructor.create(Math.copySign(0, real), Double.NaN);
  2628.             }
  2629.             if (x == 0) {
  2630.                 return constructor.create(real, Double.NaN);
  2631.             }
  2632.             // No-use of the input constructor
  2633.             return NAN;
  2634.         } else {
  2635.             // x && y are finite or infinite.

  2636.             // Check the safe region.
  2637.             // The lower and upper bounds have been copied from boost::math::atanh.
  2638.             // They are different from the safe region for asin and acos.
  2639.             // x >= SAFE_UPPER: (1-x) == -x
  2640.             // x <= SAFE_LOWER: 1 - x^2 = 1

  2641.             if (inRegion(x, y, SAFE_LOWER, SAFE_UPPER)) {
  2642.                 // Normal computation within a safe region.

  2643.                 // minus x plus 1: (-x+1)
  2644.                 final double mxp1 = 1 - x;
  2645.                 final double yy = y * y;
  2646.                 // The definition of real component is:
  2647.                 // real = log( ((x+1)^2+y^2) / ((1-x)^2+y^2) ) / 4
  2648.                 // This simplifies by adding 1 and subtracting 1 as a fraction:
  2649.                 //      = log(1 + ((x+1)^2+y^2) / ((1-x)^2+y^2) - ((1-x)^2+y^2)/((1-x)^2+y^2) ) / 4
  2650.                 //
  2651.                 // real(atanh(z)) == log(1 + 4*x / ((1-x)^2+y^2)) / 4
  2652.                 // imag(atanh(z)) == tan^-1 (2y, (1-x)(1+x) - y^2) / 2
  2653.                 // imag(atanh(z)) == tan^-1 (2y, (1 - x^2 - y^2) / 2
  2654.                 // The division is done at the end of the function.
  2655.                 re = Math.log1p(4 * x / (mxp1 * mxp1 + yy));
  2656.                 // Modified from boost which does not switch the magnitude of x and y.
  2657.                 // The denominator for atan2 is 1 - x^2 - y^2.
  2658.                 // This can be made more precise if |x| > |y|.
  2659.                 final double numerator = 2 * y;
  2660.                 final double denominator;
  2661.                 if (x < y) {
  2662.                     final double tmp = x;
  2663.                     x = y;
  2664.                     y = tmp;
  2665.                 }
  2666.                 // 1 - x is precise if |x| >= 1
  2667.                 if (x >= 1) {
  2668.                     denominator = (1 - x) * (1 + x) - y * y;
  2669.                 } else {
  2670.                     // |x| < 1: Use high precision if possible:
  2671.                     // 1 - x^2 - y^2 = -(x^2 + y^2 - 1)
  2672.                     // Modified from boost to use the custom high precision method.
  2673.                     denominator = -x2y2m1(x, y);
  2674.                 }
  2675.                 im = Math.atan2(numerator, denominator);
  2676.             } else {
  2677.                 // This section handles exception cases that would normally cause
  2678.                 // underflow or overflow in the main formulas.

  2679.                 // C99. G.7: Special case for imaginary only numbers
  2680.                 if (x == 0) {
  2681.                     if (imaginary == 0) {
  2682.                         return constructor.create(real, imaginary);
  2683.                     }
  2684.                     // atanh(iy) = i atan(y)
  2685.                     return constructor.create(real, Math.atan(imaginary));
  2686.                 }

  2687.                 // Real part:
  2688.                 // real = Math.log1p(4x / ((1-x)^2 + y^2))
  2689.                 // real = Math.log1p(4x / (1 - 2x + x^2 + y^2))
  2690.                 // real = Math.log1p(4x / (1 + x(x-2) + y^2))
  2691.                 // without either overflow or underflow in the squared terms.
  2692.                 if (x >= SAFE_UPPER) {
  2693.                     // (1-x) = -x to machine precision:
  2694.                     // log1p(4x / (x^2 + y^2))
  2695.                     if (isPosInfinite(x) || isPosInfinite(y)) {
  2696.                         re = 0;
  2697.                     } else if (y >= SAFE_UPPER) {
  2698.                         // Big x and y: divide by x*y
  2699.                         re = Math.log1p((4 / y) / (x / y + y / x));
  2700.                     } else if (y > 1) {
  2701.                         // Big x: divide through by x:
  2702.                         re = Math.log1p(4 / (x + y * y / x));
  2703.                     } else {
  2704.                         // Big x small y, as above but neglect y^2/x:
  2705.                         re = Math.log1p(4 / x);
  2706.                     }
  2707.                 } else if (y >= SAFE_UPPER) {
  2708.                     if (x > 1) {
  2709.                         // Big y, medium x, divide through by y:
  2710.                         final double mxp1 = 1 - x;
  2711.                         re = Math.log1p((4 * x / y) / (mxp1 * mxp1 / y + y));
  2712.                     } else {
  2713.                         // Big y, small x, as above but neglect (1-x)^2/y:
  2714.                         // Note: log1p(v) == v - v^2/2 + v^3/3 ... Taylor series when v is small.
  2715.                         // Here v is so small only the first term matters.
  2716.                         re = 4 * x / y / y;
  2717.                     }
  2718.                 } else if (x == 1) {
  2719.                     // x = 1, small y:
  2720.                     // Special case when x == 1 as (1-x) is invalid.
  2721.                     // Simplify the following formula:
  2722.                     // real = log( sqrt((x+1)^2+y^2) ) / 2 - log( sqrt((1-x)^2+y^2) ) / 2
  2723.                     //      = log( sqrt(4+y^2) ) / 2 - log(y) / 2
  2724.                     // if: 4+y^2 -> 4
  2725.                     //      = log( 2 ) / 2 - log(y) / 2
  2726.                     //      = (log(2) - log(y)) / 2
  2727.                     // Multiply by 2 as it will be divided by 4 at the end.
  2728.                     // C99: if y=0 raises the ‘‘divide-by-zero’’ floating-point exception.
  2729.                     re = 2 * (LN_2 - Math.log(y));
  2730.                 } else {
  2731.                     // Modified from boost which checks y > SAFE_LOWER.
  2732.                     // if y*y -> 0 it will be ignored so always include it.
  2733.                     final double mxp1 = 1 - x;
  2734.                     re = Math.log1p((4 * x) / (mxp1 * mxp1 + y * y));
  2735.                 }

  2736.                 // Imaginary part:
  2737.                 // imag = atan2(2y, (1-x)(1+x) - y^2)
  2738.                 // if x or y are large, then the formula:
  2739.                 //   atan2(2y, (1-x)(1+x) - y^2)
  2740.                 // evaluates to +(PI - theta) where theta is negligible compared to PI.
  2741.                 if (x >= SAFE_UPPER || y >= SAFE_UPPER) {
  2742.                     im = Math.PI;
  2743.                 } else if (x <= SAFE_LOWER) {
  2744.                     // (1-x)^2 -> 1
  2745.                     if (y <= SAFE_LOWER) {
  2746.                         // 1 - y^2 -> 1
  2747.                         im = Math.atan2(2 * y, 1);
  2748.                     } else {
  2749.                         im = Math.atan2(2 * y, 1 - y * y);
  2750.                     }
  2751.                 } else {
  2752.                     // Medium x, small y.
  2753.                     // Modified from boost which checks (y == 0) && (x == 1) and sets re = 0.
  2754.                     // This is same as the result from calling atan2(0, 0) so exclude this case.
  2755.                     // 1 - y^2 = 1 so ignore subtracting y^2
  2756.                     im = Math.atan2(2 * y, (1 - x) * (1 + x));
  2757.                 }
  2758.             }
  2759.         }

  2760.         re /= 4;
  2761.         im /= 2;
  2762.         return constructor.create(changeSign(re, real),
  2763.                                   changeSign(im, imaginary));
  2764.     }

  2765.     /**
  2766.      * Compute {@code x^2 + y^2 - 1} in high precision.
  2767.      * Assumes that the values x and y can be multiplied without overflow; that
  2768.      * {@code x >= y}; and both values are positive.
  2769.      *
  2770.      * @param x the x value
  2771.      * @param y the y value
  2772.      * @return {@code x^2 + y^2 - 1}.
  2773.      */
  2774.     private static double x2y2m1(double x, double y) {
  2775.         // Hull et al used (x-1)*(x+1)+y*y.
  2776.         // From the paper on page 236:

  2777.         // If x == 1 there is no cancellation.

  2778.         // If x > 1, there is also no cancellation, but the argument is now accurate
  2779.         // only to within a factor of 1 + 3 EPSILSON (note that x – 1 is exact),
  2780.         // so that error = 3 EPSILON.

  2781.         // If x < 1, there can be serious cancellation:

  2782.         // If 4 y^2 < |x^2 – 1| the cancellation is not serious ... the argument is accurate
  2783.         // only to within a factor of 1 + 4 EPSILSON so that error = 4 EPSILON.

  2784.         // Otherwise there can be serious cancellation and the relative error in the real part
  2785.         // could be enormous.

  2786.         final double xx = x * x;
  2787.         final double yy = y * y;
  2788.         // Modify to use high precision before the threshold set by Hull et al.
  2789.         // This is to preserve the monotonic output of the computation at the switch.
  2790.         // Set the threshold when x^2 + y^2 is above 0.5 thus subtracting 1 results in a number
  2791.         // that can be expressed with a higher precision than any number in the range 0.5-1.0
  2792.         // due to the variable exponent used below 0.5.
  2793.         if (x < 1 && xx + yy > 0.5) {
  2794.             // Large relative error.
  2795.             // This does not use o.a.c.numbers.LinearCombination.value(x, x, y, y, 1, -1).
  2796.             // It is optimised knowing that:
  2797.             // - the products are squares
  2798.             // - the final term is -1 (which does not require split multiplication and addition)
  2799.             // - The answer will not be NaN as the terms are not NaN components
  2800.             // - The order is known to be 1 > |x| >= |y|
  2801.             // The squares are computed using a split multiply algorithm and
  2802.             // the summation using an extended precision summation algorithm.

  2803.             // Split x and y as one 26 bits number and one 27 bits number
  2804.             final double xHigh = splitHigh(x);
  2805.             final double xLow  = x - xHigh;
  2806.             final double yHigh = splitHigh(y);
  2807.             final double yLow  = y - yHigh;

  2808.             // Accurate split multiplication x * x and y * y
  2809.             final double x2Low = squareLow(xLow, xHigh, xx);
  2810.             final double y2Low = squareLow(yLow, yHigh, yy);

  2811.             return sumx2y2m1(xx, x2Low, yy, y2Low);
  2812.         }
  2813.         return (x - 1) * (x + 1) + yy;
  2814.     }

  2815.     /**
  2816.      * Implement Dekker's method to split a value into two parts. Multiplying by (2^s + 1) create
  2817.      * a big value from which to derive the two split parts.
  2818.      * <pre>
  2819.      * c = (2^s + 1) * a
  2820.      * a_big = c - a
  2821.      * a_hi = c - a_big
  2822.      * a_lo = a - a_hi
  2823.      * a = a_hi + a_lo
  2824.      * </pre>
  2825.      *
  2826.      * <p>The multiplicand must be odd allowing a p-bit value to be split into
  2827.      * (p-s)-bit value {@code a_hi} and a non-overlapping (s-1)-bit value {@code a_lo}.
  2828.      * Combined they have (p􏰔-1) bits of significand but the sign bit of {@code a_lo}
  2829.      * contains a bit of information.
  2830.      *
  2831.      * @param a Value.
  2832.      * @return the high part of the value.
  2833.      * @see <a href="https://doi.org/10.1007/BF01397083">
  2834.      * Dekker (1971) A floating-point technique for extending the available precision</a>
  2835.      */
  2836.     private static double splitHigh(double a) {
  2837.         final double c = MULTIPLIER * a;
  2838.         return c - (c - a);
  2839.     }

  2840.     /**
  2841.      * Compute the round-off from the square of a split number with {@code low} and {@code high}
  2842.      * components. Uses Dekker's algorithm for split multiplication modified for a square product.
  2843.      *
  2844.      * <p>Note: This is candidate to be replaced with {@code Math.fma(x, x, -x * x)} to compute
  2845.      * the round-off from the square product {@code x * x}. This would remove the requirement
  2846.      * to compute the split number and make this method redundant. {@code Math.fma} requires
  2847.      * JDK 9 and FMA hardware support.
  2848.      *
  2849.      * @param low Low part of number.
  2850.      * @param high High part of number.
  2851.      * @param square Square of the number.
  2852.      * @return <code>low * low - (((product - high * high) - low * high) - high * low)</code>
  2853.      * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
  2854.      * Shewchuk (1997) Theorum 18</a>
  2855.      */
  2856.     private static double squareLow(double low, double high, double square) {
  2857.         final double lh = low * high;
  2858.         return low * low - (((square - high * high) - lh) - lh);
  2859.     }

  2860.     /**
  2861.      * Compute the round-off from the sum of two numbers {@code a} and {@code b} using
  2862.      * Dekker's two-sum algorithm. The values are required to be ordered by magnitude:
  2863.      * {@code |a| >= |b|}.
  2864.      *
  2865.      * @param a First part of sum.
  2866.      * @param b Second part of sum.
  2867.      * @param x Sum.
  2868.      * @return <code>b - (x - a)</code>
  2869.      * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
  2870.      * Shewchuk (1997) Theorum 6</a>
  2871.      */
  2872.     private static double fastSumLow(double a, double b, double x) {
  2873.         // x = a + b
  2874.         // bVirtual = x - a
  2875.         // y = b - bVirtual
  2876.         return b - (x - a);
  2877.     }

  2878.     /**
  2879.      * Compute the round-off from the sum of two numbers {@code a} and {@code b} using
  2880.      * Knuth's two-sum algorithm. The values are not required to be ordered by magnitude.
  2881.      *
  2882.      * @param a First part of sum.
  2883.      * @param b Second part of sum.
  2884.      * @param x Sum.
  2885.      * @return <code>(a - (x - (x - a))) + (b - (x - a))</code>
  2886.      * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
  2887.      * Shewchuk (1997) Theorum 7</a>
  2888.      */
  2889.     private static double sumLow(double a, double b, double x) {
  2890.         // x = a + b
  2891.         // bVirtual = x - a
  2892.         // aVirtual = x - bVirtual
  2893.         // bRoundoff = b - bVirtual
  2894.         // aRoundoff = a - aVirtual
  2895.         // y = aRoundoff + bRoundoff
  2896.         final double bVirtual = x - a;
  2897.         return (a - (x - bVirtual)) + (b - bVirtual);
  2898.     }

  2899.     /**
  2900.      * Sum x^2 + y^2 - 1. It is assumed that {@code y <= x < 1}.
  2901.      *
  2902.      * <p>Implement Shewchuk's expansion-sum algorithm: [x2Low, x2High] + [-1] + [y2Low, y2High].
  2903.      *
  2904.      * @param x2High High part of x^2.
  2905.      * @param x2Low Low part of x^2.
  2906.      * @param y2High High part of y^2.
  2907.      * @param y2Low Low part of y^2.
  2908.      * @return x^2 + y^2 - 1
  2909.      * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
  2910.      * Shewchuk (1997) Theorum 12</a>
  2911.      */
  2912.     private static double sumx2y2m1(double x2High, double x2Low, double y2High, double y2Low) {
  2913.         // Let e and f be non-overlapping expansions of components of length m and n.
  2914.         // The following algorithm will produce a non-overlapping expansion h where the
  2915.         // sum h_i = e + f and components of h are in increasing order of magnitude.

  2916.         // Expansion-sum proceeds by a grow-expansion of the first part from one expansion
  2917.         // into the other, extending its length by 1. The process repeats for the next part
  2918.         // but the grow-expansion starts at the previous merge position + 1.
  2919.         // Thus expansion-sum requires mn two-sum operations to merge length m into length n
  2920.         // resulting in length m+n-1.

  2921.         // Variables numbered from 1 as per Figure 7 (p.12). The output expansion h is placed
  2922.         // into e increasing its length for each grow expansion.

  2923.         // We have two expansions for x^2 and y^2 and the whole number -1.
  2924.         // Expecting (x^2 + y^2) close to 1 we generate first the intermediate expansion
  2925.         // (x^2 - 1) moving the result away from 1 where there are sparse floating point
  2926.         // representations. This is then added to a similar magnitude y^2. Leaving the -1
  2927.         // until last suffers from 1 ulp rounding errors more often and the requirement
  2928.         // for a distillation sum to reduce rounding error frequency.

  2929.         // Note: Do not use the alternative fast-expansion-sum of the parts sorted by magnitude.
  2930.         // The parts can be ordered with a single comparison into:
  2931.         // [y2Low, (y2High|x2Low), x2High, -1]
  2932.         // The fast-two-sum saves 1 fast-two-sum and 3 two-sum operations (21 additions) and
  2933.         // adds a penalty of a single branch condition.
  2934.         // However the order in not "strongly non-overlapping" and the fast-expansion-sum
  2935.         // output will not be strongly non-overlapping. The sum of the output has 1 ulp error
  2936.         // on random cis numbers approximately 1 in 160 events. This can be removed by a
  2937.         // distillation two-sum pass over the final expansion as a cost of 1 fast-two-sum and
  2938.         // 3 two-sum operations! So we use the expansion sum with the same operations and
  2939.         // no branches.

  2940.         // q=running sum
  2941.         double q = x2Low - 1;
  2942.         double e1 = fastSumLow(-1, x2Low, q);
  2943.         double e3 = q + x2High;
  2944.         double e2 = sumLow(q, x2High, e3);

  2945.         final double f1 = y2Low;
  2946.         final double f2 = y2High;

  2947.         // Grow expansion of f1 into e
  2948.         q = f1 + e1;
  2949.         e1 = sumLow(f1, e1, q);
  2950.         double p = q + e2;
  2951.         e2 = sumLow(q, e2, p);
  2952.         double e4 = p + e3;
  2953.         e3 = sumLow(p, e3, e4);

  2954.         // Grow expansion of f2 into e (only required to start at e2)
  2955.         q = f2 + e2;
  2956.         e2 = sumLow(f2, e2, q);
  2957.         p = q + e3;
  2958.         e3 = sumLow(q, e3, p);
  2959.         final double e5 = p + e4;
  2960.         e4 = sumLow(p, e4, e5);

  2961.         // Final summation:
  2962.         // The sum of the parts is within 1 ulp of the true expansion value e:
  2963.         // |e - sum| < ulp(sum).
  2964.         // To achieve the exact result requires iteration of a distillation two-sum through
  2965.         // the expansion until convergence, i.e. no smaller term changes higher terms.
  2966.         // This requires (n-1) iterations for length n. Here we neglect this as
  2967.         // although the method is not ensured to be exact is it robust on random
  2968.         // cis numbers.
  2969.         return e1 + e2 + e3 + e4 + e5;
  2970.     }

  2971.     /**
  2972.      * Returns the n-th roots of this complex number.
  2973.      * The nth roots are defined by the formula:
  2974.      *
  2975.      * <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) \]
  2976.      *
  2977.      * <p>for \( k=0, 1, \ldots, n-1 \), where \( |z| \) and \( \phi \)
  2978.      * are respectively the {@link #abs() modulus} and
  2979.      * {@link #arg() argument} of this complex number.
  2980.      *
  2981.      * <p>If one or both parts of this complex number is NaN, a list with all
  2982.      * all elements set to {@code NaN + i NaN} is returned.</p>
  2983.      *
  2984.      * @param n Degree of root.
  2985.      * @return A list of all {@code n}-th roots of this complex number.
  2986.      * @throws IllegalArgumentException if {@code n} is zero.
  2987.      * @see <a href="http://functions.wolfram.com/ElementaryFunctions/Root/">Root</a>
  2988.      */
  2989.     public List<Complex> nthRoot(int n) {
  2990.         if (n == 0) {
  2991.             throw new IllegalArgumentException("cannot compute zeroth root");
  2992.         }

  2993.         final List<Complex> result = new ArrayList<>();

  2994.         // nth root of abs -- faster / more accurate to use a solver here?
  2995.         final double nthRootOfAbs = Math.pow(abs(), 1.0 / n);

  2996.         // Compute nth roots of complex number with k = 0, 1, ... n-1
  2997.         final double nthPhi = arg() / n;
  2998.         final double slice = 2 * Math.PI / n;
  2999.         double innerPart = nthPhi;
  3000.         for (int k = 0; k < Math.abs(n); k++) {
  3001.             // inner part
  3002.             final double realPart = nthRootOfAbs *  Math.cos(innerPart);
  3003.             final double imaginaryPart = nthRootOfAbs *  Math.sin(innerPart);
  3004.             result.add(ofCartesian(realPart, imaginaryPart));
  3005.             innerPart += slice;
  3006.         }

  3007.         return result;
  3008.     }

  3009.     /**
  3010.      * Test for equality with another object. If the other object is a {@code Complex} then a
  3011.      * comparison is made of the real and imaginary parts; otherwise {@code false} is returned.
  3012.      *
  3013.      * <p>If both the real and imaginary parts of two complex numbers
  3014.      * are exactly the same the two {@code Complex} objects are considered to be equal.
  3015.      * For this purpose, two {@code double} values are considered to be
  3016.      * the same if and only if the method {@link Double #doubleToLongBits(double)}
  3017.      * returns the identical {@code long} value when applied to each.
  3018.      *
  3019.      * <p>Note that in most cases, for two instances of class
  3020.      * {@code Complex}, {@code c1} and {@code c2}, the
  3021.      * value of {@code c1.equals(c2)} is {@code true} if and only if
  3022.      *
  3023.      * <pre>
  3024.      *  {@code c1.getReal() == c2.getReal() && c1.getImaginary() == c2.getImaginary()}</pre>
  3025.      *
  3026.      * <p>also has the value {@code true}. However, there are exceptions:
  3027.      *
  3028.      * <ul>
  3029.      *  <li>
  3030.      *   Instances that contain {@code NaN} values in the same part
  3031.      *   are considered to be equal for that part, even though {@code Double.NaN == Double.NaN}
  3032.      *   has the value {@code false}.
  3033.      *  </li>
  3034.      *  <li>
  3035.      *   Instances that share a {@code NaN} value in one part
  3036.      *   but have different values in the other part are <em>not</em> considered equal.
  3037.      *  </li>
  3038.      *  <li>
  3039.      *   Instances that contain different representations of zero in the same part
  3040.      *   are <em>not</em> considered to be equal for that part, even though {@code -0.0 == 0.0}
  3041.      *   has the value {@code true}.
  3042.      *  </li>
  3043.      * </ul>
  3044.      *
  3045.      * <p>The behavior is the same as if the components of the two complex numbers were passed
  3046.      * to {@link java.util.Arrays#equals(double[], double[]) Arrays.equals(double[], double[])}:
  3047.      *
  3048.      * <pre>
  3049.      *  Arrays.equals(new double[]{c1.getReal(), c1.getImaginary()},
  3050.      *                new double[]{c2.getReal(), c2.getImaginary()}); </pre>
  3051.      *
  3052.      * @param other Object to test for equality with this instance.
  3053.      * @return {@code true} if the objects are equal, {@code false} if object
  3054.      * is {@code null}, not an instance of {@code Complex}, or not equal to
  3055.      * this instance.
  3056.      * @see Double#doubleToLongBits(double)
  3057.      * @see java.util.Arrays#equals(double[], double[])
  3058.      */
  3059.     @Override
  3060.     public boolean equals(Object other) {
  3061.         if (this == other) {
  3062.             return true;
  3063.         }
  3064.         if (other instanceof Complex) {
  3065.             final Complex c = (Complex) other;
  3066.             return equals(real, c.real) &&
  3067.                 equals(imaginary, c.imaginary);
  3068.         }
  3069.         return false;
  3070.     }

  3071.     /**
  3072.      * Gets a hash code for the complex number.
  3073.      *
  3074.      * <p>The behavior is the same as if the components of the complex number were passed
  3075.      * to {@link java.util.Arrays#hashCode(double[]) Arrays.hashCode(double[])}:
  3076.      *
  3077.      * <pre>
  3078.      *  {@code Arrays.hashCode(new double[] {getReal(), getImaginary()})}</pre>
  3079.      *
  3080.      * @return A hash code value for this object.
  3081.      * @see java.util.Arrays#hashCode(double[]) Arrays.hashCode(double[])
  3082.      */
  3083.     @Override
  3084.     public int hashCode() {
  3085.         return 31 * (31 + Double.hashCode(real)) + Double.hashCode(imaginary);
  3086.     }

  3087.     /**
  3088.      * Returns a string representation of the complex number.
  3089.      *
  3090.      * <p>The string will represent the numeric values of the real and imaginary parts.
  3091.      * The values are split by a separator and surrounded by parentheses.
  3092.      * The string can be {@link #parse(String) parsed} to obtain an instance with the same value.
  3093.      *
  3094.      * <p>The format for complex number \( x + i y \) is {@code "(x,y)"}, with \( x \) and
  3095.      * \( y \) converted as if using {@link Double#toString(double)}.
  3096.      *
  3097.      * @return A string representation of the complex number.
  3098.      * @see #parse(String)
  3099.      * @see Double#toString(double)
  3100.      */
  3101.     @Override
  3102.     public String toString() {
  3103.         return new StringBuilder(TO_STRING_SIZE)
  3104.             .append(FORMAT_START)
  3105.             .append(real).append(FORMAT_SEP)
  3106.             .append(imaginary)
  3107.             .append(FORMAT_END)
  3108.             .toString();
  3109.     }

  3110.     /**
  3111.      * Returns {@code true} if the values are equal according to semantics of
  3112.      * {@link Double#equals(Object)}.
  3113.      *
  3114.      * @param x Value
  3115.      * @param y Value
  3116.      * @return {@code Double.valueof(x).equals(Double.valueOf(y))}.
  3117.      */
  3118.     private static boolean equals(double x, double y) {
  3119.         return Double.doubleToLongBits(x) == Double.doubleToLongBits(y);
  3120.     }

  3121.     /**
  3122.      * Check that a value is negative. It must meet all the following conditions:
  3123.      * <ul>
  3124.      *  <li>it is not {@code NaN},</li>
  3125.      *  <li>it is negative signed,</li>
  3126.      * </ul>
  3127.      *
  3128.      * <p>Note: This is true for negative zero.</p>
  3129.      *
  3130.      * @param d Value.
  3131.      * @return {@code true} if {@code d} is negative.
  3132.      */
  3133.     private static boolean negative(double d) {
  3134.         return d < 0 || Double.doubleToLongBits(d) == NEGATIVE_ZERO_LONG_BITS;
  3135.     }

  3136.     /**
  3137.      * Check that a value is positive infinity. Used to replace {@link Double#isInfinite()}
  3138.      * when the input value is known to be positive (i.e. in the case where it has been
  3139.      * set using {@link Math#abs(double)}).
  3140.      *
  3141.      * @param d Value.
  3142.      * @return {@code true} if {@code d} is +inf.
  3143.      */
  3144.     private static boolean isPosInfinite(double d) {
  3145.         return d == Double.POSITIVE_INFINITY;
  3146.     }

  3147.     /**
  3148.      * Check that an absolute value is finite. Used to replace {@link Double#isFinite(double)}
  3149.      * when the input value is known to be positive (i.e. in the case where it has been
  3150.      * set using {@link Math#abs(double)}).
  3151.      *
  3152.      * @param d Value.
  3153.      * @return {@code true} if {@code d} is +finite.
  3154.      */
  3155.     private static boolean isPosFinite(double d) {
  3156.         return d <= Double.MAX_VALUE;
  3157.     }

  3158.     /**
  3159.      * Create a complex number given the real and imaginary parts, then multiply by {@code -i}.
  3160.      * This is used in functions that implement trigonomic identities. It is the functional
  3161.      * equivalent of:
  3162.      *
  3163.      * <pre>
  3164.      *  z = new Complex(real, imaginary).multiplyImaginary(-1);</pre>
  3165.      *
  3166.      * @param real Real part.
  3167.      * @param imaginary Imaginary part.
  3168.      * @return {@code Complex} object.
  3169.      */
  3170.     private static Complex multiplyNegativeI(double real, double imaginary) {
  3171.         return new Complex(imaginary, -real);
  3172.     }

  3173.     /**
  3174.      * Change the sign of the magnitude based on the signed value.
  3175.      *
  3176.      * <p>If the signed value is negative then the result is {@code -magnitude}; otherwise
  3177.      * return {@code magnitude}.
  3178.      *
  3179.      * <p>A signed value of {@code -0.0} is treated as negative. A signed value of {@code NaN}
  3180.      * is treated as positive.
  3181.      *
  3182.      * <p>This is not the same as {@link Math#copySign(double, double)} as this method
  3183.      * will change the sign based on the signed value rather than copy the sign.
  3184.      *
  3185.      * @param magnitude the magnitude
  3186.      * @param signedValue the signed value
  3187.      * @return magnitude or -magnitude.
  3188.      * @see #negative(double)
  3189.      */
  3190.     private static double changeSign(double magnitude, double signedValue) {
  3191.         return negative(signedValue) ? -magnitude : magnitude;
  3192.     }

  3193.     /**
  3194.      * Returns a scale suitable for use with {@link Math#scalb(double, int)} to normalise
  3195.      * the number to the interval {@code [1, 2)}.
  3196.      *
  3197.      * <p>The scale is typically the largest unbiased exponent used in the representation of the
  3198.      * two numbers. In contrast to {@link Math#getExponent(double)} this handles
  3199.      * sub-normal numbers by computing the number of leading zeros in the mantissa
  3200.      * and shifting the unbiased exponent. The result is that for all finite, non-zero,
  3201.      * numbers {@code a, b}, the magnitude of {@code scalb(x, -getScale(a, b))} is
  3202.      * always in the range {@code [1, 2)}, where {@code x = max(|a|, |b|)}.
  3203.      *
  3204.      * <p>This method is a functional equivalent of the c function ilogb(double) adapted for
  3205.      * two input arguments.
  3206.      *
  3207.      * <p>The result is to be used to scale a complex number using {@link Math#scalb(double, int)}.
  3208.      * Hence the special case of both zero arguments is handled using the return value for NaN
  3209.      * as zero cannot be scaled. This is different from {@link Math#getExponent(double)}
  3210.      * or {@link #getMaxExponent(double, double)}.
  3211.      *
  3212.      * <p>Special cases:
  3213.      *
  3214.      * <ul>
  3215.      * <li>If either argument is NaN or infinite, then the result is
  3216.      * {@link Double#MAX_EXPONENT} + 1.
  3217.      * <li>If both arguments are zero, then the result is
  3218.      * {@link Double#MAX_EXPONENT} + 1.
  3219.      * </ul>
  3220.      *
  3221.      * @param a the first value
  3222.      * @param b the second value
  3223.      * @return The maximum unbiased exponent of the values to be used for scaling
  3224.      * @see Math#getExponent(double)
  3225.      * @see Math#scalb(double, int)
  3226.      * @see <a href="http://www.cplusplus.com/reference/cmath/ilogb/">ilogb</a>
  3227.      */
  3228.     private static int getScale(double a, double b) {
  3229.         // Only interested in the exponent and mantissa so remove the sign bit
  3230.         final long x = Double.doubleToRawLongBits(a) & UNSIGN_MASK;
  3231.         final long y = Double.doubleToRawLongBits(b) & UNSIGN_MASK;
  3232.         // Only interested in the maximum
  3233.         final long bits = Math.max(x, y);
  3234.         // Get the unbiased exponent
  3235.         int exp = ((int) (bits >>> 52)) - EXPONENT_OFFSET;

  3236.         // No case to distinguish nan/inf
  3237.         // Handle sub-normal numbers
  3238.         if (exp == Double.MIN_EXPONENT - 1) {
  3239.             // Special case for zero, return as nan/inf to indicate scaling is not possible
  3240.             if (bits == 0) {
  3241.                 return Double.MAX_EXPONENT + 1;
  3242.             }
  3243.             // A sub-normal number has an exponent below -1022. The amount below
  3244.             // is defined by the number of shifts of the most significant bit in
  3245.             // the mantissa that is required to get a 1 at position 53 (i.e. as
  3246.             // if it were a normal number with assumed leading bit)
  3247.             final long mantissa = bits & MANTISSA_MASK;
  3248.             exp -= Long.numberOfLeadingZeros(mantissa << 12);
  3249.         }
  3250.         return exp;
  3251.     }

  3252.     /**
  3253.      * Returns the largest unbiased exponent used in the representation of the
  3254.      * two numbers. Special cases:
  3255.      *
  3256.      * <ul>
  3257.      * <li>If either argument is NaN or infinite, then the result is
  3258.      * {@link Double#MAX_EXPONENT} + 1.
  3259.      * <li>If both arguments are zero or subnormal, then the result is
  3260.      * {@link Double#MIN_EXPONENT} -1.
  3261.      * </ul>
  3262.      *
  3263.      * <p>This is used by {@link #divide(double, double, double, double)} as
  3264.      * a simple detection that a number may overflow if multiplied
  3265.      * by a value in the interval [1, 2).
  3266.      *
  3267.      * @param a the first value
  3268.      * @param b the second value
  3269.      * @return The maximum unbiased exponent of the values.
  3270.      * @see Math#getExponent(double)
  3271.      * @see #divide(double, double, double, double)
  3272.      */
  3273.     private static int getMaxExponent(double a, double b) {
  3274.         // This could return:
  3275.         // Math.getExponent(Math.max(Math.abs(a), Math.abs(b)))
  3276.         // A speed test is required to determine performance.
  3277.         return Math.max(Math.getExponent(a), Math.getExponent(b));
  3278.     }

  3279.     /**
  3280.      * Checks if both x and y are in the region defined by the minimum and maximum.
  3281.      *
  3282.      * @param x x value.
  3283.      * @param y y value.
  3284.      * @param min the minimum (exclusive).
  3285.      * @param max the maximum (exclusive).
  3286.      * @return true if inside the region.
  3287.      */
  3288.     private static boolean inRegion(double x, double y, double min, double max) {
  3289.         return x < max && x > min && y < max && y > min;
  3290.     }

  3291.     /**
  3292.      * Returns {@code sqrt(x^2 + y^2)} without intermediate overflow or underflow.
  3293.      *
  3294.      * <p>Special cases:
  3295.      * <ul>
  3296.      * <li>If either argument is infinite, then the result is positive infinity.
  3297.      * <li>If either argument is NaN and neither argument is infinite, then the result is NaN.
  3298.      * </ul>
  3299.      *
  3300.      * <p>The computed result is expected to be within 1 ulp of the exact result.
  3301.      *
  3302.      * <p>This method is a replacement for {@link Math#hypot(double, double)}. There
  3303.      * will be differences between this method and {@code Math.hypot(double, double)} due
  3304.      * to the use of a different algorithm to compute the high precision sum of
  3305.      * {@code x^2 + y^2}. This method has been tested to have a lower maximum error from
  3306.      * the exact result; any differences are expected to be 1 ULP indicating a rounding
  3307.      * change in the sum.
  3308.      *
  3309.      * <p>JDK9 ported the hypot function to Java for bug JDK-7130085 due to the slow performance
  3310.      * of the method as a native function. Benchmarks of the Complex class for functions that
  3311.      * use hypot confirm this is slow pre-Java 9. This implementation outperforms the new faster
  3312.      * {@code Math.hypot(double, double)} on JDK 11 (LTS). See the Commons numbers examples JMH
  3313.      * module for benchmarks. Comparisons with alternative implementations indicate
  3314.      * performance gains are related to edge case handling and elimination of an unpredictable
  3315.      * branch in the computation of {@code x^2 + y^2}.
  3316.      *
  3317.      * <p>This port was adapted from the "Freely Distributable Math Library" hypot function.
  3318.      * This method only (and not invoked methods within) is distributed under the terms of the
  3319.      * original notice as shown below:
  3320.      * <pre>
  3321.      * ====================================================
  3322.      * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
  3323.      *
  3324.      * Developed at SunSoft, a Sun Microsystems, Inc. business.
  3325.      * Permission to use, copy, modify, and distribute this
  3326.      * software is freely granted, provided that this notice
  3327.      * is preserved.
  3328.      * ====================================================
  3329.      * </pre>
  3330.      *
  3331.      * <p>Note: The fdlibm c code makes use of the language ability to read and write directly
  3332.      * to the upper and lower 32-bits of the 64-double. The function performs
  3333.      * checking on the upper 32-bits for the magnitude of the two numbers by accessing
  3334.      * the exponent and 20 most significant bits of the mantissa. These upper bits
  3335.      * are manipulated during scaling and then used to perform extended precision
  3336.      * computation of the sum {@code x^2 + y^2} where the high part of the number has 20-bit
  3337.      * precision. Manipulation of direct bits has no equivalent in Java
  3338.      * other than use of {@link Double#doubleToLongBits(double)} and
  3339.      * {@link Double#longBitsToDouble(long)}. To avoid conversion to and from long and double
  3340.      * representations this implementation only scales the double representation. The high
  3341.      * and low parts of a double for the extended precision computation are extracted
  3342.      * using the method of Dekker (1971) to create two 26-bit numbers. This works for sub-normal
  3343.      * numbers and reduces the maximum error in comparison to fdlibm hypot which does not
  3344.      * use a split number algorithm for sub-normal numbers.
  3345.      *
  3346.      * @param x Value x
  3347.      * @param y Value y
  3348.      * @return sqrt(x^2 + y^2)
  3349.      * @see Math#hypot(double, double)
  3350.      * @see <a href="https://www.netlib.org/fdlibm/e_hypot.c">fdlibm e_hypot.c</a>
  3351.      * @see <a href="https://bugs.java.com/bugdatabase/view_bug.do?bug_id=7130085">JDK-7130085 : Port fdlibm hypot to Java</a>
  3352.      */
  3353.     private static double hypot(double x, double y) {
  3354.         // Differences to the fdlibm reference:
  3355.         //
  3356.         // 1. fdlibm orders the two parts using the magnitude of the upper 32-bits.
  3357.         // This incorrectly orders numbers which differ only in the lower 32-bits.
  3358.         // This invalidates hypot(x, y) = hypot(y, x) for small sub-normal numbers and a minority
  3359.         // of cases of normal numbers. This implementation forces the |x| >= |y| order
  3360.         // using the entire 63-bits of the unsigned doubles to ensure the function
  3361.         // is commutative.
  3362.         //
  3363.         // 2. fdlibm computed scaling by directly writing changes to the exponent bits
  3364.         // and maintained the high part (ha) during scaling for use in the high
  3365.         // precision sum x^2 + y^2. Since exponent scaling cannot be applied to sub-normals
  3366.         // the original version dropped the split number representation for sub-normals
  3367.         // and can produce maximum errors above 1 ULP for sub-normal numbers.
  3368.         // This version uses Dekker's method to split the number. This can be applied to
  3369.         // sub-normals and allows dropping the condition to check for sub-normal numbers
  3370.         // since all small numbers are handled with a single scaling factor.
  3371.         // The effect is increased precision for the majority of sub-normal cases where
  3372.         // the implementations compute a different result.
  3373.         //
  3374.         // 3. An alteration is done here to add an 'else if' instead of a second
  3375.         // 'if' statement. Thus you cannot scale down and up at the same time.
  3376.         //
  3377.         // 4. There is no use of the absolute double value. The magnitude comparison is
  3378.         // performed using the long bit representation. The computation x^2+y^2 is
  3379.         // insensitive to the sign bit. Thus use of Math.abs(double) is only in edge-case
  3380.         // branches.
  3381.         //
  3382.         // 5. The exponent different to ignore the smaller component has changed from 60 to 54.
  3383.         //
  3384.         // Original comments from fdlibm are in c style: /* */
  3385.         // Extra comments added for reference.
  3386.         //
  3387.         // Note that the high 32-bits are compared to constants.
  3388.         // The lowest 20-bits are the upper bits of the 52-bit mantissa.
  3389.         // The next 11-bits are the biased exponent. The sign bit has been cleared.
  3390.         // Scaling factors are powers of two for exact scaling.
  3391.         // For clarity the values have been refactored to named constants.

  3392.         // The mask is used to remove the sign bit.
  3393.         final long xbits = Double.doubleToRawLongBits(x) & UNSIGN_MASK;
  3394.         final long ybits = Double.doubleToRawLongBits(y) & UNSIGN_MASK;

  3395.         // Order by magnitude: |a| >= |b|
  3396.         double a;
  3397.         double b;
  3398.         /* High word of x & y */
  3399.         final int ha;
  3400.         final int hb;
  3401.         if (ybits > xbits) {
  3402.             a = y;
  3403.             b = x;
  3404.             ha = (int) (ybits >>> 32);
  3405.             hb = (int) (xbits >>> 32);
  3406.         } else {
  3407.             a = x;
  3408.             b = y;
  3409.             ha = (int) (xbits >>> 32);
  3410.             hb = (int) (ybits >>> 32);
  3411.         }

  3412.         // Check if the smaller part is significant.
  3413.         // a^2 is computed in extended precision for an effective mantissa of 106-bits.
  3414.         // An exponent difference of 54 is where b^2 will not overlap a^2.
  3415.         if ((ha - hb) > EXP_54) {
  3416.             /* a/b > 2**54 */
  3417.             // or a is Inf or NaN.
  3418.             // No addition of a + b for sNaN.
  3419.             return Math.abs(a);
  3420.         }

  3421.         double rescale = 1.0;
  3422.         if (ha > EXP_500) {
  3423.             /* a > 2^500 */
  3424.             if (ha >= EXP_1024) {
  3425.                 /* Inf or NaN */
  3426.                 // Check b is infinite for the IEEE754 result.
  3427.                 // No addition of a + b for sNaN.
  3428.                 return Math.abs(b) == Double.POSITIVE_INFINITY ?
  3429.                     Double.POSITIVE_INFINITY :
  3430.                     Math.abs(a);
  3431.             }
  3432.             /* scale a and b by 2^-600 */
  3433.             // Before scaling: a in [2^500, 2^1023].
  3434.             // After scaling: a in [2^-100, 2^423].
  3435.             // After scaling: b in [2^-154, 2^423].
  3436.             a *= TWO_POW_NEG_600;
  3437.             b *= TWO_POW_NEG_600;
  3438.             rescale = TWO_POW_600;
  3439.         } else if (hb < EXP_NEG_500) {
  3440.             // No special handling of sub-normals.
  3441.             // These do not matter when we do not manipulate the exponent bits
  3442.             // for scaling the split representation.

  3443.             // Intentional comparison with zero.
  3444.             if (b == 0) {
  3445.                 return Math.abs(a);
  3446.             }

  3447.             /* scale a and b by 2^600 */
  3448.             // Effective min exponent of a sub-normal = -1022 - 52 = -1074.
  3449.             // Before scaling: b in [2^-1074, 2^-501].
  3450.             // After scaling: b in [2^-474, 2^99].
  3451.             // After scaling: a in [2^-474, 2^153].
  3452.             a *= TWO_POW_600;
  3453.             b *= TWO_POW_600;
  3454.             rescale = TWO_POW_NEG_600;
  3455.         }

  3456.         // High precision x^2 + y^2
  3457.         return Math.sqrt(x2y2(a, b)) * rescale;
  3458.     }

  3459.     /**
  3460.      * Return {@code x^2 + y^2} with high accuracy.
  3461.      *
  3462.      * <p>It is assumed that {@code 2^500 > |x| >= |y| > 2^-500}. Thus there will be no
  3463.      * overflow or underflow of the result. The inputs are not assumed to be unsigned.
  3464.      *
  3465.      * <p>The computation is performed using Dekker's method for extended precision
  3466.      * multiplication of x and y and then summation of the extended precision squares.
  3467.      *
  3468.      * @param x Value x.
  3469.      * @param y Value y
  3470.      * @return x^2 + y^2
  3471.      * @see <a href="https://doi.org/10.1007/BF01397083">
  3472.      * Dekker (1971) A floating-point technique for extending the available precision</a>
  3473.      */
  3474.     private static double x2y2(double x, double y) {
  3475.         // Note:
  3476.         // This method is different from the high-accuracy summation used in fdlibm for hypot.
  3477.         // The summation could be any valid computation of x^2+y^2. However since this follows
  3478.         // the re-scaling logic in hypot(x, y) the use of high precision has relatively
  3479.         // less performance overhead than if used without scaling.
  3480.         // The Dekker algorithm is branchless for better performance
  3481.         // than the fdlibm method with a maximum ULP error of approximately 0.86.
  3482.         //
  3483.         // See NUMBERS-143 for analysis.

  3484.         // Do a Dekker summation of double length products x*x and y*y
  3485.         // (10 multiply and 20 additions).
  3486.         final double xx = x * x;
  3487.         final double yy = y * y;
  3488.         // Compute the round-off from the products.
  3489.         // With FMA hardware support in JDK 9+ this can be replaced with the much faster:
  3490.         // xxLow = Math.fma(x, x, -xx)
  3491.         // yyLow = Math.fma(y, y, -yy)
  3492.         // Dekker mul12
  3493.         final double xHigh = splitHigh(x);
  3494.         final double xLow = x - xHigh;
  3495.         final double xxLow = squareLow(xLow, xHigh, xx);
  3496.         // Dekker mul12
  3497.         final double yHigh = splitHigh(y);
  3498.         final double yLow = y - yHigh;
  3499.         final double yyLow = squareLow(yLow, yHigh, yy);
  3500.         // Dekker add2
  3501.         final double r = xx + yy;
  3502.         // Note: The order is important. Assume xx > yy and drop Dekker's conditional
  3503.         // check for which is the greater magnitude.
  3504.         // s = xx - r + yy + yyLow + xxLow
  3505.         // z = r + s
  3506.         // zz = r - z + s
  3507.         // Here we compute z inline and ignore computing the round-off zz.
  3508.         // Note: The round-off could be used with Dekker's sqrt2 method.
  3509.         // That adds 7 multiply, 1 division and 19 additions doubling the cost
  3510.         // and reducing error to < 0.5 ulp for the final sqrt.
  3511.         return xx - r + yy + yyLow + xxLow + r;
  3512.     }
  3513. }