DD.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.core;

  18. import java.io.Serializable;
  19. import java.math.BigDecimal;
  20. import java.util.function.DoubleUnaryOperator;

  21. /**
  22.  * Computes double-double floating-point operations.
  23.  *
  24.  * <p>A double-double is an unevaluated sum of two IEEE double precision numbers capable of
  25.  * representing at least 106 bits of significand. A normalized double-double number {@code (x, xx)}
  26.  *  satisfies the condition that the parts are non-overlapping in magnitude such that:
  27.  * <pre>
  28.  * |x| &gt; |xx|
  29.  * x == x + xx
  30.  * </pre>
  31.  *
  32.  * <p>This implementation assumes a normalized representation during operations on a {@code DD}
  33.  * number and computes results as a normalized representation. Any double-double number
  34.  * can be normalized by summation of the parts (see {@link #ofSum(double, double) ofSum}).
  35.  * Note that the number {@code (x, xx)} may also be referred to using the labels high and low
  36.  * to indicate the magnitude of the parts as
  37.  * {@code (x}<sub>hi</sub>{@code , x}<sub>lo</sub>{@code )}, or using a numerical suffix for the
  38.  * parts as {@code (x}<sub>0</sub>{@code , x}<sub>1</sub>{@code )}. The numerical suffix is
  39.  * typically used when the number has an arbitrary number of parts.
  40.  *
  41.  * <p>The double-double class is immutable.
  42.  *
  43.  * <p><b>Construction</b>
  44.  *
  45.  * <p>Factory methods to create a {@code DD} that are exact use the prefix {@code of}. Methods
  46.  * that create the closest possible representation use the prefix {@code from}. These methods
  47.  * may suffer a possible loss of precision during conversion.
  48.  *
  49.  * <p>Primitive values of type {@code double}, {@code int} and {@code long} are
  50.  * converted exactly to a {@code DD}.
  51.  *
  52.  * <p>The {@code DD} class can also be created as the result of an arithmetic operation on a pair
  53.  * of {@code double} operands. The resulting {@code DD} has the IEEE754 {@code double} result
  54.  * of the operation in the first part, and the second part contains the round-off lost from the
  55.  * operation due to rounding. Construction using add ({@code +}), subtract ({@code -}) and
  56.  * multiply ({@code *}) operators are exact. Construction using division ({@code /}) may be
  57.  * inexact if the quotient is not representable.
  58.  *
  59.  * <p>Note that it is more efficient to create a {@code DD} from a {@code double} operation than
  60.  * to create two {@code DD} values and combine them with the same operation. The result will be
  61.  * the same for add, subtract and multiply but may lose precision for divide.
  62.  * <pre>{@code
  63.  * // Inefficient
  64.  * DD a = DD.of(1.23).add(DD.of(4.56));
  65.  * // Optimal
  66.  * DD b = DD.ofSum(1.23, 4.56);
  67.  *
  68.  * // Inefficient and may lose precision
  69.  * DD c = DD.of(1.23).divide(DD.of(4.56));
  70.  * // Optimal
  71.  * DD d = DD.fromQuotient(1.23, 4.56);
  72.  * }</pre>
  73.  *
  74.  * <p>It is not possible to directly specify the two parts of the number.
  75.  * The two parts must be added using {@link #ofSum(double, double) ofSum}.
  76.  * If the two parts already represent a number {@code (x, xx)} such that {@code x == x + xx}
  77.  * then the magnitudes of the parts will be unchanged; any signed zeros may be subject to a sign
  78.  * change.
  79.  *
  80.  * <p><b>Primitive operands</b>
  81.  *
  82.  * <p>Operations are provided using a {@code DD} operand or a {@code double} operand.
  83.  * Implicit type conversion allows methods with a {@code double} operand to be used
  84.  * with other primitives such as {@code int} or {@code long}. Note that casting of a {@code long}
  85.  * to a {@code double} may result in loss of precision.
  86.  * To maintain the full precision of a {@code long} first convert the value to a {@code DD} using
  87.  * {@link #of(long)} and use the same arithmetic operation using the {@code DD} operand.
  88.  *
  89.  * <p><b>Accuracy</b>
  90.  *
  91.  * <p>Add and multiply operations using two {@code double} values operands are computed to an
  92.  * exact {@code DD} result (see {@link #ofSum(double, double) ofSum} and
  93.  * {@link #ofProduct(double, double) ofProduct}). Operations involving a {@code DD} and another
  94.  * operand, either {@code double} or {@code DD}, are not exact.
  95.  *
  96.  * <p>This class is not intended to perform exact arithmetic. Arbitrary precision arithmetic is
  97.  * available using {@link BigDecimal}. Single operations will compute the {@code DD} result within
  98.  * a tolerance of the 106-bit exact result. This far exceeds the accuracy of {@code double}
  99.  * arithmetic. The reduced accuracy is a compromise to deliver increased performance.
  100.  * The class is intended to reduce error in equivalent {@code double} arithmetic operations where
  101.  * the {@code double} valued result is required to high accuracy. Although it
  102.  * is possible to reduce error to 2<sup>-106</sup> for all operations, the additional computation
  103.  * would impact performance and would require multiple chained operations to potentially
  104.  * observe a different result when the final {@code DD} is converted to a {@code double}.
  105.  *
  106.  * <p><b>Canonical representation</b>
  107.  *
  108.  * <p>The double-double number is the sum of its parts. The canonical representation of the
  109.  * number is the explicit value of the parts. The {@link #toString()} method is provided to
  110.  * convert to a String representation of the parts formatted as a tuple.
  111.  *
  112.  * <p>The class implements {@link #equals(Object)} and {@link #hashCode()} and allows usage as
  113.  * a key in a Set or Map. Equality requires <em>binary</em> equivalence of the parts. Note that
  114.  * representations of zero using different combinations of +/- 0.0 are not considered equal.
  115.  * Also note that many non-normalized double-double numbers can represent the same number.
  116.  * Double-double numbers can be normalized before operations that involve {@link #equals(Object)}
  117.  * by {@link #ofSum(double, double) adding} the parts; this is exact for a finite sum
  118.  * and provides equality support for non-zero numbers. Alternatively exact numerical equality
  119.  * and comparisons are supported by conversion to a {@link #bigDecimalValue() BigDecimal}
  120.  * representation. Note that {@link BigDecimal} does not support non-finite values.
  121.  *
  122.  * <p><b>Overflow, underflow and non-finite support</b>
  123.  *
  124.  * <p>A double-double number is limited to the same finite range as a {@code double}
  125.  * ({@value Double#MIN_VALUE} to {@value Double#MAX_VALUE}). This class is intended for use when
  126.  * the ultimate result is finite and intermediate values do not approach infinity or zero.
  127.  *
  128.  * <p>This implementation does not support IEEE standards for handling infinite and NaN when used
  129.  * in arithmetic operations. Computations may split a 64-bit double into two parts and/or use
  130.  * subtraction of intermediate terms to compute round-off parts. These operations may generate
  131.  * infinite values due to overflow which then propagate through further operations to NaN,
  132.  * for example computing the round-off using {@code Inf - Inf = NaN}.
  133.  *
  134.  * <p>Operations that involve splitting a double (multiply, divide) are safe
  135.  * when the base 2 exponent is below 996. This puts an upper limit of approximately +/-6.7e299 on
  136.  * any values to be split; in practice the arguments to multiply and divide operations are further
  137.  * constrained by the expected finite value of the product or quotient.
  138.  *
  139.  * <p>Likewise the smallest value that can be represented is {@link Double#MIN_VALUE}. The full
  140.  * 106-bit accuracy will be lost when intermediates are within 2<sup>53</sup> of
  141.  * {@link Double#MIN_NORMAL}.
  142.  *
  143.  * <p>The {@code DD} result can be verified by checking it is a {@link #isFinite() finite}
  144.  * evaluated sum. Computations expecting to approach over or underflow must use scaling of
  145.  * intermediate terms (see {@link #frexp(int[]) frexp} and {@link #scalb(int) scalb}) and
  146.  * appropriate management of the current base 2 scale.
  147.  *
  148.  * <p>References:
  149.  * <ol>
  150.  * <li>
  151.  * Dekker, T.J. (1971)
  152.  * <a href="https://doi.org/10.1007/BF01397083">
  153.  * A floating-point technique for extending the available precision</a>
  154.  * Numerische Mathematik, 18:224–242.
  155.  * <li>
  156.  * Shewchuk, J.R. (1997)
  157.  * <a href="https://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
  158.  * Arbitrary Precision Floating-Point Arithmetic</a>.
  159.  * <li>
  160.  * Hide, Y, Li, X.S. and Bailey, D.H. (2008)
  161.  * <a href="https://www.davidhbailey.com/dhbpapers/qd.pdf">
  162.  * Library for Double-Double and Quad-Double Arithmetic</a>.
  163.  * </ol>
  164.  *
  165.  * @since 1.2
  166.  */
  167. public final class DD
  168.     extends Number
  169.     implements NativeOperators<DD>,
  170.                Serializable {
  171.     // Caveat:
  172.     //
  173.     // The code below uses many additions/subtractions that may
  174.     // appear redundant. However, they should NOT be simplified, as they
  175.     // do use IEEE754 floating point arithmetic rounding properties.
  176.     //
  177.     // Algorithms are based on computing the product or sum of two values x and y in
  178.     // extended precision. The standard result is stored using a double (high part z) and
  179.     // the round-off error (or low part zz) is stored in a second double, e.g:
  180.     // x * y = (z, zz); z + zz = x * y
  181.     // x + y = (z, zz); z + zz = x + y
  182.     //
  183.     // The building blocks for double-double arithmetic are:
  184.     //
  185.     // Fast-Two-Sum: Addition of two doubles (ordered |x| > |y|) to a double-double
  186.     // Two-Sum: Addition of two doubles (unordered) to a double-double
  187.     // Two-Prod: Multiplication of two doubles to a double-double
  188.     //
  189.     // These are used to create functions operating on double and double-double numbers.
  190.     //
  191.     // To sum multiple (z, zz) results ideally the parts are sorted in order of
  192.     // non-decreasing magnitude and summed. This is exact if each number's most significant
  193.     // bit is below the least significant bit of the next (i.e. does not
  194.     // overlap). Creating non-overlapping parts requires a rebalancing
  195.     // of adjacent pairs using a summation z + zz = (z1, zz1) iteratively through the parts
  196.     // (see Shewchuk (1997) Grow-Expansion and Expansion-Sum [2]).
  197.     //
  198.     // Accurate summation of an expansion (more than one double value) to a double-double
  199.     // performs a two-sum through the expansion e (length m).
  200.     // The single pass with two-sum ensures that the final term e_m is a good approximation
  201.     // for e: |e - e_m| < ulp(e_m); and the sum of the parts to
  202.     // e_(m-1) is within 1 ULP of the round-off ulp(|e - e_m|).
  203.     // These final two terms create the double-double result using two-sum.
  204.     //
  205.     // Maintenance of 1 ULP precision in the round-off component for all double-double
  206.     // operations is a performance burden. This class avoids this requirement to provide
  207.     // a compromise between accuracy and performance.

  208.     /**
  209.      * A double-double number representing one.
  210.      */
  211.     public static final DD ONE = new DD(1, 0);
  212.     /**
  213.      * A double-double number representing zero.
  214.      */
  215.     public static final DD ZERO = new DD(0, 0);

  216.     /**
  217.      * The multiplier used to split the double value into high and low parts. From
  218.      * Dekker (1971): "The constant should be chosen equal to 2^(p - p/2) + 1,
  219.      * where p is the number of binary digits in the mantissa". Here p is 53
  220.      * and the multiplier is {@code 2^27 + 1}.
  221.      */
  222.     private static final double MULTIPLIER = 1.0 + 0x1.0p27;
  223.     /** The mask to extract the raw 11-bit exponent.
  224.      * The value must be shifted 52-bits to remove the mantissa bits. */
  225.     private static final int EXP_MASK = 0x7ff;
  226.     /** The value 2046 converted for use if using {@link Integer#compareUnsigned(int, int)}.
  227.      * This requires adding {@link Integer#MIN_VALUE} to 2046. */
  228.     private static final int CMP_UNSIGNED_2046 = Integer.MIN_VALUE + 2046;
  229.     /** The value -1 converted for use if using {@link Integer#compareUnsigned(int, int)}.
  230.      * This requires adding {@link Integer#MIN_VALUE} to -1. */
  231.     private static final int CMP_UNSIGNED_MINUS_1 = Integer.MIN_VALUE - 1;
  232.     /** The value 1022 converted for use if using {@link Integer#compareUnsigned(int, int)}.
  233.      * This requires adding {@link Integer#MIN_VALUE} to 1022. */
  234.     private static final int CMP_UNSIGNED_1022 = Integer.MIN_VALUE + 1022;
  235.     /** 2^512. */
  236.     private static final double TWO_POW_512 = 0x1.0p512;
  237.     /** 2^-512. */
  238.     private static final double TWO_POW_M512 = 0x1.0p-512;
  239.     /** 2^53. Any double with a magnitude above this is an even integer. */
  240.     private static final double TWO_POW_53 = 0x1.0p53;
  241.     /** Mask to extract the high 32-bits from a long. */
  242.     private static final long HIGH32_MASK = 0xffff_ffff_0000_0000L;
  243.     /** Mask to remove the sign bit from a long. */
  244.     private static final long UNSIGN_MASK = 0x7fff_ffff_ffff_ffffL;
  245.     /** Mask to extract the 52-bit mantissa from a long representation of a double. */
  246.     private static final long MANTISSA_MASK = 0x000f_ffff_ffff_ffffL;
  247.     /** Exponent offset in IEEE754 representation. */
  248.     private static final int EXPONENT_OFFSET = 1023;
  249.     /** 0.5. */
  250.     private static final double HALF = 0.5;
  251.     /** The limit for safe multiplication of {@code x*y}, assuming values above 1.
  252.      * Used to maintain positive values during the power computation. */
  253.     private static final double SAFE_MULTIPLY = 0x1.0p500;

  254.     /**
  255.      * The size of the buffer for {@link #toString()}.
  256.      *
  257.      * <p>The longest double will require a sign, a maximum of 17 digits, the decimal place
  258.      * and the exponent, e.g. for max value this is 24 chars: -1.7976931348623157e+308.
  259.      * Set the buffer size to twice this and round up to a power of 2 thus
  260.      * allowing for formatting characters. The size is 64.
  261.      */
  262.     private static final int TO_STRING_SIZE = 64;
  263.     /** {@link #toString() String representation}. */
  264.     private static final char FORMAT_START = '(';
  265.     /** {@link #toString() String representation}. */
  266.     private static final char FORMAT_END = ')';
  267.     /** {@link #toString() String representation}. */
  268.     private static final char FORMAT_SEP = ',';

  269.     /** Serializable version identifier. */
  270.     private static final long serialVersionUID = 20230701L;

  271.     /** The high part of the double-double number. */
  272.     private final double x;
  273.     /** The low part of the double-double number. */
  274.     private final double xx;

  275.     /**
  276.      * Create a double-double number {@code (x, xx)}.
  277.      *
  278.      * @param x High part.
  279.      * @param xx Low part.
  280.      */
  281.     private DD(double x, double xx) {
  282.         this.x = x;
  283.         this.xx = xx;
  284.     }

  285.     // Conversion constructors

  286.     /**
  287.      * Creates the double-double number as the value {@code (x, 0)}.
  288.      *
  289.      * @param x Value.
  290.      * @return the double-double
  291.      */
  292.     public static DD of(double x) {
  293.         return new DD(x, 0);
  294.     }

  295.     /**
  296.      * Creates the double-double number as the value {@code (x, xx)}.
  297.      *
  298.      * <p><strong>Warning</strong>
  299.      *
  300.      * <p>The arguments are used directly. No checks are made that they represent
  301.      * a normalized double-double number: {@code x == x + xx}.
  302.      *
  303.      * <p>This method is exposed for testing.
  304.      *
  305.      * @param x High part.
  306.      * @param xx Low part.
  307.      * @return the double-double
  308.      * @see #twoSum(double, double)
  309.      */
  310.     static DD of(double x, double xx) {
  311.         return new DD(x, xx);
  312.     }

  313.     /**
  314.      * Creates the double-double number as the value {@code (x, 0)}.
  315.      *
  316.      * <p>Note this method exists to avoid using {@link #of(long)} for {@code integer}
  317.      * arguments; the {@code long} variation is slower as it preserves all 64-bits
  318.      * of information.
  319.      *
  320.      * @param x Value.
  321.      * @return the double-double
  322.      * @see #of(long)
  323.      */
  324.     public static DD of(int x) {
  325.         return new DD(x, 0);
  326.     }

  327.     /**
  328.      * Creates the double-double number with the high part equal to {@code (double) x}
  329.      * and the low part equal to any remaining bits.
  330.      *
  331.      * <p>Note this method preserves all 64-bits of precision. Faster construction can be
  332.      * achieved using up to 53-bits of precision using {@code of((double) x)}.
  333.      *
  334.      * @param x Value.
  335.      * @return the double-double
  336.      * @see #of(double)
  337.      */
  338.     public static DD of(long x) {
  339.         // Note: Casting the long to a double can lose bits due to rounding.
  340.         // These are not recoverable using lo = x - (long)((double) x)
  341.         // if the double is rounded outside the range of a long (i.e. 2^53).
  342.         // Split the long into two 32-bit numbers that are exactly representable
  343.         // and add them.
  344.         final long a = x & HIGH32_MASK;
  345.         final long b = x - a;
  346.         // When x is positive: a > b or a == 0
  347.         // When x is negative: |a| > |b|
  348.         return fastTwoSum(a, b);
  349.     }

  350.     /**
  351.      * Creates the double-double number {@code (z, zz)} using the {@code double} representation
  352.      * of the argument {@code x}; the low part is the {@code double} representation of the
  353.      * round-off error.
  354.      * <pre>
  355.      * double z = x.doubleValue();
  356.      * double zz = x.subtract(new BigDecimal(z)).doubleValue();
  357.      * </pre>
  358.      * <p>If the value cannot be represented as a finite value the result will have an
  359.      * infinite high part and the low part is undefined.
  360.      *
  361.      * <p>Note: This conversion can lose information about the precision of the BigDecimal value.
  362.      * The result is the closest double-double representation to the value.
  363.      *
  364.      * @param x Value.
  365.      * @return the double-double
  366.      */
  367.     public static DD from(BigDecimal x) {
  368.         final double z = x.doubleValue();
  369.         // Guard against an infinite throwing a exception
  370.         final double zz = Double.isInfinite(z) ? 0 : x.subtract(new BigDecimal(z)).doubleValue();
  371.         // No normalisation here
  372.         return new DD(z, zz);
  373.     }

  374.     // Arithmetic constructors:

  375.     /**
  376.      * Returns a {@code DD} whose value is {@code (x + y)}.
  377.      * The values are not required to be ordered by magnitude,
  378.      * i.e. the result is commutative: {@code x + y == y + x}.
  379.      *
  380.      * <p>This method ignores special handling of non-normal numbers and
  381.      * overflow within the extended precision computation.
  382.      * This creates the following special cases:
  383.      *
  384.      * <ul>
  385.      *  <li>If {@code x + y} is infinite then the low part is NaN.
  386.      *  <li>If {@code x} or {@code y} is infinite or NaN then the low part is NaN.
  387.      *  <li>If {@code x + y} is sub-normal or zero then the low part is +/-0.0.
  388.      * </ul>
  389.      *
  390.      * <p>An invalid result can be identified using {@link #isFinite()}.
  391.      *
  392.      * <p>The result is the exact double-double representation of the sum.
  393.      *
  394.      * @param x Addend.
  395.      * @param y Addend.
  396.      * @return the sum {@code x + y}.
  397.      * @see #ofDifference(double, double)
  398.      */
  399.     public static DD ofSum(double x, double y) {
  400.         return twoSum(x, y);
  401.     }

  402.     /**
  403.      * Returns a {@code DD} whose value is {@code (x - y)}.
  404.      * The values are not required to be ordered by magnitude,
  405.      * i.e. the result matches a negation and addition: {@code x - y == -y + x}.
  406.      *
  407.      * <p>Computes the same results as {@link #ofSum(double, double) ofSum(a, -b)}.
  408.      * See that method for details of special cases.
  409.      *
  410.      * <p>An invalid result can be identified using {@link #isFinite()}.
  411.      *
  412.      * <p>The result is the exact double-double representation of the difference.
  413.      *
  414.      * @param x Minuend.
  415.      * @param y Subtrahend.
  416.      * @return {@code x - y}.
  417.      * @see #ofSum(double, double)
  418.      */
  419.     public static DD ofDifference(double x, double y) {
  420.         return twoDiff(x, y);
  421.     }

  422.     /**
  423.      * Returns a {@code DD} whose value is {@code (x * y)}.
  424.      *
  425.      * <p>This method ignores special handling of non-normal numbers and intermediate
  426.      * overflow within the extended precision computation.
  427.      * This creates the following special cases:
  428.      *
  429.      * <ul>
  430.      *  <li>If either {@code |x|} or {@code |y|} multiplied by {@code 1 + 2^27}
  431.      *      is infinite (intermediate overflow) then the low part is NaN.
  432.      *  <li>If {@code x * y} is infinite then the low part is NaN.
  433.      *  <li>If {@code x} or {@code y} is infinite or NaN then the low part is NaN.
  434.      *  <li>If {@code x * y} is sub-normal or zero then the low part is +/-0.0.
  435.      * </ul>
  436.      *
  437.      * <p>An invalid result can be identified using {@link #isFinite()}.
  438.      *
  439.      * <p>Note: Ignoring special cases is a design choice for performance. The
  440.      * method is therefore not a drop-in replacement for
  441.      * {@code roundOff = Math.fma(x, y, -x * y)}.
  442.      *
  443.      * <p>The result is the exact double-double representation of the product.
  444.      *
  445.      * @param x Factor.
  446.      * @param y Factor.
  447.      * @return the product {@code x * y}.
  448.      */
  449.     public static DD ofProduct(double x, double y) {
  450.         return twoProd(x, y);
  451.     }

  452.     /**
  453.      * Returns a {@code DD} whose value is {@code (x * x)}.
  454.      *
  455.      * <p>This method is an optimisation of {@link #ofProduct(double, double) multiply(x, x)}.
  456.      * See that method for details of special cases.
  457.      *
  458.      * <p>An invalid result can be identified using {@link #isFinite()}.
  459.      *
  460.      * <p>The result is the exact double-double representation of the square.
  461.      *
  462.      * @param x Factor.
  463.      * @return the square {@code x * x}.
  464.      * @see #ofProduct(double, double)
  465.      */
  466.     public static DD ofSquare(double x) {
  467.         return twoSquare(x);
  468.     }

  469.     /**
  470.      * Returns a {@code DD} whose value is {@code (x / y)}.
  471.      * If {@code y = 0} the result is undefined.
  472.      *
  473.      * <p>This method ignores special handling of non-normal numbers and intermediate
  474.      * overflow within the extended precision computation.
  475.      * This creates the following special cases:
  476.      *
  477.      * <ul>
  478.      *  <li>If either {@code |x / y|} or {@code |y|} multiplied by {@code 1 + 2^27}
  479.      *      is infinite (intermediate overflow) then the low part is NaN.
  480.      *  <li>If {@code x / y} is infinite then the low part is NaN.
  481.      *  <li>If {@code x} or {@code y} is infinite or NaN then the low part is NaN.
  482.      *  <li>If {@code x / y} is sub-normal or zero, excluding the previous cases,
  483.      *      then the low part is +/-0.0.
  484.      * </ul>
  485.      *
  486.      * <p>An invalid result can be identified using {@link #isFinite()}.
  487.      *
  488.      * <p>The result is the closest double-double representation to the quotient.
  489.      *
  490.      * @param x Dividend.
  491.      * @param y Divisor.
  492.      * @return the quotient {@code x / y}.
  493.      */
  494.     public static DD fromQuotient(double x, double y) {
  495.         // Long division
  496.         // quotient q0 = x / y
  497.         final double q0 = x / y;
  498.         // remainder r = x - q0 * y
  499.         final double p0 = q0 * y;
  500.         final double p1 = twoProductLow(q0, y, p0);
  501.         final double r0 = x - p0;
  502.         final double r1 = twoDiffLow(x, p0, r0) - p1;
  503.         // correction term q1 = r0 / y
  504.         final double q1 = (r0 + r1) / y;
  505.         return new DD(q0, q1);
  506.     }

  507.     // Properties

  508.     /**
  509.      * Gets the first part {@code x} of the double-double number {@code (x, xx)}.
  510.      * In a normalized double-double number this part will have the greatest magnitude.
  511.      *
  512.      * <p>This is equivalent to returning the high-part {@code x}<sub>hi</sub> for the number
  513.      * {@code (x}<sub>hi</sub>{@code , x}<sub>lo</sub>{@code )}.
  514.      *
  515.      * @return the first part
  516.      */
  517.     public double hi() {
  518.         return x;
  519.     }

  520.     /**
  521.      * Gets the second part {@code xx} of the double-double number {@code (x, xx)}.
  522.      * In a normalized double-double number this part will have the smallest magnitude.
  523.      *
  524.      * <p>This is equivalent to returning the low part {@code x}<sub>lo</sub> for the number
  525.      * {@code (x}<sub>hi</sub>{@code , x}<sub>lo</sub>{@code )}.
  526.      *
  527.      * @return the second part
  528.      */
  529.     public double lo() {
  530.         return xx;
  531.     }

  532.     /**
  533.      * Returns {@code true} if the evaluated sum of the parts is finite.
  534.      *
  535.      * <p>This method is provided as a utility to check the result of a {@code DD} computation.
  536.      * Note that for performance the {@code DD} class does not follow IEEE754 arithmetic
  537.      * for infinite and NaN, and does not protect from overflow of intermediate values in
  538.      * multiply and divide operations. If this method returns {@code false} following
  539.      * {@code DD} arithmetic then the computation is not supported to extended precision.
  540.      *
  541.      * <p>Note: Any number that returns {@code true} may be converted to the exact
  542.      * {@link BigDecimal} value.
  543.      *
  544.      * @return {@code true} if this instance represents a finite {@code double} value.
  545.      * @see Double#isFinite(double)
  546.      * @see #bigDecimalValue()
  547.      */
  548.     public boolean isFinite() {
  549.         return Double.isFinite(x + xx);
  550.     }

  551.     // Number conversions

  552.     /**
  553.      * Get the value as a {@code double}. This is the evaluated sum of the parts.
  554.      *
  555.      * <p>Note that even when the return value is finite, this conversion can lose
  556.      * information about the precision of the {@code DD} value.
  557.      *
  558.      * <p>Conversion of a finite {@code DD} can also be performed using the
  559.      * {@link #bigDecimalValue() BigDecimal} representation.
  560.      *
  561.      * @return the value converted to a {@code double}
  562.      * @see #bigDecimalValue()
  563.      */
  564.     @Override
  565.     public double doubleValue() {
  566.         return x + xx;
  567.     }

  568.     /**
  569.      * Get the value as a {@code float}. This is the narrowing primitive conversion of the
  570.      * {@link #doubleValue()}. This conversion can lose range, resulting in a
  571.      * {@code float} zero from a nonzero {@code double} and a {@code float} infinity from
  572.      * a finite {@code double}. A {@code double} NaN is converted to a {@code float} NaN
  573.      * and a {@code double} infinity is converted to the same-signed {@code float}
  574.      * infinity.
  575.      *
  576.      * <p>Note that even when the return value is finite, this conversion can lose
  577.      * information about the precision of the {@code DD} value.
  578.      *
  579.      * <p>Conversion of a finite {@code DD} can also be performed using the
  580.      * {@link #bigDecimalValue() BigDecimal} representation.
  581.      *
  582.      * @return the value converted to a {@code float}
  583.      * @see #bigDecimalValue()
  584.      */
  585.     @Override
  586.     public float floatValue() {
  587.         return (float) doubleValue();
  588.     }

  589.     /**
  590.      * Get the value as an {@code int}. This conversion discards the fractional part of the
  591.      * number and effectively rounds the value to the closest whole number in the direction
  592.      * of zero. This is the equivalent of a cast of a floating-point number to an integer, for
  593.      * example {@code (int) -2.75 => -2}.
  594.      *
  595.      * <p>Note that this conversion can lose information about the precision of the
  596.      * {@code DD} value.
  597.      *
  598.      * <p>Special cases:
  599.      * <ul>
  600.      *  <li>If the {@code DD} value is infinite the result is {@link Integer#MAX_VALUE}.
  601.      *  <li>If the {@code DD} value is -infinite the result is {@link Integer#MIN_VALUE}.
  602.      *  <li>If the {@code DD} value is NaN the result is 0.
  603.      * </ul>
  604.      *
  605.      * <p>Conversion of a finite {@code DD} can also be performed using the
  606.      * {@link #bigDecimalValue() BigDecimal} representation. Note that {@link BigDecimal}
  607.      * conversion rounds to the {@link java.math.BigInteger BigInteger} whole number
  608.      * representation and returns the low-order 32-bits. Numbers too large for an {@code int}
  609.      * may change sign. This method ensures the sign is correct by directly rounding to
  610.      * an {@code int} and returning the respective upper or lower limit for numbers too
  611.      * large for an {@code int}.
  612.      *
  613.      * @return the value converted to an {@code int}
  614.      * @see #bigDecimalValue()
  615.      */
  616.     @Override
  617.     public int intValue() {
  618.         // Clip the long value
  619.         return (int) Math.max(Integer.MIN_VALUE, Math.min(Integer.MAX_VALUE, longValue()));
  620.     }

  621.     /**
  622.      * Get the value as a {@code long}. This conversion discards the fractional part of the
  623.      * number and effectively rounds the value to the closest whole number in the direction
  624.      * of zero. This is the equivalent of a cast of a floating-point number to an integer, for
  625.      * example {@code (long) -2.75 => -2}.
  626.      *
  627.      * <p>Note that this conversion can lose information about the precision of the
  628.      * {@code DD} value.
  629.      *
  630.      * <p>Special cases:
  631.      * <ul>
  632.      *  <li>If the {@code DD} value is infinite the result is {@link Long#MAX_VALUE}.
  633.      *  <li>If the {@code DD} value is -infinite the result is {@link Long#MIN_VALUE}.
  634.      *  <li>If the {@code DD} value is NaN the result is 0.
  635.      * </ul>
  636.      *
  637.      * <p>Conversion of a finite {@code DD} can also be performed using the
  638.      * {@link #bigDecimalValue() BigDecimal} representation. Note that {@link BigDecimal}
  639.      * conversion rounds to the {@link java.math.BigInteger BigInteger} whole number
  640.      * representation and returns the low-order 64-bits. Numbers too large for a {@code long}
  641.      * may change sign. This method ensures the sign is correct by directly rounding to
  642.      * a {@code long} and returning the respective upper or lower limit for numbers too
  643.      * large for a {@code long}.
  644.      *
  645.      * @return the value converted to an {@code int}
  646.      * @see #bigDecimalValue()
  647.      */
  648.     @Override
  649.     public long longValue() {
  650.         // Assume |hi| > |lo|, i.e. the low part is the round-off
  651.         final long a = (long) x;
  652.         // The cast will truncate the value to the range [Long.MIN_VALUE, Long.MAX_VALUE].
  653.         // If the long converted back to a double is the same value then the high part
  654.         // was a representable integer and we must use the low part.
  655.         // Note: The floating-point comparison is intentional.
  656.         if (a == x) {
  657.             // Edge case: Any double value above 2^53 is even. To workaround representation
  658.             // of 2^63 as Long.MAX_VALUE (which is 2^63-1) we can split a into two parts.
  659.             long a1;
  660.             long a2;
  661.             if (Math.abs(x) > TWO_POW_53) {
  662.                 a1 = (long) (x * 0.5);
  663.                 a2 = a1;
  664.             } else {
  665.                 a1 = a;
  666.                 a2 = 0;
  667.             }

  668.             // To truncate the fractional part of the double-double towards zero we
  669.             // convert the low part to a whole number. This must be rounded towards zero
  670.             // with respect to the sign of the high part.
  671.             final long b = (long) (a < 0 ? Math.ceil(xx) : Math.floor(xx));

  672.             final long sum = a1 + b + a2;
  673.             // Avoid overflow. If the sum has changed sign then an overflow occurred.
  674.             // This happens when high == 2^63 and the low part is additional magnitude.
  675.             // The xor operation creates a negative if the signs are different.
  676.             if ((sum ^ a) >= 0) {
  677.                 return sum;
  678.             }
  679.         }
  680.         // Here the high part had a fractional part, was non-finite or was 2^63.
  681.         // Ignore the low part.
  682.         return a;
  683.     }

  684.     /**
  685.      * Get the value as a {@code BigDecimal}. This is the evaluated sum of the parts;
  686.      * the conversion is exact.
  687.      *
  688.      * <p>The conversion will raise a {@link NumberFormatException} if the number
  689.      * is non-finite.
  690.      *
  691.      * @return the double-double as a {@code BigDecimal}.
  692.      * @throws NumberFormatException if any part of the number is {@code infinite} or {@code NaN}
  693.      * @see BigDecimal
  694.      */
  695.     public BigDecimal bigDecimalValue() {
  696.         return new BigDecimal(x).add(new BigDecimal(xx));
  697.     }

  698.     // Static extended precision methods for computing the round-off component
  699.     // for double addition and multiplication

  700.     /**
  701.      * Compute the sum of two numbers {@code a} and {@code b} using
  702.      * Dekker's two-sum algorithm. The values are required to be ordered by magnitude:
  703.      * {@code |a| >= |b|}.
  704.      *
  705.      * <p>If {@code a} is zero and {@code b} is non-zero the returned value is {@code (b, 0)}.
  706.      *
  707.      * @param a First part of sum.
  708.      * @param b Second part of sum.
  709.      * @return the sum
  710.      * @see #fastTwoDiff(double, double)
  711.      * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
  712.      * Shewchuk (1997) Theorum 6</a>
  713.      */
  714.     static DD fastTwoSum(double a, double b) {
  715.         final double x = a + b;
  716.         return new DD(x, fastTwoSumLow(a, b, x));
  717.     }

  718.     /**
  719.      * Compute the round-off of the sum of two numbers {@code a} and {@code b} using
  720.      * Dekker's two-sum algorithm. The values are required to be ordered by magnitude:
  721.      * {@code |a| >= |b|}.
  722.      *
  723.      * <p>If {@code a} is zero and {@code b} is non-zero the returned value is zero.
  724.      *
  725.      * @param a First part of sum.
  726.      * @param b Second part of sum.
  727.      * @param x Sum.
  728.      * @return the sum round-off
  729.      * @see #fastTwoSum(double, double)
  730.      */
  731.     static double fastTwoSumLow(double a, double b, double x) {
  732.         // (x, xx) = a + b
  733.         // bVirtual = x - a
  734.         // xx = b - bVirtual
  735.         return b - (x - a);
  736.     }

  737.     /**
  738.      * Compute the difference of two numbers {@code a} and {@code b} using
  739.      * Dekker's two-sum algorithm. The values are required to be ordered by magnitude:
  740.      * {@code |a| >= |b|}.
  741.      *
  742.      * <p>Computes the same results as {@link #fastTwoSum(double, double) fastTwoSum(a, -b)}.
  743.      *
  744.      * @param a Minuend.
  745.      * @param b Subtrahend.
  746.      * @return the difference
  747.      * @see #fastTwoSum(double, double)
  748.      * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
  749.      * Shewchuk (1997) Theorum 6</a>
  750.      */
  751.     static DD fastTwoDiff(double a, double b) {
  752.         final double x = a - b;
  753.         return new DD(x, fastTwoDiffLow(a, b, x));
  754.     }

  755.     /**
  756.      * Compute the round-off of the difference of two numbers {@code a} and {@code b} using
  757.      * Dekker's two-sum algorithm. The values are required to be ordered by magnitude:
  758.      * {@code |a| >= |b|}.
  759.      *
  760.      * @param a Minuend.
  761.      * @param b Subtrahend.
  762.      * @param x Difference.
  763.      * @return the difference round-off
  764.      * @see #fastTwoDiff(double, double)
  765.      */
  766.     private static double fastTwoDiffLow(double a, double b, double x) {
  767.         // (x, xx) = a - b
  768.         // bVirtual = a - x
  769.         // xx = bVirtual - b
  770.         return (a - x) - b;
  771.     }

  772.     /**
  773.      * Compute the sum of two numbers {@code a} and {@code b} using
  774.      * Knuth's two-sum algorithm. The values are not required to be ordered by magnitude,
  775.      * i.e. the result is commutative {@code s = a + b == b + a}.
  776.      *
  777.      * @param a First part of sum.
  778.      * @param b Second part of sum.
  779.      * @return the sum
  780.      * @see #twoDiff(double, double)
  781.      * @see <a href="http://www-2.cs.cmu.edu/afs/cs/project/quake/public/papers/robust-arithmetic.ps">
  782.      * Shewchuk (1997) Theorum 7</a>
  783.      */
  784.     static DD twoSum(double a, double b) {
  785.         final double x = a + b;
  786.         return new DD(x, twoSumLow(a, b, x));
  787.     }

  788.     /**
  789.      * Compute the round-off of the sum of two numbers {@code a} and {@code b} using
  790.      * Knuth two-sum algorithm. The values are not required to be ordered by magnitude,
  791.      * i.e. the result is commutative {@code s = a + b == b + a}.
  792.      *
  793.      * @param a First part of sum.
  794.      * @param b Second part of sum.
  795.      * @param x Sum.
  796.      * @return the sum round-off
  797.      * @see #twoSum(double, double)
  798.      */
  799.     static double twoSumLow(double a, double b, double x) {
  800.         // (x, xx) = a + b
  801.         // bVirtual = x - a
  802.         // aVirtual = x - bVirtual
  803.         // bRoundoff = b - bVirtual
  804.         // aRoundoff = a - aVirtual
  805.         // xx = aRoundoff + bRoundoff
  806.         final double bVirtual = x - a;
  807.         return (a - (x - bVirtual)) + (b - bVirtual);
  808.     }

  809.     /**
  810.      * Compute the difference of two numbers {@code a} and {@code b} using
  811.      * Knuth's two-sum algorithm. The values are not required to be ordered by magnitude.
  812.      *
  813.      * <p>Computes the same results as {@link #twoSum(double, double) twoSum(a, -b)}.
  814.      *
  815.      * @param a Minuend.
  816.      * @param b Subtrahend.
  817.      * @return the difference
  818.      * @see #twoSum(double, double)
  819.      */
  820.     static DD twoDiff(double a, double b) {
  821.         final double x = a - b;
  822.         return new DD(x, twoDiffLow(a, b, x));
  823.     }

  824.     /**
  825.      * Compute the round-off of the difference of two numbers {@code a} and {@code b} using
  826.      * Knuth two-sum algorithm. The values are not required to be ordered by magnitude,
  827.      *
  828.      * @param a Minuend.
  829.      * @param b Subtrahend.
  830.      * @param x Difference.
  831.      * @return the difference round-off
  832.      * @see #twoDiff(double, double)
  833.      */
  834.     private static double twoDiffLow(double a, double b, double x) {
  835.         // (x, xx) = a - b
  836.         // bVirtual = a - x
  837.         // aVirtual = x + bVirtual
  838.         // bRoundoff = b - bVirtual
  839.         // aRoundoff = a - aVirtual
  840.         // xx = aRoundoff - bRoundoff
  841.         final double bVirtual = a - x;
  842.         return (a - (x + bVirtual)) - (b - bVirtual);
  843.     }

  844.     /**
  845.      * Compute the double-double number {@code (z,zz)} for the exact
  846.      * product of {@code x} and {@code y}.
  847.      *
  848.      * <p>The high part of the number is equal to the product {@code z = x * y}.
  849.      * The low part is set to the round-off of the {@code double} product.
  850.      *
  851.      * <p>This method ignores special handling of non-normal numbers and intermediate
  852.      * overflow within the extended precision computation.
  853.      * This creates the following special cases:
  854.      *
  855.      * <ul>
  856.      *  <li>If {@code x * y} is sub-normal or zero then the low part is +/-0.0.
  857.      *  <li>If {@code x * y} is infinite then the low part is NaN.
  858.      *  <li>If {@code x} or {@code y} is infinite or NaN then the low part is NaN.
  859.      *  <li>If either {@code |x|} or {@code |y|} multiplied by {@code 1 + 2^27}
  860.      *      is infinite (intermediate overflow) then the low part is NaN.
  861.      * </ul>
  862.      *
  863.      * <p>Note: Ignoring special cases is a design choice for performance. The
  864.      * method is therefore not a drop-in replacement for
  865.      * {@code round_off = Math.fma(x, y, -x * y)}.
  866.      *
  867.      * @param x First factor.
  868.      * @param y Second factor.
  869.      * @return the product
  870.      */
  871.     static DD twoProd(double x, double y) {
  872.         final double xy = x * y;
  873.         // No checks for non-normal xy, or overflow during the split of the arguments
  874.         return new DD(xy, twoProductLow(x, y, xy));
  875.     }

  876.     /**
  877.      * Compute the low part of the double length number {@code (z,zz)} for the exact
  878.      * product of {@code x} and {@code y} using Dekker's mult12 algorithm. The standard
  879.      * precision product {@code x*y} must be provided. The numbers {@code x} and {@code y}
  880.      * are split into high and low parts using Dekker's algorithm.
  881.      *
  882.      * <p>Warning: This method does not perform scaling in Dekker's split and large
  883.      * finite numbers can create NaN results.
  884.      *
  885.      * @param x First factor.
  886.      * @param y Second factor.
  887.      * @param xy Product of the factors (x * y).
  888.      * @return the low part of the product double length number
  889.      * @see #highPart(double)
  890.      */
  891.     static double twoProductLow(double x, double y, double xy) {
  892.         // Split the numbers using Dekker's algorithm without scaling
  893.         final double hx = highPart(x);
  894.         final double lx = x - hx;
  895.         final double hy = highPart(y);
  896.         final double ly = y - hy;
  897.         return twoProductLow(hx, lx, hy, ly, xy);
  898.     }

  899.     /**
  900.      * Compute the low part of the double length number {@code (z,zz)} for the exact
  901.      * product of {@code x} and {@code y} using Dekker's mult12 algorithm. The standard
  902.      * precision product {@code x*y}, and the high and low parts of the factors must be
  903.      * provided.
  904.      *
  905.      * @param hx High-part of first factor.
  906.      * @param lx Low-part of first factor.
  907.      * @param hy High-part of second factor.
  908.      * @param ly Low-part of second factor.
  909.      * @param xy Product of the factors (x * y).
  910.      * @return the low part of the product double length number
  911.      */
  912.     static double twoProductLow(double hx, double lx, double hy, double ly, double xy) {
  913.         // Compute the multiply low part:
  914.         // err1 = xy - hx * hy
  915.         // err2 = err1 - lx * hy
  916.         // err3 = err2 - hx * ly
  917.         // low = lx * ly - err3
  918.         return lx * ly - (((xy - hx * hy) - lx * hy) - hx * ly);
  919.     }

  920.     /**
  921.      * Compute the double-double number {@code (z,zz)} for the exact
  922.      * square of {@code x}.
  923.      *
  924.      * <p>The high part of the number is equal to the square {@code z = x * x}.
  925.      * The low part is set to the round-off of the {@code double} square.
  926.      *
  927.      * <p>This method is an optimisation of {@link #twoProd(double, double) twoProd(x, x)}.
  928.      * See that method for details of special cases.
  929.      *
  930.      * @param x Factor.
  931.      * @return the square
  932.      * @see #twoProd(double, double)
  933.      */
  934.     static DD twoSquare(double x) {
  935.         final double xx = x * x;
  936.         // No checks for non-normal xy, or overflow during the split of the arguments
  937.         return new DD(xx, twoSquareLow(x, xx));
  938.     }

  939.     /**
  940.      * Compute the low part of the double length number {@code (z,zz)} for the exact
  941.      * square of {@code x} using Dekker's mult12 algorithm. The standard
  942.      * precision square {@code x*x} must be provided. The number {@code x}
  943.      * is split into high and low parts using Dekker's algorithm.
  944.      *
  945.      * <p>Warning: This method does not perform scaling in Dekker's split and large
  946.      * finite numbers can create NaN results.
  947.      *
  948.      * @param x Factor.
  949.      * @param x2 Square of the factor (x * x).
  950.      * @return the low part of the square double length number
  951.      * @see #highPart(double)
  952.      * @see #twoProductLow(double, double, double)
  953.      */
  954.     static double twoSquareLow(double x, double x2) {
  955.         // See productLowUnscaled
  956.         final double hx = highPart(x);
  957.         final double lx = x - hx;
  958.         return twoSquareLow(hx, lx, x2);
  959.     }

  960.     /**
  961.      * Compute the low part of the double length number {@code (z,zz)} for the exact
  962.      * square of {@code x} using Dekker's mult12 algorithm. The standard
  963.      * precision square {@code x*x}, and the high and low parts of the factors must be
  964.      * provided.
  965.      *
  966.      * @param hx High-part of factor.
  967.      * @param lx Low-part of factor.
  968.      * @param x2 Square of the factor (x * x).
  969.      * @return the low part of the square double length number
  970.      */
  971.     static double twoSquareLow(double hx, double lx, double x2) {
  972.         return lx * lx - ((x2 - hx * hx) - 2 * lx * hx);
  973.     }

  974.     /**
  975.      * Implement Dekker's method to split a value into two parts. Multiplying by (2^s + 1) creates
  976.      * a big value from which to derive the two split parts.
  977.      * <pre>
  978.      * c = (2^s + 1) * a
  979.      * a_big = c - a
  980.      * a_hi = c - a_big
  981.      * a_lo = a - a_hi
  982.      * a = a_hi + a_lo
  983.      * </pre>
  984.      *
  985.      * <p>The multiplicand allows a p-bit value to be split into
  986.      * (p-s)-bit value {@code a_hi} and a non-overlapping (s-1)-bit value {@code a_lo}.
  987.      * Combined they have (p-1) bits of significand but the sign bit of {@code a_lo}
  988.      * contains a bit of information. The constant is chosen so that s is ceil(p/2) where
  989.      * the precision p for a double is 53-bits (1-bit of the mantissa is assumed to be
  990.      * 1 for a non sub-normal number) and s is 27.
  991.      *
  992.      * <p>This conversion does not use scaling and the result of overflow is NaN. Overflow
  993.      * may occur when the exponent of the input value is above 996.
  994.      *
  995.      * <p>Splitting a NaN or infinite value will return NaN.
  996.      *
  997.      * @param value Value.
  998.      * @return the high part of the value.
  999.      * @see Math#getExponent(double)
  1000.      */
  1001.     static double highPart(double value) {
  1002.         final double c = MULTIPLIER * value;
  1003.         return c - (c - value);
  1004.     }

  1005.     // Public API operations

  1006.     /**
  1007.      * Returns a {@code DD} whose value is the negation of both parts of double-double number.
  1008.      *
  1009.      * @return the negation
  1010.      */
  1011.     @Override
  1012.     public DD negate() {
  1013.         return new DD(-x, -xx);
  1014.     }

  1015.     /**
  1016.      * Returns a {@code DD} whose value is the absolute value of the number {@code (x, xx)}
  1017.      * This method assumes that the low part {@code xx} is the smaller magnitude.
  1018.      *
  1019.      * <p>Cases:
  1020.      * <ul>
  1021.      *  <li>If the {@code x} value is negative the result is {@code (-x, -xx)}.
  1022.      *  <li>If the {@code x} value is +/- 0.0 the result is {@code (0.0, 0.0)}; this
  1023.      *      will remove sign information from the round-off component assumed to be zero.
  1024.      *  <li>Otherwise the result is {@code this}.
  1025.      * </ul>
  1026.      *
  1027.      * @return the absolute value
  1028.      * @see #negate()
  1029.      * @see #ZERO
  1030.      */
  1031.     public DD abs() {
  1032.         // Assume |hi| > |lo|, i.e. the low part is the round-off
  1033.         if (x < 0) {
  1034.             return negate();
  1035.         }
  1036.         // NaN, positive or zero
  1037.         // return a canonical absolute of zero
  1038.         return x == 0 ? ZERO : this;
  1039.     }

  1040.     /**
  1041.      * Returns the largest (closest to positive infinity) {@code DD} value that is less
  1042.      * than or equal to {@code this} number {@code (x, xx)} and is equal to a mathematical integer.
  1043.      *
  1044.      * <p>This method may change the representation of zero and non-finite values; the
  1045.      * result is equivalent to {@code Math.floor(x)} and the {@code xx} part is ignored.
  1046.      *
  1047.      * <p>Cases:
  1048.      * <ul>
  1049.      *  <li>If {@code x} is NaN, then the result is {@code (NaN, 0)}.
  1050.      *  <li>If {@code x} is infinite, then the result is {@code (x, 0)}.
  1051.      *  <li>If {@code x} is +/-0.0, then the result is {@code (x, 0)}.
  1052.      *  <li>If {@code x != Math.floor(x)}, then the result is {@code (Math.floor(x), 0)}.
  1053.      *  <li>Otherwise the result is the {@code DD} value equal to the sum
  1054.      *      {@code Math.floor(x) + Math.floor(xx)}.
  1055.      * </ul>
  1056.      *
  1057.      * <p>The result may generate a high part smaller (closer to negative infinity) than
  1058.      * {@code Math.floor(x)} if {@code x} is a representable integer and the {@code xx} value
  1059.      * is negative.
  1060.      *
  1061.      * @return the largest (closest to positive infinity) value that is less than or equal
  1062.      * to {@code this} and is equal to a mathematical integer
  1063.      * @see Math#floor(double)
  1064.      * @see #isFinite()
  1065.      */
  1066.     public DD floor() {
  1067.         return floorOrCeil(x, xx, Math::floor);
  1068.     }

  1069.     /**
  1070.      * Returns the smallest (closest to negative infinity) {@code DD} value that is greater
  1071.      * than or equal to {@code this} number {@code (x, xx)} and is equal to a mathematical integer.
  1072.      *
  1073.      * <p>This method may change the representation of zero and non-finite values; the
  1074.      * result is equivalent to {@code Math.ceil(x)} and the {@code xx} part is ignored.
  1075.      *
  1076.      * <p>Cases:
  1077.      * <ul>
  1078.      *  <li>If {@code x} is NaN, then the result is {@code (NaN, 0)}.
  1079.      *  <li>If {@code x} is infinite, then the result is {@code (x, 0)}.
  1080.      *  <li>If {@code x} is +/-0.0, then the result is {@code (x, 0)}.
  1081.      *  <li>If {@code x != Math.ceil(x)}, then the result is {@code (Math.ceil(x), 0)}.
  1082.      *  <li>Otherwise the result is the {@code DD} value equal to the sum
  1083.      *      {@code Math.ceil(x) + Math.ceil(xx)}.
  1084.      * </ul>
  1085.      *
  1086.      * <p>The result may generate a high part larger (closer to positive infinity) than
  1087.      * {@code Math.ceil(x)} if {@code x} is a representable integer and the {@code xx} value
  1088.      * is positive.
  1089.      *
  1090.      * @return the smallest (closest to negative infinity) value that is greater than or equal
  1091.      * to {@code this} and is equal to a mathematical integer
  1092.      * @see Math#ceil(double)
  1093.      * @see #isFinite()
  1094.      */
  1095.     public DD ceil() {
  1096.         return floorOrCeil(x, xx, Math::ceil);
  1097.     }

  1098.     /**
  1099.      * Implementation of the floor and ceiling functions.
  1100.      *
  1101.      * <p>Cases:
  1102.      * <ul>
  1103.      *  <li>If {@code x} is non-finite or zero, then the result is {@code (x, 0)}.
  1104.      *  <li>If {@code x} is rounded by the operator to a new value {@code y}, then the
  1105.      *      result is {@code (y, 0)}.
  1106.      *  <li>Otherwise the result is the {@code DD} value equal to the sum {@code op(x) + op(xx)}.
  1107.      * </ul>
  1108.      *
  1109.      * @param x High part of x.
  1110.      * @param xx Low part of x.
  1111.      * @param op Floor or ceiling operator.
  1112.      * @return the result
  1113.      */
  1114.     private static DD floorOrCeil(double x, double xx, DoubleUnaryOperator op) {
  1115.         // Assume |hi| > |lo|, i.e. the low part is the round-off
  1116.         final double y = op.applyAsDouble(x);
  1117.         // Note: The floating-point comparison is intentional
  1118.         if (y == x) {
  1119.             // Handle non-finite and zero by ignoring the low part
  1120.             if (isNotNormal(y)) {
  1121.                 return new DD(y, 0);
  1122.             }
  1123.             // High part is an integer, use the low part.
  1124.             // Any rounding must propagate to the high part.
  1125.             // Note: add 0.0 to convert -0.0 to 0.0. This is required to ensure
  1126.             // the round-off component of the fastTwoSum result is always 0.0
  1127.             // when yy == 0. This only applies in the ceiling operator when
  1128.             // xx is in (-1, 0] and will be converted to -0.0.
  1129.             final double yy = op.applyAsDouble(xx) + 0;
  1130.             return fastTwoSum(y, yy);
  1131.         }
  1132.         // NaN or already rounded.
  1133.         // xx has no effect on the rounding.
  1134.         return new DD(y, 0);
  1135.     }

  1136.     /**
  1137.      * Returns a {@code DD} whose value is {@code (this + y)}.
  1138.      *
  1139.      * <p>This computes the same result as
  1140.      * {@link #add(DD) add(DD.of(y))}.
  1141.      *
  1142.      * <p>The computed result is within 2 eps of the exact result where eps is 2<sup>-106</sup>.
  1143.      *
  1144.      * @param y Value to be added to this number.
  1145.      * @return {@code this + y}.
  1146.      * @see #add(DD)
  1147.      */
  1148.     public DD add(double y) {
  1149.         // (s0, s1) = x + y
  1150.         final double s0 = x + y;
  1151.         final double s1 = twoSumLow(x, y, s0);
  1152.         // Note: if x + y cancel to a non-zero result then s0 is >= 1 ulp of x.
  1153.         // This is larger than xx so fast-two-sum can be used.
  1154.         return fastTwoSum(s0, s1 + xx);
  1155.     }

  1156.     /**
  1157.      * Returns a {@code DD} whose value is {@code (this + y)}.
  1158.      *
  1159.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1160.      *
  1161.      * @param y Value to be added to this number.
  1162.      * @return {@code this + y}.
  1163.      */
  1164.     @Override
  1165.     public DD add(DD y) {
  1166.         return add(x, xx, y.x, y.xx);
  1167.     }

  1168.     /**
  1169.      * Compute the sum of {@code (x, xx)} and {@code (y, yy)}.
  1170.      *
  1171.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1172.      *
  1173.      * @param x High part of x.
  1174.      * @param xx Low part of x.
  1175.      * @param y High part of y.
  1176.      * @param yy Low part of y.
  1177.      * @return the sum
  1178.      * @see #accurateAdd(double, double, double, double)
  1179.      */
  1180.     static DD add(double x, double xx, double y, double yy) {
  1181.         // Sum parts and save
  1182.         // (s0, s1) = x + y
  1183.         final double s0 = x + y;
  1184.         final double s1 = twoSumLow(x, y, s0);
  1185.         // (t0, t1) = xx + yy
  1186.         final double t0 = xx + yy;
  1187.         final double t1 = twoSumLow(xx, yy, t0);
  1188.         // result = s + t
  1189.         // |s1| is >= 1 ulp of max(|x|, |y|)
  1190.         // |t0| is >= 1 ulp of max(|xx|, |yy|)
  1191.         final DD zz = fastTwoSum(s0, s1 + t0);
  1192.         return fastTwoSum(zz.x, zz.xx + t1);
  1193.     }

  1194.     /**
  1195.      * Compute the sum of {@code (x, xx)} and {@code y}.
  1196.      *
  1197.      * <p>This computes the same result as
  1198.      * {@link #accurateAdd(double, double, double, double) accurateAdd(x, xx, y, 0)}.
  1199.      *
  1200.      * <p>Note: This is an internal helper method used when accuracy is required.
  1201.      * The computed result is within 1 eps of the exact result where eps is 2<sup>-106</sup>.
  1202.      * The performance is approximately 1.5-fold slower than {@link #add(double)}.
  1203.      *
  1204.      * @param x High part of x.
  1205.      * @param xx Low part of x.
  1206.      * @param y y.
  1207.      * @return the sum
  1208.      */
  1209.     static DD accurateAdd(double x, double xx, double y) {
  1210.         // Grow expansion (Schewchuk): (x, xx) + y -> (s0, s1, s2)
  1211.         DD s = twoSum(xx, y);
  1212.         double s2 = s.xx;
  1213.         s = twoSum(x, s.x);
  1214.         final double s0 = s.x;
  1215.         final double s1 = s.xx;
  1216.         // Compress (Schewchuk Fig. 15): (s0, s1, s2) -> (s0, s1)
  1217.         s = fastTwoSum(s1, s2);
  1218.         s2 = s.xx;
  1219.         s = fastTwoSum(s0, s.x);
  1220.         // Here (s0, s1) = s
  1221.         // e = exact 159-bit result
  1222.         // |e - s0| <= ulp(s0)
  1223.         // |s1 + s2| <= ulp(e - s0)
  1224.         return fastTwoSum(s.x, s2 + s.xx);
  1225.     }

  1226.     /**
  1227.      * Compute the sum of {@code (x, xx)} and {@code (y, yy)}.
  1228.      *
  1229.      * <p>The high-part of the result is within 1 ulp of the true sum {@code e}.
  1230.      * The low-part of the result is within 1 ulp of the result of the high-part
  1231.      * subtracted from the true sum {@code e - hi}.
  1232.      *
  1233.      * <p>Note: This is an internal helper method used when accuracy is required.
  1234.      * The computed result is within 1 eps of the exact result where eps is 2<sup>-106</sup>.
  1235.      * The performance is approximately 2-fold slower than {@link #add(DD)}.
  1236.      *
  1237.      * @param x High part of x.
  1238.      * @param xx Low part of x.
  1239.      * @param y High part of y.
  1240.      * @param yy Low part of y.
  1241.      * @return the sum
  1242.      */
  1243.     static DD accurateAdd(double x, double xx, double y, double yy) {
  1244.         // Expansion sum (Schewchuk Fig 7): (x, xx) + (x, yy) -> (s0, s1, s2, s3)
  1245.         DD s = twoSum(xx, yy);
  1246.         double s3 = s.xx;
  1247.         s = twoSum(x, s.x);
  1248.         // (s0, s1, s2) == (s.x, s.xx, s3)
  1249.         double s0 = s.x;
  1250.         s = twoSum(s.xx, y);
  1251.         double s2 = s.xx;
  1252.         s = twoSum(s0, s.x);
  1253.         // s1 = s.xx
  1254.         s0 = s.x;
  1255.         // Compress (Schewchuk Fig. 15) (s0, s1, s2, s3) -> (s0, s1)
  1256.         s = fastTwoSum(s.xx, s2);
  1257.         final double s1 = s.x;
  1258.         s = fastTwoSum(s.xx, s3);
  1259.         // s2 = s.x
  1260.         s3 = s.xx;
  1261.         s = fastTwoSum(s1, s.x);
  1262.         s2 = s.xx;
  1263.         s = fastTwoSum(s0, s.x);
  1264.         // Here (s0, s1) = s
  1265.         // e = exact 212-bit result
  1266.         // |e - s0| <= ulp(s0)
  1267.         // |s1 + s2 + s3| <= ulp(e - s0)   (Sum magnitudes small to high)
  1268.         return fastTwoSum(s.x, s3 + s2 + s.xx);
  1269.     }

  1270.     /**
  1271.      * Returns a {@code DD} whose value is {@code (this - y)}.
  1272.      *
  1273.      * <p>This computes the same result as {@link #add(DD) add(-y)}.
  1274.      *
  1275.      * <p>The computed result is within 2 eps of the exact result where eps is 2<sup>-106</sup>.
  1276.      *
  1277.      * @param y Value to be subtracted from this number.
  1278.      * @return {@code this - y}.
  1279.      * @see #subtract(DD)
  1280.      */
  1281.     public DD subtract(double y) {
  1282.         return add(-y);
  1283.     }

  1284.     /**
  1285.      * Returns a {@code DD} whose value is {@code (this - y)}.
  1286.      *
  1287.      * <p>This computes the same result as {@link #add(DD) add(y.negate())}.
  1288.      *
  1289.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1290.      *
  1291.      * @param y Value to be subtracted from this number.
  1292.      * @return {@code this - y}.
  1293.      */
  1294.     @Override
  1295.     public DD subtract(DD y) {
  1296.         return add(x, xx, -y.x, -y.xx);
  1297.     }

  1298.     /**
  1299.      * Returns a {@code DD} whose value is {@code this * y}.
  1300.      *
  1301.      * <p>This computes the same result as
  1302.      * {@link #multiply(DD) multiply(DD.of(y))}.
  1303.      *
  1304.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1305.      *
  1306.      * @param y Factor.
  1307.      * @return {@code this * y}.
  1308.      * @see #multiply(DD)
  1309.      */
  1310.     public DD multiply(double y) {
  1311.         return multiply(x, xx, y);
  1312.     }

  1313.     /**
  1314.      * Compute the multiplication product of {@code (x, xx)} and {@code y}.
  1315.      *
  1316.      * <p>This computes the same result as
  1317.      * {@link #multiply(double, double, double, double) multiply(x, xx, y, 0)}.
  1318.      *
  1319.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1320.      *
  1321.      * @param x High part of x.
  1322.      * @param xx Low part of x.
  1323.      * @param y High part of y.
  1324.      * @return the product
  1325.      * @see #multiply(double, double, double, double)
  1326.      */
  1327.     private static DD multiply(double x, double xx, double y) {
  1328.         // Dekker mul2 with yy=0
  1329.         // (Alternative: Scale expansion (Schewchuk Fig 13))
  1330.         final double hi = x * y;
  1331.         final double lo = twoProductLow(x, y, hi);
  1332.         // Save 2 FLOPS compared to multiply(x, xx, y, 0).
  1333.         // This is reused in divide to save more FLOPS so worth the optimisation.
  1334.         return fastTwoSum(hi, lo + xx * y);
  1335.     }

  1336.     /**
  1337.      * Returns a {@code DD} whose value is {@code this * y}.
  1338.      *
  1339.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1340.      *
  1341.      * @param y Factor.
  1342.      * @return {@code this * y}.
  1343.      */
  1344.     @Override
  1345.     public DD multiply(DD y) {
  1346.         return multiply(x, xx, y.x, y.xx);
  1347.     }

  1348.     /**
  1349.      * Compute the multiplication product of {@code (x, xx)} and {@code (y, yy)}.
  1350.      *
  1351.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1352.      *
  1353.      * @param x High part of x.
  1354.      * @param xx Low part of x.
  1355.      * @param y High part of y.
  1356.      * @param yy Low part of y.
  1357.      * @return the product
  1358.      */
  1359.     private static DD multiply(double x, double xx, double y, double yy) {
  1360.         // Dekker mul2
  1361.         // (Alternative: Scale expansion (Schewchuk Fig 13))
  1362.         final double hi = x * y;
  1363.         final double lo = twoProductLow(x, y, hi);
  1364.         return fastTwoSum(hi, lo + (x * yy + xx * y));
  1365.     }

  1366.     /**
  1367.      * Returns a {@code DD} whose value is {@code this * this}.
  1368.      *
  1369.      * <p>This method is an optimisation of {@link #multiply(DD) multiply(this)}.
  1370.      *
  1371.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1372.      *
  1373.      * @return {@code this}<sup>2</sup>
  1374.      * @see #multiply(DD)
  1375.      */
  1376.     public DD square() {
  1377.         return square(x, xx);
  1378.     }

  1379.     /**
  1380.      * Compute the square of {@code (x, xx)}.
  1381.      *
  1382.      * @param x High part of x.
  1383.      * @param xx Low part of x.
  1384.      * @return the square
  1385.      */
  1386.     private static DD square(double x, double xx) {
  1387.         // Dekker mul2
  1388.         final double hi = x * x;
  1389.         final double lo = twoSquareLow(x, hi);
  1390.         return fastTwoSum(hi, lo + (2 * x * xx));
  1391.     }

  1392.     /**
  1393.      * Returns a {@code DD} whose value is {@code (this / y)}.
  1394.      * If {@code y = 0} the result is undefined.
  1395.      *
  1396.      * <p>The computed result is within 1 eps of the exact result where eps is 2<sup>-106</sup>.
  1397.      *
  1398.      * @param y Divisor.
  1399.      * @return {@code this / y}.
  1400.      */
  1401.     public DD divide(double y) {
  1402.         return divide(x, xx, y);
  1403.     }

  1404.     /**
  1405.      * Compute the division of {@code (x, xx)} by {@code y}.
  1406.      * If {@code y = 0} the result is undefined.
  1407.      *
  1408.      * <p>The computed result is within 1 eps of the exact result where eps is 2<sup>-106</sup>.
  1409.      *
  1410.      * @param x High part of x.
  1411.      * @param xx Low part of x.
  1412.      * @param y High part of y.
  1413.      * @return the quotient
  1414.      */
  1415.     private static DD divide(double x, double xx, double y) {
  1416.         // Long division
  1417.         // quotient q0 = x / y
  1418.         final double q0 = x / y;
  1419.         // remainder r0 = x - q0 * y
  1420.         DD p = twoProd(y, q0);
  1421.         // High accuracy add required
  1422.         DD r = accurateAdd(x, xx, -p.x, -p.xx);
  1423.         // next quotient q1 = r0 / y
  1424.         final double q1 = r.x / y;
  1425.         // remainder r1 = r0 - q1 * y
  1426.         p = twoProd(y, q1);
  1427.         // accurateAdd not used as we do not need r1.xx
  1428.         r = add(r.x, r.xx, -p.x, -p.xx);
  1429.         // next quotient q2 = r1 / y
  1430.         final double q2 = r.x / y;
  1431.         // Collect (q0, q1, q2)
  1432.         final DD q = fastTwoSum(q0, q1);
  1433.         return twoSum(q.x, q.xx + q2);
  1434.     }

  1435.     /**
  1436.      * Returns a {@code DD} whose value is {@code (this / y)}.
  1437.      * If {@code y = 0} the result is undefined.
  1438.      *
  1439.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1440.      *
  1441.      * @param y Divisor.
  1442.      * @return {@code this / y}.
  1443.      */
  1444.     @Override
  1445.     public DD divide(DD y) {
  1446.         return divide(x, xx, y.x, y.xx);
  1447.     }

  1448.     /**
  1449.      * Compute the division of {@code (x, xx)} by {@code (y, yy)}.
  1450.      * If {@code y = 0} the result is undefined.
  1451.      *
  1452.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1453.      *
  1454.      * @param x High part of x.
  1455.      * @param xx Low part of x.
  1456.      * @param y High part of y.
  1457.      * @param yy Low part of y.
  1458.      * @return the quotient
  1459.      */
  1460.     private static DD divide(double x, double xx, double y, double yy) {
  1461.         // Long division
  1462.         // quotient q0 = x / y
  1463.         final double q0 = x / y;
  1464.         // remainder r0 = x - q0 * y
  1465.         DD p = multiply(y, yy, q0);
  1466.         // High accuracy add required
  1467.         DD r = accurateAdd(x, xx, -p.x, -p.xx);
  1468.         // next quotient q1 = r0 / y
  1469.         final double q1 = r.x / y;
  1470.         // remainder r1 = r0 - q1 * y
  1471.         p = multiply(y, yy, q1);
  1472.         // accurateAdd not used as we do not need r1.xx
  1473.         r = add(r.x, r.xx, -p.x, -p.xx);
  1474.         // next quotient q2 = r1 / y
  1475.         final double q2 = r.x / y;
  1476.         // Collect (q0, q1, q2)
  1477.         final DD q = fastTwoSum(q0, q1);
  1478.         return twoSum(q.x, q.xx + q2);
  1479.     }

  1480.     /**
  1481.      * Compute the reciprocal of {@code this}.
  1482.      * If {@code this} value is zero the result is undefined.
  1483.      *
  1484.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1485.      *
  1486.      * @return {@code this}<sup>-1</sup>
  1487.      */
  1488.     @Override
  1489.     public DD reciprocal() {
  1490.         return reciprocal(x, xx);
  1491.     }

  1492.     /**
  1493.      * Compute the inverse of {@code (y, yy)}.
  1494.      * If {@code y = 0} the result is undefined.
  1495.      *
  1496.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1497.      *
  1498.      * @param y High part of y.
  1499.      * @param yy Low part of y.
  1500.      * @return the inverse
  1501.      */
  1502.     private static DD reciprocal(double y, double yy) {
  1503.         // As per divide using (x, xx) = (1, 0)
  1504.         // quotient q0 = x / y
  1505.         final double q0 = 1 / y;
  1506.         // remainder r0 = x - q0 * y
  1507.         DD p = multiply(y, yy, q0);
  1508.         // High accuracy add required
  1509.         // This add saves 2 twoSum and 3 fastTwoSum (24 FLOPS) by ignoring the zero low part
  1510.         DD r = accurateAdd(-p.x, -p.xx, 1);
  1511.         // next quotient q1 = r0 / y
  1512.         final double q1 = r.x / y;
  1513.         // remainder r1 = r0 - q1 * y
  1514.         p = multiply(y, yy, q1);
  1515.         // accurateAdd not used as we do not need r1.xx
  1516.         r = add(r.x, r.xx, -p.x, -p.xx);
  1517.         // next quotient q2 = r1 / y
  1518.         final double q2 = r.x / y;
  1519.         // Collect (q0, q1, q2)
  1520.         final DD q = fastTwoSum(q0, q1);
  1521.         return twoSum(q.x, q.xx + q2);
  1522.     }

  1523.     /**
  1524.      * Compute the square root of {@code this} number {@code (x, xx)}.
  1525.      *
  1526.      * <p>Uses the result {@code Math.sqrt(x)}
  1527.      * if that result is not a finite normalized {@code double}.
  1528.      *
  1529.      * <p>Special cases:
  1530.      * <ul>
  1531.      *  <li>If {@code x} is NaN or less than zero, then the result is {@code (NaN, 0)}.
  1532.      *  <li>If {@code x} is positive infinity, then the result is {@code (+infinity, 0)}.
  1533.      *  <li>If {@code x} is positive zero or negative zero, then the result is {@code (x, 0)}.
  1534.      * </ul>
  1535.      *
  1536.      * <p>The computed result is within 4 eps of the exact result where eps is 2<sup>-106</sup>.
  1537.      *
  1538.      * @return {@code sqrt(this)}
  1539.      * @see Math#sqrt(double)
  1540.      * @see Double#MIN_NORMAL
  1541.      */
  1542.     public DD sqrt() {
  1543.         // Standard sqrt
  1544.         final double c = Math.sqrt(x);

  1545.         // Here we support {negative, +infinity, nan and zero} edge cases.
  1546.         // This is required to avoid a divide by zero in the following
  1547.         // computation, otherwise (0, 0).sqrt() = (NaN, NaN).
  1548.         if (isNotNormal(c)) {
  1549.             return new DD(c, 0);
  1550.         }

  1551.         // Here hi is positive, non-zero and finite; assume lo is also finite

  1552.         // Dekker's double precision sqrt2 algorithm.
  1553.         // See Dekker, 1971, pp 242.
  1554.         final double hc = highPart(c);
  1555.         final double lc = c - hc;
  1556.         final double u = c * c;
  1557.         final double uu = twoSquareLow(hc, lc, u);
  1558.         final double cc = (x - u - uu + xx) * 0.5 / c;

  1559.         // Extended precision result:
  1560.         // y = c + cc
  1561.         // yy = c - y + cc
  1562.         return fastTwoSum(c, cc);
  1563.     }

  1564.     /**
  1565.      * Checks if the number is not normal. This is functionally equivalent to:
  1566.      * <pre>{@code
  1567.      * final double abs = Math.abs(a);
  1568.      * return (abs <= Double.MIN_NORMAL || !(abs <= Double.MAX_VALUE));
  1569.      * }</pre>
  1570.      *
  1571.      * @param a The value.
  1572.      * @return true if the value is not normal
  1573.      */
  1574.     static boolean isNotNormal(double a) {
  1575.         // Sub-normal numbers have a biased exponent of 0.
  1576.         // Inf/NaN numbers have a biased exponent of 2047.
  1577.         // Catch both cases by extracting the raw exponent, subtracting 1
  1578.         // and compare unsigned (so 0 underflows to a unsigned large value).
  1579.         final int baisedExponent = ((int) (Double.doubleToRawLongBits(a) >>> 52)) & EXP_MASK;
  1580.         // Pre-compute the additions used by Integer.compareUnsigned
  1581.         return baisedExponent + CMP_UNSIGNED_MINUS_1 >= CMP_UNSIGNED_2046;
  1582.     }

  1583.     /**
  1584.      * Multiply {@code this} number {@code (x, xx)} by an integral power of two.
  1585.      * <pre>
  1586.      * (y, yy) = (x, xx) * 2^exp
  1587.      * </pre>
  1588.      *
  1589.      * <p>The result is rounded as if performed by a single correctly rounded floating-point
  1590.      * multiply. This performs the same result as:
  1591.      * <pre>
  1592.      * y = Math.scalb(x, exp);
  1593.      * yy = Math.scalb(xx, exp);
  1594.      * </pre>
  1595.      *
  1596.      * <p>The implementation computes using a single multiplication if {@code exp}
  1597.      * is in {@code [-1022, 1023]}. Otherwise the parts {@code (x, xx)} are scaled by
  1598.      * repeated multiplication by power-of-two factors. The result is exact unless the scaling
  1599.      * generates sub-normal parts; in this case precision may be lost by a single rounding.
  1600.      *
  1601.      * @param exp Power of two scale factor.
  1602.      * @return the result
  1603.      * @see Math#scalb(double, int)
  1604.      * @see #frexp(int[])
  1605.      */
  1606.     public DD scalb(int exp) {
  1607.         // Handle scaling when 2^n can be represented with a single normal number
  1608.         // n >= -1022 && n <= 1023
  1609.         // Using unsigned compare => n + 1022 <= 1023 + 1022
  1610.         if (exp + CMP_UNSIGNED_1022 < CMP_UNSIGNED_2046) {
  1611.             final double s = twoPow(exp);
  1612.             return new DD(x * s, xx * s);
  1613.         }

  1614.         // Scale by multiples of 2^512 (largest representable power of 2).
  1615.         // Scaling requires max 5 multiplications to under/overflow any normal value.
  1616.         // Break this down into e.g.: 2^512^(exp / 512) * 2^(exp % 512)
  1617.         // Number of multiples n = exp / 512   : exp >>> 9
  1618.         // Remainder           m = exp % 512   : exp & 511  (exp must be positive)
  1619.         int n;
  1620.         int m;
  1621.         double p;
  1622.         if (exp < 0) {
  1623.             // Downscaling
  1624.             // (Note: Using an unsigned shift handles negation of min value: -2^31)
  1625.             n = -exp >>> 9;
  1626.             // m = exp % 512
  1627.             m = -(-exp & 511);
  1628.             p = TWO_POW_M512;
  1629.         } else {
  1630.             // Upscaling
  1631.             n = exp >>> 9;
  1632.             m = exp & 511;
  1633.             p = TWO_POW_512;
  1634.         }

  1635.         // Multiply by the remainder scaling factor first. The remaining multiplications
  1636.         // are either 2^512 or 2^-512.
  1637.         // Down-scaling to sub-normal will use the final multiplication into a sub-normal result.
  1638.         // Note here that n >= 1 as the n in [-1022, 1023] case has been handled.

  1639.         double z0;
  1640.         double z1;

  1641.         // Handle n : 1, 2, 3, 4, 5
  1642.         if (n >= 5) {
  1643.             // n >= 5 will be over/underflow. Use an extreme scale factor.
  1644.             // Do not use +/- infinity as this creates NaN if x = 0.
  1645.             // p -> 2^1023 or 2^-1025
  1646.             p *= p * 0.5;
  1647.             z0 = x * p * p * p;
  1648.             z1 = xx * p * p * p;
  1649.             return new DD(z0, z1);
  1650.         }

  1651.         final double s = twoPow(m);
  1652.         if (n == 4) {
  1653.             z0 = x * s * p * p * p * p;
  1654.             z1 = xx * s * p * p * p * p;
  1655.         } else if (n == 3) {
  1656.             z0 = x * s * p * p * p;
  1657.             z1 = xx * s * p * p * p;
  1658.         } else if (n == 2) {
  1659.             z0 = x * s * p * p;
  1660.             z1 = xx * s * p * p;
  1661.         } else {
  1662.             // n = 1. Occurs only if exp = -1023.
  1663.             z0 = x * s * p;
  1664.             z1 = xx * s * p;
  1665.         }
  1666.         return new DD(z0, z1);
  1667.     }

  1668.     /**
  1669.      * Create a normalized double with the value {@code 2^n}.
  1670.      *
  1671.      * <p>Warning: Do not call with {@code n = -1023}. This will create zero.
  1672.      *
  1673.      * @param n Exponent (in the range [-1022, 1023]).
  1674.      * @return the double
  1675.      */
  1676.     static double twoPow(int n) {
  1677.         return Double.longBitsToDouble(((long) (n + 1023)) << 52);
  1678.     }

  1679.     /**
  1680.      * Convert {@code this} number {@code x} to fractional {@code f} and integral
  1681.      * {@code 2^exp} components.
  1682.      * <pre>
  1683.      * x = f * 2^exp
  1684.      * </pre>
  1685.      *
  1686.      * <p>The combined fractional part (f, ff) is in the range {@code [0.5, 1)}.
  1687.      *
  1688.      * <p>Special cases:
  1689.      * <ul>
  1690.      *  <li>If {@code x} is zero, then the normalized fraction is zero and the exponent is zero.
  1691.      *  <li>If {@code x} is NaN, then the normalized fraction is NaN and the exponent is unspecified.
  1692.      *  <li>If {@code x} is infinite, then the normalized fraction is infinite and the exponent is unspecified.
  1693.      *  <li>If high-part {@code x} is an exact power of 2 and the low-part {@code xx} has an opposite
  1694.      *      signed non-zero magnitude then fraction high-part {@code f} will be {@code +/-1} such that
  1695.      *      the double-double number is in the range {@code [0.5, 1)}.
  1696.      * </ul>
  1697.      *
  1698.      * <p>This is named using the equivalent function in the standard C math.h library.
  1699.      *
  1700.      * @param exp Power of two scale factor (integral exponent).
  1701.      * @return Fraction part.
  1702.      * @see Math#getExponent(double)
  1703.      * @see #scalb(int)
  1704.      * @see <a href="https://www.cplusplus.com/reference/cmath/frexp/">C math.h frexp</a>
  1705.      */
  1706.     public DD frexp(int[] exp) {
  1707.         exp[0] = getScale(x);
  1708.         // Handle non-scalable numbers
  1709.         if (exp[0] == Double.MAX_EXPONENT + 1) {
  1710.             // Returns +/-0.0, inf or nan
  1711.             // Maintain the fractional part unchanged.
  1712.             // Do not change the fractional part of inf/nan, and assume
  1713.             // |xx| < |x| thus if x == 0 then xx == 0 (otherwise the double-double is invalid)
  1714.             // Unspecified for NaN/inf so just return zero exponent.
  1715.             exp[0] = 0;
  1716.             return this;
  1717.         }
  1718.         // The scale will create the fraction in [1, 2) so increase by 1 for [0.5, 1)
  1719.         exp[0] += 1;
  1720.         DD f = scalb(-exp[0]);
  1721.         // Return |(hi, lo)| = (1, -eps) if required.
  1722.         // f.x * f.xx < 0 detects sign change unless the product underflows.
  1723.         // Handle extreme case of |f.xx| being min value by doubling f.x to 1.
  1724.         if (Math.abs(f.x) == HALF && 2 * f.x * f.xx < 0) {
  1725.             f = new DD(f.x * 2, f.xx * 2);
  1726.             exp[0] -= 1;
  1727.         }
  1728.         return f;
  1729.     }

  1730.     /**
  1731.      * Returns a scale suitable for use with {@link Math#scalb(double, int)} to normalise
  1732.      * the number to the interval {@code [1, 2)}.
  1733.      *
  1734.      * <p>In contrast to {@link Math#getExponent(double)} this handles
  1735.      * sub-normal numbers by computing the number of leading zeros in the mantissa
  1736.      * and shifting the unbiased exponent. The result is that for all finite, non-zero,
  1737.      * numbers, the magnitude of {@code scalb(x, -getScale(x))} is
  1738.      * always in the range {@code [1, 2)}.
  1739.      *
  1740.      * <p>This method is a functional equivalent of the c function ilogb(double).
  1741.      *
  1742.      * <p>The result is to be used to scale a number using {@link Math#scalb(double, int)}.
  1743.      * Hence the special case of a zero argument is handled using the return value for NaN
  1744.      * as zero cannot be scaled. This is different from {@link Math#getExponent(double)}.
  1745.      *
  1746.      * <p>Special cases:
  1747.      * <ul>
  1748.      *  <li>If the argument is NaN or infinite, then the result is {@link Double#MAX_EXPONENT} + 1.
  1749.      *  <li>If the argument is zero, then the result is {@link Double#MAX_EXPONENT} + 1.
  1750.      * </ul>
  1751.      *
  1752.      * @param a Value.
  1753.      * @return The unbiased exponent of the value to be used for scaling, or 1024 for 0, NaN or Inf
  1754.      * @see Math#getExponent(double)
  1755.      * @see Math#scalb(double, int)
  1756.      * @see <a href="https://www.cplusplus.com/reference/cmath/ilogb/">ilogb</a>
  1757.      */
  1758.     private static int getScale(double a) {
  1759.         // Only interested in the exponent and mantissa so remove the sign bit
  1760.         final long bits = Double.doubleToRawLongBits(a) & UNSIGN_MASK;
  1761.         // Get the unbiased exponent
  1762.         int exp = ((int) (bits >>> 52)) - EXPONENT_OFFSET;

  1763.         // No case to distinguish nan/inf (exp == 1024).
  1764.         // Handle sub-normal numbers
  1765.         if (exp == Double.MIN_EXPONENT - 1) {
  1766.             // Special case for zero, return as nan/inf to indicate scaling is not possible
  1767.             if (bits == 0) {
  1768.                 return Double.MAX_EXPONENT + 1;
  1769.             }
  1770.             // A sub-normal number has an exponent below -1022. The amount below
  1771.             // is defined by the number of shifts of the most significant bit in
  1772.             // the mantissa that is required to get a 1 at position 53 (i.e. as
  1773.             // if it were a normal number with assumed leading bit)
  1774.             final long mantissa = bits & MANTISSA_MASK;
  1775.             exp -= Long.numberOfLeadingZeros(mantissa << 12);
  1776.         }
  1777.         return exp;
  1778.     }

  1779.     /**
  1780.      * Compute {@code this} number {@code (x, xx)} raised to the power {@code n}.
  1781.      *
  1782.      * <p>Special cases:
  1783.      * <ul>
  1784.      *  <li>If {@code x} is not a finite normalized {@code double}, the low part {@code xx}
  1785.      *      is ignored and the result is {@link Math#pow(double, double) Math.pow(x, n)}.
  1786.      *  <li>If {@code n = 0} the result is {@code (1, 0)}.
  1787.      *  <li>If {@code n = 1} the result is {@code (x, xx)}.
  1788.      *  <li>If {@code n = -1} the result is the {@link #reciprocal() reciprocal}.
  1789.      *  <li>If the computation overflows the result is undefined.
  1790.      * </ul>
  1791.      *
  1792.      * <p>Computation uses multiplication by factors generated by repeat squaring of the value.
  1793.      * These multiplications have no special case handling for overflow; in the event of overflow
  1794.      * the result is undefined. The {@link #pow(int, long[])} method can be used to
  1795.      * generate a scaled fraction result for any finite {@code DD} number and exponent.
  1796.      *
  1797.      * <p>The computed result is approximately {@code 16 * (n - 1) * eps} of the exact result
  1798.      * where eps is 2<sup>-106</sup>.
  1799.      *
  1800.      * @param n Exponent.
  1801.      * @return {@code this}<sup>n</sup>
  1802.      * @see Math#pow(double, double)
  1803.      * @see #pow(int, long[])
  1804.      * @see #isFinite()
  1805.      */
  1806.     @Override
  1807.     public DD pow(int n) {
  1808.         // Edge cases.
  1809.         if (n == 1) {
  1810.             return this;
  1811.         }
  1812.         if (n == 0) {
  1813.             return ONE;
  1814.         }

  1815.         // Handles {infinity, nan and zero} cases
  1816.         if (isNotNormal(x)) {
  1817.             // Assume the high part has the greatest magnitude
  1818.             // so here the low part is irrelevant
  1819.             return new DD(Math.pow(x, n), 0);
  1820.         }

  1821.         // Here hi is finite; assume lo is also finite
  1822.         if (n == -1) {
  1823.             return reciprocal();
  1824.         }

  1825.         // Extended precision computation is required.
  1826.         // No checks for overflow.
  1827.         if (n < 0) {
  1828.             // Note: Correctly handles negating -2^31
  1829.             return computePow(x, xx, -n).reciprocal();
  1830.         }
  1831.         return computePow(x, xx, n);
  1832.     }

  1833.     /**
  1834.      * Compute the number {@code x} (non-zero finite) raised to the power {@code n}.
  1835.      *
  1836.      * <p>The input power is treated as an unsigned integer. Thus the negative value
  1837.      * {@link Integer#MIN_VALUE} is 2^31.
  1838.      *
  1839.      * @param x Fractional high part of x.
  1840.      * @param xx Fractional low part of x.
  1841.      * @param n Power (in [2, 2^31]).
  1842.      * @return x^n.
  1843.      */
  1844.     private static DD computePow(double x, double xx, int n) {
  1845.         // Compute the power by multiplication (keeping track of the scale):
  1846.         // 13 = 1101
  1847.         // x^13 = x^8 * x^4 * x^1
  1848.         //      = ((x^2 * x)^2)^2 * x
  1849.         // 21 = 10101
  1850.         // x^21 = x^16 * x^4 * x^1
  1851.         //      = (((x^2)^2 * x)^2)^2 * x
  1852.         // 1. Find highest set bit in n (assume n != 0)
  1853.         // 2. Initialise result as x
  1854.         // 3. For remaining bits (0 or 1) below the highest set bit:
  1855.         //    - square the current result
  1856.         //    - if the current bit is 1 then multiply by x
  1857.         // In this scheme the factors to multiply by x can be pre-computed.

  1858.         // Split b
  1859.         final double xh = highPart(x);
  1860.         final double xl = x - xh;

  1861.         // Initialise the result as x^1
  1862.         double f0 = x;
  1863.         double f1 = xx;

  1864.         double u;
  1865.         double v;
  1866.         double w;

  1867.         // Shift the highest set bit off the top.
  1868.         // Any remaining bits are detected in the sign bit.
  1869.         final int shift = Integer.numberOfLeadingZeros(n) + 1;
  1870.         int bits = n << shift;

  1871.         // Multiplication is done without object allocation of DD intermediates.
  1872.         // The square can be optimised.
  1873.         // Process remaining bits below highest set bit.
  1874.         for (int i = 32 - shift; i != 0; i--, bits <<= 1) {
  1875.             // Square the result
  1876.             // Inline multiply(f0, f1, f0, f1), adapted for squaring
  1877.             u = f0 * f0;
  1878.             v = twoSquareLow(f0, u);
  1879.             // Inline (f0, f1) = fastTwoSum(hi, lo + (2 * f0 * f1))
  1880.             w = v + (2 * f0 * f1);
  1881.             f0 = u + w;
  1882.             f1 = fastTwoSumLow(u, w, f0);
  1883.             if (bits < 0) {
  1884.                 // Inline multiply(f0, f1, x, xx)
  1885.                 u = highPart(f0);
  1886.                 v = f0 - u;
  1887.                 w = f0 * x;
  1888.                 v = twoProductLow(u, v, xh, xl, w);
  1889.                 // Inline (f0, f1) = fastTwoSum(w, v + (f0 * xx + f1 * x))
  1890.                 u = v + (f0 * xx + f1 * x);
  1891.                 f0 = w + u;
  1892.                 f1 = fastTwoSumLow(w, u, f0);
  1893.             }
  1894.         }

  1895.         return new DD(f0, f1);
  1896.     }

  1897.     /**
  1898.      * Compute {@code this} number {@code x} raised to the power {@code n}.
  1899.      *
  1900.      * <p>The value is returned as fractional {@code f} and integral
  1901.      * {@code 2^exp} components.
  1902.      * <pre>
  1903.      * (x+xx)^n = (f+ff) * 2^exp
  1904.      * </pre>
  1905.      *
  1906.      * <p>The combined fractional part (f, ff) is in the range {@code [0.5, 1)}.
  1907.      *
  1908.      * <p>Special cases:
  1909.      * <ul>
  1910.      *  <li>If {@code (x, xx)} is zero the high part of the fractional part is
  1911.      *      computed using {@link Math#pow(double, double) Math.pow(x, n)} and the exponent is 0.
  1912.      *  <li>If {@code n = 0} the fractional part is 0.5 and the exponent is 1.
  1913.      *  <li>If {@code (x, xx)} is an exact power of 2 the fractional part is 0.5 and the exponent
  1914.      *      is the power of 2 minus 1.
  1915.      *  <li>If the result high-part is an exact power of 2 and the low-part has an opposite
  1916.      *      signed non-zero magnitude then the fraction high-part {@code f} will be {@code +/-1} such that
  1917.      *      the double-double number is in the range {@code [0.5, 1)}.
  1918.      *  <li>If the argument is not finite then a fractional representation is not possible.
  1919.      *      In this case the fraction and the scale factor is undefined.
  1920.      * </ul>
  1921.      *
  1922.      * <p>The computed result is approximately {@code 16 * (n - 1) * eps} of the exact result
  1923.      * where eps is 2<sup>-106</sup>.
  1924.      *
  1925.      * @param n Power.
  1926.      * @param exp Result power of two scale factor (integral exponent).
  1927.      * @return Fraction part.
  1928.      * @see #frexp(int[])
  1929.      */
  1930.     public DD pow(int n, long[] exp) {
  1931.         // Edge cases.
  1932.         if (n == 0) {
  1933.             exp[0] = 1;
  1934.             return new DD(0.5, 0);
  1935.         }
  1936.         // IEEE result for non-finite or zero
  1937.         if (!Double.isFinite(x) || x == 0) {
  1938.             exp[0] = 0;
  1939.             return new DD(Math.pow(x, n), 0);
  1940.         }
  1941.         // Here the number is non-zero finite
  1942.         final int[] ie = {0};
  1943.         DD f = frexp(ie);
  1944.         final long b = ie[0];
  1945.         // Handle exact powers of 2
  1946.         if (Math.abs(f.x) == HALF && f.xx == 0) {
  1947.             // (f * 2^b)^n = (2f)^n * 2^(b-1)^n
  1948.             // Use Math.pow to create the sign.
  1949.             // Note the result must be scaled to the fractional representation
  1950.             // by multiplication by 0.5 and addition of 1 to the exponent.
  1951.             final double y0 = 0.5 * Math.pow(2 * f.x, n);
  1952.             // Propagate sign change (y0*f.x) to the original zero (this.xx)
  1953.             final double y1 = Math.copySign(0.0, y0 * f.x * this.xx);
  1954.             exp[0] = 1 + (b - 1) * n;
  1955.             return new DD(y0, y1);
  1956.         }
  1957.         if (n < 0) {
  1958.             f = computePowScaled(b, f.x, f.xx, -n, exp);
  1959.             // Result is a non-zero fraction part so inversion is safe
  1960.             f = reciprocal(f.x, f.xx);
  1961.             // Rescale to [0.5, 1.0)
  1962.             f = f.frexp(ie);
  1963.             exp[0] = ie[0] - exp[0];
  1964.             return f;
  1965.         }
  1966.         return computePowScaled(b, f.x, f.xx, n, exp);
  1967.     }

  1968.     /**
  1969.      * Compute the number {@code x} (non-zero finite) raised to the power {@code n}.
  1970.      *
  1971.      * <p>The input power is treated as an unsigned integer. Thus the negative value
  1972.      * {@link Integer#MIN_VALUE} is 2^31.
  1973.      *
  1974.      * @param b Integral component 2^exp of x.
  1975.      * @param x Fractional high part of x.
  1976.      * @param xx Fractional low part of x.
  1977.      * @param n Power (in [2, 2^31]).
  1978.      * @param exp Result power of two scale factor (integral exponent).
  1979.      * @return Fraction part.
  1980.      */
  1981.     private static DD computePowScaled(long b, double x, double xx, int n, long[] exp) {
  1982.         // Compute the power by multiplication (keeping track of the scale):
  1983.         // 13 = 1101
  1984.         // x^13 = x^8 * x^4 * x^1
  1985.         //      = ((x^2 * x)^2)^2 * x
  1986.         // 21 = 10101
  1987.         // x^21 = x^16 * x^4 * x^1
  1988.         //      = (((x^2)^2 * x)^2)^2 * x
  1989.         // 1. Find highest set bit in n (assume n != 0)
  1990.         // 2. Initialise result as x
  1991.         // 3. For remaining bits (0 or 1) below the highest set bit:
  1992.         //    - square the current result
  1993.         //    - if the current bit is 1 then multiply by x
  1994.         // In this scheme the factors to multiply by x can be pre-computed.

  1995.         // Scale the input in [0.5, 1) to be above 1. Represented as 2^be * b.
  1996.         final long be = b - 1;
  1997.         final double b0 = x * 2;
  1998.         final double b1 = xx * 2;
  1999.         // Split b
  2000.         final double b0h = highPart(b0);
  2001.         final double b0l = b0 - b0h;

  2002.         // Initialise the result as x^1. Represented as 2^fe * f.
  2003.         long fe = be;
  2004.         double f0 = b0;
  2005.         double f1 = b1;

  2006.         double u;
  2007.         double v;
  2008.         double w;

  2009.         // Shift the highest set bit off the top.
  2010.         // Any remaining bits are detected in the sign bit.
  2011.         final int shift = Integer.numberOfLeadingZeros(n) + 1;
  2012.         int bits = n << shift;

  2013.         // Multiplication is done without using DD.multiply as the arguments
  2014.         // are always finite and the product will not overflow. The square can be optimised.
  2015.         // Process remaining bits below highest set bit.
  2016.         for (int i = 32 - shift; i != 0; i--, bits <<= 1) {
  2017.             // Square the result
  2018.             // Inline multiply(f0, f1, f0, f1, f), adapted for squaring
  2019.             fe <<= 1;
  2020.             u = f0 * f0;
  2021.             v = twoSquareLow(f0, u);
  2022.             // Inline fastTwoSum(hi, lo + (2 * f0 * f1), f)
  2023.             w = v + (2 * f0 * f1);
  2024.             f0 = u + w;
  2025.             f1 = fastTwoSumLow(u, w, f0);
  2026.             // Rescale
  2027.             if (Math.abs(f0) > SAFE_MULTIPLY) {
  2028.                 // Scale back to the [1, 2) range. As safe multiply is 2^500
  2029.                 // the exponent should be < 1001 so the twoPow scaling factor is supported.
  2030.                 final int e = Math.getExponent(f0);
  2031.                 final double s = twoPow(-e);
  2032.                 fe += e;
  2033.                 f0 *= s;
  2034.                 f1 *= s;
  2035.             }
  2036.             if (bits < 0) {
  2037.                 // Multiply by b
  2038.                 fe += be;
  2039.                 // Inline multiply(f0, f1, b0, b1, f)
  2040.                 u = highPart(f0);
  2041.                 v = f0 - u;
  2042.                 w = f0 * b0;
  2043.                 v = twoProductLow(u, v, b0h, b0l, w);
  2044.                 // Inline fastTwoSum(w, v + (f0 * b1 + f1 * b0), f)
  2045.                 u = v + (f0 * b1 + f1 * b0);
  2046.                 f0 = w + u;
  2047.                 f1 = fastTwoSumLow(w, u, f0);
  2048.                 // Avoid rescale as x2 is in [1, 2)
  2049.             }
  2050.         }

  2051.         final int[] e = {0};
  2052.         final DD f = new DD(f0, f1).frexp(e);
  2053.         exp[0] = fe + e[0];
  2054.         return f;
  2055.     }

  2056.     /**
  2057.      * Test for equality with another object. If the other object is a {@code DD} then a
  2058.      * comparison is made of the parts; otherwise {@code false} is returned.
  2059.      *
  2060.      * <p>If both parts of two double-double numbers
  2061.      * are numerically equivalent the two {@code DD} objects are considered to be equal.
  2062.      * For this purpose, two {@code double} values are considered to be
  2063.      * the same if and only if the method call
  2064.      * {@link Double#doubleToLongBits(double) Double.doubleToLongBits(value + 0.0)}
  2065.      * returns the identical {@code long} when applied to each value. This provides
  2066.      * numeric equality of different representations of zero as per {@code -0.0 == 0.0},
  2067.      * and equality of {@code NaN} values.
  2068.      *
  2069.      * <p>Note that in most cases, for two instances of class
  2070.      * {@code DD}, {@code x} and {@code y}, the
  2071.      * value of {@code x.equals(y)} is {@code true} if and only if
  2072.      *
  2073.      * <pre>
  2074.      *  {@code x.hi() == y.hi() && x.lo() == y.lo()}</pre>
  2075.      *
  2076.      * <p>also has the value {@code true}. However, there are exceptions:
  2077.      *
  2078.      * <ul>
  2079.      *  <li>Instances that contain {@code NaN} values in the same part
  2080.      *      are considered to be equal for that part, even though {@code Double.NaN == Double.NaN}
  2081.      *      has the value {@code false}.
  2082.      *  <li>Instances that share a {@code NaN} value in one part
  2083.      *      but have different values in the other part are <em>not</em> considered equal.
  2084.      * </ul>
  2085.      *
  2086.      * <p>The behavior is the same as if the components of the two double-double numbers were passed
  2087.      * to {@link java.util.Arrays#equals(double[], double[]) Arrays.equals(double[], double[])}:
  2088.      *
  2089.      * <pre>
  2090.      *  Arrays.equals(new double[]{x.hi() + 0.0, x.lo() + 0.0},
  2091.      *                new double[]{y.hi() + 0.0, y.lo() + 0.0}); </pre>
  2092.      *
  2093.      * <p>Note: Addition of {@code 0.0} converts signed representations of zero values
  2094.      * {@code -0.0} and {@code 0.0} to a canonical {@code 0.0}.
  2095.      *
  2096.      * @param other Object to test for equality with this instance.
  2097.      * @return {@code true} if the objects are equal, {@code false} if object
  2098.      * is {@code null}, not an instance of {@code DD}, or not equal to
  2099.      * this instance.
  2100.      * @see Double#doubleToLongBits(double)
  2101.      * @see java.util.Arrays#equals(double[], double[])
  2102.      */
  2103.     @Override
  2104.     public boolean equals(Object other) {
  2105.         if (this == other) {
  2106.             return true;
  2107.         }
  2108.         if (other instanceof DD) {
  2109.             final DD c = (DD) other;
  2110.             return equals(x, c.x) && equals(xx, c.xx);
  2111.         }
  2112.         return false;
  2113.     }

  2114.     /**
  2115.      * Gets a hash code for the double-double number.
  2116.      *
  2117.      * <p>The behavior is the same as if the parts of the double-double number were passed
  2118.      * to {@link java.util.Arrays#hashCode(double[]) Arrays.hashCode(double[])}:
  2119.      *
  2120.      * <pre>
  2121.      *  {@code Arrays.hashCode(new double[] {hi() + 0.0, lo() + 0.0})}</pre>
  2122.      *
  2123.      * <p>Note: Addition of {@code 0.0} provides the same hash code for different
  2124.      * signed representations of zero values {@code -0.0} and {@code 0.0}.
  2125.      *
  2126.      * @return A hash code value for this object.
  2127.      * @see java.util.Arrays#hashCode(double[]) Arrays.hashCode(double[])
  2128.      */
  2129.     @Override
  2130.     public int hashCode() {
  2131.         return 31 * (31 + Double.hashCode(x + 0.0)) + Double.hashCode(xx + 0.0);
  2132.     }

  2133.     /**
  2134.      * Returns {@code true} if the values are numerically equal.
  2135.      *
  2136.      * <p>Two {@code double} values are considered to be
  2137.      * the same if and only if the method call
  2138.      * {@link Double#doubleToLongBits(double) Double.doubleToLongBits(value + 0.0)}
  2139.      * returns the identical {@code long} when applied to each value. This provides
  2140.      * numeric equality of different representations of zero as per {@code -0.0 == 0.0},
  2141.      * and equality of {@code NaN} values.
  2142.      *
  2143.      * @param x Value
  2144.      * @param y Value
  2145.      * @return {@code true} if the values are numerically equal
  2146.      */
  2147.     private static boolean equals(double x, double y) {
  2148.         return Double.doubleToLongBits(x + 0.0) == Double.doubleToLongBits(y + 0.0);
  2149.     }

  2150.     /**
  2151.      * Returns a string representation of the double-double number.
  2152.      *
  2153.      * <p>The string will represent the numeric values of the parts.
  2154.      * The values are split by a separator and surrounded by parentheses.
  2155.      *
  2156.      * <p>The format for a double-double number is {@code "(x,xx)"}, with {@code x} and
  2157.      * {@code xx} converted as if using {@link Double#toString(double)}.
  2158.      *
  2159.      * <p>Note: A numerical string representation of a finite double-double number can be
  2160.      * generated by conversion to a {@link BigDecimal} before formatting.
  2161.      *
  2162.      * @return A string representation of the double-double number.
  2163.      * @see Double#toString(double)
  2164.      * @see #bigDecimalValue()
  2165.      */
  2166.     @Override
  2167.     public String toString() {
  2168.         return new StringBuilder(TO_STRING_SIZE)
  2169.             .append(FORMAT_START)
  2170.             .append(x).append(FORMAT_SEP)
  2171.             .append(xx)
  2172.             .append(FORMAT_END)
  2173.             .toString();
  2174.     }

  2175.     /**
  2176.      * {@inheritDoc}
  2177.      *
  2178.      * <p>Note: Addition of this value with any element {@code a} may not create an
  2179.      * element equal to {@code a} if the element contains sign zeros. In this case the
  2180.      * magnitude of the result will be identical.
  2181.      */
  2182.     @Override
  2183.     public DD zero() {
  2184.         return ZERO;
  2185.     }

  2186.     /** {@inheritDoc} */
  2187.     @Override
  2188.     public boolean isZero() {
  2189.         // we keep |x| > |xx| and Java provides 0.0 == -0.0
  2190.         return x == 0.0;
  2191.     }

  2192.     /**
  2193.      * {@inheritDoc}
  2194.      *
  2195.      * <p>Note: Multiplication of this value with any element {@code a} may not create an
  2196.      * element equal to {@code a} if the element contains sign zeros. In this case the
  2197.      * magnitude of the result will be identical.
  2198.      */
  2199.     @Override
  2200.     public DD one() {
  2201.         return ONE;
  2202.     }

  2203.     /** {@inheritDoc} */
  2204.     @Override
  2205.     public boolean isOne() {
  2206.         return x == 1.0 && xx == 0.0;
  2207.     }

  2208.     /**
  2209.      * {@inheritDoc}
  2210.      *
  2211.      * <p>This computes the same result as {@link #multiply(double) multiply((double) y)}.
  2212.      *
  2213.      * @see #multiply(double)
  2214.      */
  2215.     @Override
  2216.     public DD multiply(int n) {
  2217.         // Note: This method exists to support the NativeOperators interface
  2218.         return multiply(x, xx, n);
  2219.     }
  2220. }