1 /*
   2  * Copyright (c) 1994, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.invoke.MethodHandles;
  29 import java.lang.constant.Constable;
  30 import java.lang.constant.ConstantDesc;
  31 import java.util.Optional;
  32 
  33 import jdk.internal.math.FloatingDecimal;
  34 import jdk.internal.math.DoubleConsts;
  35 import jdk.internal.math.DoubleToDecimal;
  36 import jdk.internal.vm.annotation.IntrinsicCandidate;
  37 
  38 /**
  39  * The {@code Double} class is the {@linkplain
  40  * java.lang##wrapperClass wrapper class} for values of the primitive
  41  * type {@code double}. An object of type {@code Double} contains a
  42  * single field whose type is {@code double}.
  43  *
  44  * <p>In addition, this class provides several methods for converting a
  45  * {@code double} to a {@code String} and a
  46  * {@code String} to a {@code double}, as well as other
  47  * constants and methods useful when dealing with a
  48  * {@code double}.
  49  *
  50  * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
  51  * class; programmers should treat instances that are
  52  * {@linkplain #equals(Object) equal} as interchangeable and should not
  53  * use instances for synchronization, or unpredictable behavior may
  54  * occur. For example, in a future release, synchronization may fail.
  55  *
  56  * <h2><a id=equivalenceRelation>Floating-point Equality, Equivalence,
  57  * and Comparison</a></h2>
  58  *
  59  * IEEE 754 floating-point values include finite nonzero values,
  60  * signed zeros ({@code +0.0} and {@code -0.0}), signed infinities
  61  * ({@linkplain Double#POSITIVE_INFINITY positive infinity} and
  62  * {@linkplain Double#NEGATIVE_INFINITY negative infinity}), and
  63  * {@linkplain Double#NaN NaN} (not-a-number).
  64  *
  65  * <p>An <em>equivalence relation</em> on a set of values is a boolean
  66  * relation on pairs of values that is reflexive, symmetric, and
  67  * transitive. For more discussion of equivalence relations and object
  68  * equality, see the {@link Object#equals Object.equals}
  69  * specification. An equivalence relation partitions the values it
  70  * operates over into sets called <i>equivalence classes</i>.  All the
  71  * members of the equivalence class are equal to each other under the
  72  * relation. An equivalence class may contain only a single member. At
  73  * least for some purposes, all the members of an equivalence class
  74  * are substitutable for each other.  In particular, in a numeric
  75  * expression equivalent values can be <em>substituted</em> for one
  76  * another without changing the result of the expression, meaning
  77  * changing the equivalence class of the result of the expression.
  78  *
  79  * <p>Notably, the built-in {@code ==} operation on floating-point
  80  * values is <em>not</em> an equivalence relation. Despite not
  81  * defining an equivalence relation, the semantics of the IEEE 754
  82  * {@code ==} operator were deliberately designed to meet other needs
  83  * of numerical computation. There are two exceptions where the
  84  * properties of an equivalence relation are not satisfied by {@code
  85  * ==} on floating-point values:
  86  *
  87  * <ul>
  88  *
  89  * <li>If {@code v1} and {@code v2} are both NaN, then {@code v1
  90  * == v2} has the value {@code false}. Therefore, for two NaN
  91  * arguments the <em>reflexive</em> property of an equivalence
  92  * relation is <em>not</em> satisfied by the {@code ==} operator.
  93  *
  94  * <li>If {@code v1} represents {@code +0.0} while {@code v2}
  95  * represents {@code -0.0}, or vice versa, then {@code v1 == v2} has
  96  * the value {@code true} even though {@code +0.0} and {@code -0.0}
  97  * are distinguishable under various floating-point operations. For
  98  * example, {@code 1.0/+0.0} evaluates to positive infinity while
  99  * {@code 1.0/-0.0} evaluates to <em>negative</em> infinity and
 100  * positive infinity and negative infinity are neither equal to each
 101  * other nor equivalent to each other. Thus, while a signed zero input
 102  * most commonly determines the sign of a zero result, because of
 103  * dividing by zero, {@code +0.0} and {@code -0.0} may not be
 104  * substituted for each other in general. The sign of a zero input
 105  * also has a non-substitutable effect on the result of some math
 106  * library methods.
 107  *
 108  * </ul>
 109  *
 110  * <p>For ordered comparisons using the built-in comparison operators
 111  * ({@code <}, {@code <=}, etc.), NaN values have another anomalous
 112  * situation: a NaN is neither less than, nor greater than, nor equal
 113  * to any value, including itself. This means the <i>trichotomy of
 114  * comparison</i> does <em>not</em> hold.
 115  *
 116  * <p>To provide the appropriate semantics for {@code equals} and
 117  * {@code compareTo} methods, those methods cannot simply be wrappers
 118  * around {@code ==} or ordered comparison operations. Instead, {@link
 119  * Double#equals equals} uses {@linkplain ##repEquivalence representation
 120  * equivalence}, defining NaN arguments to be equal to each other,
 121  * restoring reflexivity, and defining {@code +0.0} to <em>not</em> be
 122  * equal to {@code -0.0}. For comparisons, {@link Double#compareTo
 123  * compareTo} defines a total order where {@code -0.0} is less than
 124  * {@code +0.0} and where a NaN is equal to itself and considered
 125  * greater than positive infinity.
 126  *
 127  * <p>The operational semantics of {@code equals} and {@code
 128  * compareTo} are expressed in terms of {@linkplain #doubleToLongBits
 129  * bit-wise converting} the floating-point values to integral values.
 130  *
 131  * <p>The <em>natural ordering</em> implemented by {@link #compareTo
 132  * compareTo} is {@linkplain Comparable consistent with equals}. That
 133  * is, two objects are reported as equal by {@code equals} if and only
 134  * if {@code compareTo} on those objects returns zero.
 135  *
 136  * <p>The adjusted behaviors defined for {@code equals} and {@code
 137  * compareTo} allow instances of wrapper classes to work properly with
 138  * conventional data structures. For example, defining NaN
 139  * values to be {@code equals} to one another allows NaN to be used as
 140  * an element of a {@link java.util.HashSet HashSet} or as the key of
 141  * a {@link java.util.HashMap HashMap}. Similarly, defining {@code
 142  * compareTo} as a total ordering, including {@code +0.0}, {@code
 143  * -0.0}, and NaN, allows instances of wrapper classes to be used as
 144  * elements of a {@link java.util.SortedSet SortedSet} or as keys of a
 145  * {@link java.util.SortedMap SortedMap}.
 146  *
 147  * <p>Comparing numerical equality to various useful equivalence
 148  * relations that can be defined over floating-point values:
 149  *
 150  * <dl>
 151  * <dt><a id=fpNumericalEq></a><dfn>{@index "numerical equality"}</dfn> ({@code ==}
 152  * operator): (<em>Not</em> an equivalence relation)</dt>
 153  * <dd>Two floating-point values represent the same extended real
 154  * number. The extended real numbers are the real numbers augmented
 155  * with positive infinity and negative infinity. Under numerical
 156  * equality, {@code +0.0} and {@code -0.0} are equal since they both
 157  * map to the same real value, 0. A NaN does not map to any real
 158  * number and is not equal to any value, including itself.
 159  * </dd>
 160  *
 161  * <dt><dfn>{@index "bit-wise equivalence"}</dfn>:</dt>
 162  * <dd>The bits of the two floating-point values are the same. This
 163  * equivalence relation for {@code double} values {@code a} and {@code
 164  * b} is implemented by the expression
 165  * <br>{@code Double.doubleTo}<code><b>Raw</b></code>{@code LongBits(a) == Double.doubleTo}<code><b>Raw</b></code>{@code LongBits(b)}<br>
 166  * Under this relation, {@code +0.0} and {@code -0.0} are
 167  * distinguished from each other and every bit pattern encoding a NaN
 168  * is distinguished from every other bit pattern encoding a NaN.
 169  * </dd>
 170  *
 171  * <dt><dfn><a id=repEquivalence></a>{@index "representation equivalence"}</dfn>:</dt>
 172  * <dd>The two floating-point values represent the same IEEE 754
 173  * <i>datum</i>. In particular, for {@linkplain #isFinite(double)
 174  * finite} values, the sign, {@linkplain Math#getExponent(double)
 175  * exponent}, and significand components of the floating-point values
 176  * are the same. Under this relation:
 177  * <ul>
 178  * <li> {@code +0.0} and {@code -0.0} are distinguished from each other.
 179  * <li> every bit pattern encoding a NaN is considered equivalent to each other
 180  * <li> positive infinity is equivalent to positive infinity; negative
 181  *      infinity is equivalent to negative infinity.
 182  * </ul>
 183  * Expressions implementing this equivalence relation include:
 184  * <ul>
 185  * <li>{@code Double.doubleToLongBits(a) == Double.doubleToLongBits(b)}
 186  * <li>{@code Double.valueOf(a).equals(Double.valueOf(b))}
 187  * <li>{@code Double.compare(a, b) == 0}
 188  * </ul>
 189  * Note that representation equivalence is often an appropriate notion
 190  * of equivalence to test the behavior of {@linkplain StrictMath math
 191  * libraries}.
 192  * </dd>
 193  * </dl>
 194  *
 195  * For two binary floating-point values {@code a} and {@code b}, if
 196  * neither of {@code a} and {@code b} is zero or NaN, then the three
 197  * relations numerical equality, bit-wise equivalence, and
 198  * representation equivalence of {@code a} and {@code b} have the same
 199  * {@code true}/{@code false} value. In other words, for binary
 200  * floating-point values, the three relations only differ if at least
 201  * one argument is zero or NaN.
 202  *
 203  * <h2><a id=decimalToBinaryConversion>Decimal &harr; Binary Conversion Issues</a></h2>
 204  *
 205  * Many surprising results of binary floating-point arithmetic trace
 206  * back to aspects of decimal to binary conversion and binary to
 207  * decimal conversion. While integer values can be exactly represented
 208  * in any base, which fractional values can be exactly represented in
 209  * a base is a function of the base. For example, in base 10, 1/3 is a
 210  * repeating fraction (0.33333....); but in base 3, 1/3 is exactly
 211  * 0.1<sub>(3)</sub>, that is 1&nbsp;&times;&nbsp;3<sup>-1</sup>.
 212  * Similarly, in base 10, 1/10 is exactly representable as 0.1
 213  * (1&nbsp;&times;&nbsp;10<sup>-1</sup>), but in base 2, it is a
 214  * repeating fraction (0.0001100110011...<sub>(2)</sub>).
 215  *
 216  * <p>Values of the {@code float} type have {@value Float#PRECISION}
 217  * bits of precision and values of the {@code double} type have
 218  * {@value Double#PRECISION} bits of precision. Therefore, since 0.1
 219  * is a repeating fraction in base 2 with a four-bit repeat, {@code
 220  * 0.1f} != {@code 0.1d}. In more detail, including hexadecimal
 221  * floating-point literals:
 222  *
 223  * <ul>
 224  * <li>The exact numerical value of {@code 0.1f} ({@code 0x1.99999a0000000p-4f}) is
 225  *     0.100000001490116119384765625.
 226  * <li>The exact numerical value of {@code 0.1d} ({@code 0x1.999999999999ap-4d}) is
 227  *     0.1000000000000000055511151231257827021181583404541015625.
 228  * </ul>
 229  *
 230  * These are the closest {@code float} and {@code double} values,
 231  * respectively, to the numerical value of 0.1.  These results are
 232  * consistent with a {@code float} value having the equivalent of 6 to
 233  * 9 digits of decimal precision and a {@code double} value having the
 234  * equivalent of 15 to 17 digits of decimal precision. (The
 235  * equivalent precision varies according to the different relative
 236  * densities of binary and decimal values at different points along the
 237  * real number line.)
 238  *
 239  * <p>This representation hazard of decimal fractions is one reason to
 240  * use caution when storing monetary values as {@code float} or {@code
 241  * double}. Alternatives include:
 242  * <ul>
 243  * <li>using {@link java.math.BigDecimal BigDecimal} to store decimal
 244  * fractional values exactly
 245  *
 246  * <li>scaling up so the monetary value is an integer &mdash; for
 247  * example, multiplying by 100 if the value is denominated in cents or
 248  * multiplying by 1000 if the value is denominated in mills &mdash;
 249  * and then storing that scaled value in an integer type
 250  *
 251  *</ul>
 252  *
 253  * <p>For each finite floating-point value and a given floating-point
 254  * type, there is a contiguous region of the real number line which
 255  * maps to that value. Under the default round to nearest rounding
 256  * policy (JLS {@jls 15.4}), this contiguous region for a value is
 257  * typically one {@linkplain Math#ulp ulp} (unit in the last place)
 258  * wide and centered around the exactly representable value. (At
 259  * exponent boundaries, the region is asymmetrical and larger on the
 260  * side with the larger exponent.) For example, for {@code 0.1f}, the
 261  * region can be computed as follows:
 262  *
 263  * <br>// Numeric values listed are exact values
 264  * <br>oneTenthApproxAsFloat = 0.100000001490116119384765625;
 265  * <br>ulpOfoneTenthApproxAsFloat = Math.ulp(0.1f) = 7.450580596923828125E-9;
 266  * <br>// Numeric range that is converted to the float closest to 0.1, _excludes_ endpoints
 267  * <br>(oneTenthApproxAsFloat - &frac12;ulpOfoneTenthApproxAsFloat, oneTenthApproxAsFloat + &frac12;ulpOfoneTenthApproxAsFloat) =
 268  * <br>(0.0999999977648258209228515625, 0.1000000052154064178466796875)
 269  *
 270  * <p>In particular, a correctly rounded decimal to binary conversion
 271  * of any string representing a number in this range, say by {@link
 272  * Float#parseFloat(String)}, will be converted to the same value:
 273  *
 274  * {@snippet lang="java" :
 275  * Float.parseFloat("0.0999999977648258209228515625000001"); // rounds up to oneTenthApproxAsFloat
 276  * Float.parseFloat("0.099999998");                          // rounds up to oneTenthApproxAsFloat
 277  * Float.parseFloat("0.1");                                  // rounds up to oneTenthApproxAsFloat
 278  * Float.parseFloat("0.100000001490116119384765625");        // exact conversion
 279  * Float.parseFloat("0.100000005215406417846679687");        // rounds down to oneTenthApproxAsFloat
 280  * Float.parseFloat("0.100000005215406417846679687499999");  // rounds down to oneTenthApproxAsFloat
 281  * }
 282  *
 283  * <p>Similarly, an analogous range can be constructed  for the {@code
 284  * double} type based on the exact value of {@code double}
 285  * approximation to {@code 0.1d} and the numerical value of {@code
 286  * Math.ulp(0.1d)} and likewise for other particular numerical values
 287  * in the {@code float} and {@code double} types.
 288  *
 289  * <p>As seen in the above conversions, compared to the exact
 290  * numerical value the operation would have without rounding, the same
 291  * floating-point value as a result can be:
 292  * <ul>
 293  * <li>greater than the exact result
 294  * <li>equal to the exact result
 295  * <li>less than the exact result
 296  * </ul>
 297  *
 298  * A floating-point value doesn't "know" whether it was the result of
 299  * rounding up, or rounding down, or an exact operation; it contains
 300  * no history of how it was computed. Consequently, the sum of
 301  * {@snippet lang="java" :
 302  * 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f;
 303  * // Numerical value of computed sum: 1.00000011920928955078125,
 304  * // the next floating-point value larger than 1.0f, equal to Math.nextUp(1.0f).
 305  * }
 306  * or
 307  * {@snippet lang="java" :
 308  * 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d;
 309  * // Numerical value of computed sum: 0.99999999999999988897769753748434595763683319091796875,
 310  * // the next floating-point value smaller than 1.0d, equal to Math.nextDown(1.0d).
 311  * }
 312  *
 313  * should <em>not</em> be expected to be exactly equal to 1.0, but
 314  * only to be close to 1.0. Consequently, the following code is an
 315  * infinite loop:
 316  *
 317  * {@snippet lang="java" :
 318  * double d = 0.0;
 319  * while (d != 1.0) { // Surprising infinite loop
 320  *   d += 0.1; // Sum never _exactly_ equals 1.0
 321  * }
 322  * }
 323  *
 324  * Instead, use an integer loop count for counted loops:
 325  *
 326  * {@snippet lang="java" :
 327  * double d = 0.0;
 328  * for (int i = 0; i < 10; i++) {
 329  *   d += 0.1;
 330  * } // Value of d is equal to Math.nextDown(1.0).
 331  * }
 332  *
 333  * or test against a floating-point limit using ordered comparisons
 334  * ({@code <}, {@code <=}, {@code >}, {@code >=}):
 335  *
 336  * {@snippet lang="java" :
 337  *  double d = 0.0;
 338  *  while (d <= 1.0) {
 339  *    d += 0.1;
 340  *  } // Value of d approximately 1.0999999999999999
 341  *  }
 342  *
 343  * While floating-point arithmetic may have surprising results, IEEE
 344  * 754 floating-point arithmetic follows a principled design and its
 345  * behavior is predictable on the Java platform.
 346  *
 347  * @jls 4.2.3 Floating-Point Types and Values
 348  * @jls 4.2.4 Floating-Point Operations
 349  * @jls 15.21.1 Numerical Equality Operators == and !=
 350  * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
 351  *
 352  * @spec https://standards.ieee.org/ieee/754/6210/
 353  *       IEEE Standard for Floating-Point Arithmetic
 354  *
 355  * @since 1.0
 356  */
 357 @jdk.internal.ValueBased
 358 public final class Double extends Number
 359         implements Comparable<Double>, Constable, ConstantDesc {
 360     /**
 361      * A constant holding the positive infinity of type
 362      * {@code double}. It is equal to the value returned by
 363      * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
 364      */
 365     public static final double POSITIVE_INFINITY = 1.0 / 0.0;
 366 
 367     /**
 368      * A constant holding the negative infinity of type
 369      * {@code double}. It is equal to the value returned by
 370      * {@code Double.longBitsToDouble(0xfff0000000000000L)}.
 371      */
 372     public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
 373 
 374     /**
 375      * A constant holding a Not-a-Number (NaN) value of type {@code double}.
 376      * It is {@linkplain Double##equivalenceRelation equivalent} to the
 377      * value returned by {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
 378      */
 379     public static final double NaN = 0.0d / 0.0;
 380 
 381     /**
 382      * A constant holding the largest positive finite value of type
 383      * {@code double},
 384      * (2-2<sup>-52</sup>)&middot;2<sup>1023</sup>.  It is equal to
 385      * the hexadecimal floating-point literal
 386      * {@code 0x1.fffffffffffffP+1023} and also equal to
 387      * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
 388      */
 389     public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308
 390 
 391     /**
 392      * A constant holding the smallest positive normal value of type
 393      * {@code double}, 2<sup>-1022</sup>.  It is equal to the
 394      * hexadecimal floating-point literal {@code 0x1.0p-1022} and also
 395      * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}.
 396      *
 397      * @since 1.6
 398      */
 399     public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308
 400 
 401     /**
 402      * A constant holding the smallest positive nonzero value of type
 403      * {@code double}, 2<sup>-1074</sup>. It is equal to the
 404      * hexadecimal floating-point literal
 405      * {@code 0x0.0000000000001P-1022} and also equal to
 406      * {@code Double.longBitsToDouble(0x1L)}.
 407      */
 408     public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324
 409 
 410     /**
 411      * The number of bits used to represent a {@code double} value,
 412      * {@value}.
 413      *
 414      * @since 1.5
 415      */
 416     public static final int SIZE = 64;
 417 
 418     /**
 419      * The number of bits in the significand of a {@code double}
 420      * value, {@value}.  This is the parameter N in section {@jls
 421      * 4.2.3} of <cite>The Java Language Specification</cite>.
 422      *
 423      * @since 19
 424      */
 425     public static final int PRECISION = 53;
 426 
 427     /**
 428      * Maximum exponent a finite {@code double} variable may have,
 429      * {@value}.  It is equal to the value returned by {@code
 430      * Math.getExponent(Double.MAX_VALUE)}.
 431      *
 432      * @since 1.6
 433      */
 434     public static final int MAX_EXPONENT = (1 << (SIZE - PRECISION - 1)) - 1; // 1023
 435 
 436     /**
 437      * Minimum exponent a normalized {@code double} variable may have,
 438      * {@value}.  It is equal to the value returned by {@code
 439      * Math.getExponent(Double.MIN_NORMAL)}.
 440      *
 441      * @since 1.6
 442      */
 443     public static final int MIN_EXPONENT = 1 - MAX_EXPONENT; // -1022
 444 
 445     /**
 446      * The number of bytes used to represent a {@code double} value,
 447      * {@value}.
 448      *
 449      * @since 1.8
 450      */
 451     public static final int BYTES = SIZE / Byte.SIZE;
 452 
 453     /**
 454      * The {@code Class} instance representing the primitive type
 455      * {@code double}.
 456      *
 457      * @since 1.1
 458      */
 459     public static final Class<Double> TYPE = Class.getPrimitiveClass("double");
 460 
 461     /**
 462      * Returns a string representation of the {@code double}
 463      * argument. All characters mentioned below are ASCII characters.
 464      * <ul>
 465      * <li>If the argument is NaN, the result is the string
 466      *     "{@code NaN}".
 467      * <li>Otherwise, the result is a string that represents the sign and
 468      * magnitude (absolute value) of the argument. If the sign is negative,
 469      * the first character of the result is '{@code -}'
 470      * ({@code '\u005Cu002D'}); if the sign is positive, no sign character
 471      * appears in the result. As for the magnitude <i>m</i>:
 472      * <ul>
 473      * <li>If <i>m</i> is infinity, it is represented by the characters
 474      * {@code "Infinity"}; thus, positive infinity produces the result
 475      * {@code "Infinity"} and negative infinity produces the result
 476      * {@code "-Infinity"}.
 477      *
 478      * <li>If <i>m</i> is zero, it is represented by the characters
 479      * {@code "0.0"}; thus, negative zero produces the result
 480      * {@code "-0.0"} and positive zero produces the result
 481      * {@code "0.0"}.
 482      *
 483      * <li> Otherwise <i>m</i> is positive and finite.
 484      * It is converted to a string in two stages:
 485      * <ul>
 486      * <li> <em>Selection of a decimal</em>:
 487      * A well-defined decimal <i>d</i><sub><i>m</i></sub>
 488      * is selected to represent <i>m</i>.
 489      * This decimal is (almost always) the <em>shortest</em> one that
 490      * rounds to <i>m</i> according to the round to nearest
 491      * rounding policy of IEEE 754 floating-point arithmetic.
 492      * <li> <em>Formatting as a string</em>:
 493      * The decimal <i>d</i><sub><i>m</i></sub> is formatted as a string,
 494      * either in plain or in computerized scientific notation,
 495      * depending on its value.
 496      * </ul>
 497      * </ul>
 498      * </ul>
 499      *
 500      * <p>A <em>decimal</em> is a number of the form
 501      * <i>s</i>&times;10<sup><i>i</i></sup>
 502      * for some (unique) integers <i>s</i> &gt; 0 and <i>i</i> such that
 503      * <i>s</i> is not a multiple of 10.
 504      * These integers are the <em>significand</em> and
 505      * the <em>exponent</em>, respectively, of the decimal.
 506      * The <em>length</em> of the decimal is the (unique)
 507      * positive integer <i>n</i> meeting
 508      * 10<sup><i>n</i>-1</sup> &le; <i>s</i> &lt; 10<sup><i>n</i></sup>.
 509      *
 510      * <p>The decimal <i>d</i><sub><i>m</i></sub> for a finite positive <i>m</i>
 511      * is defined as follows:
 512      * <ul>
 513      * <li>Let <i>R</i> be the set of all decimals that round to <i>m</i>
 514      * according to the usual <em>round to nearest</em> rounding policy of
 515      * IEEE 754 floating-point arithmetic.
 516      * <li>Let <i>p</i> be the minimal length over all decimals in <i>R</i>.
 517      * <li>When <i>p</i> &ge; 2, let <i>T</i> be the set of all decimals
 518      * in <i>R</i> with length <i>p</i>.
 519      * Otherwise, let <i>T</i> be the set of all decimals
 520      * in <i>R</i> with length 1 or 2.
 521      * <li>Define <i>d</i><sub><i>m</i></sub> as the decimal in <i>T</i>
 522      * that is closest to <i>m</i>.
 523      * Or if there are two such decimals in <i>T</i>,
 524      * select the one with the even significand.
 525      * </ul>
 526      *
 527      * <p>The (uniquely) selected decimal <i>d</i><sub><i>m</i></sub>
 528      * is then formatted.
 529      * Let <i>s</i>, <i>i</i> and <i>n</i> be the significand, exponent and
 530      * length of <i>d</i><sub><i>m</i></sub>, respectively.
 531      * Further, let <i>e</i> = <i>n</i> + <i>i</i> - 1 and let
 532      * <i>s</i><sub>1</sub>&hellip;<i>s</i><sub><i>n</i></sub>
 533      * be the usual decimal expansion of <i>s</i>.
 534      * Note that <i>s</i><sub>1</sub> &ne; 0
 535      * and <i>s</i><sub><i>n</i></sub> &ne; 0.
 536      * Below, the decimal point {@code '.'} is {@code '\u005Cu002E'}
 537      * and the exponent indicator {@code 'E'} is {@code '\u005Cu0045'}.
 538      * <ul>
 539      * <li>Case -3 &le; <i>e</i> &lt; 0:
 540      * <i>d</i><sub><i>m</i></sub> is formatted as
 541      * <code>0.0</code>&hellip;<code>0</code><!--
 542      * --><i>s</i><sub>1</sub>&hellip;<i>s</i><sub><i>n</i></sub>,
 543      * where there are exactly -(<i>n</i> + <i>i</i>) zeroes between
 544      * the decimal point and <i>s</i><sub>1</sub>.
 545      * For example, 123 &times; 10<sup>-4</sup> is formatted as
 546      * {@code 0.0123}.
 547      * <li>Case 0 &le; <i>e</i> &lt; 7:
 548      * <ul>
 549      * <li>Subcase <i>i</i> &ge; 0:
 550      * <i>d</i><sub><i>m</i></sub> is formatted as
 551      * <i>s</i><sub>1</sub>&hellip;<i>s</i><sub><i>n</i></sub><!--
 552      * --><code>0</code>&hellip;<code>0.0</code>,
 553      * where there are exactly <i>i</i> zeroes
 554      * between <i>s</i><sub><i>n</i></sub> and the decimal point.
 555      * For example, 123 &times; 10<sup>2</sup> is formatted as
 556      * {@code 12300.0}.
 557      * <li>Subcase <i>i</i> &lt; 0:
 558      * <i>d</i><sub><i>m</i></sub> is formatted as
 559      * <i>s</i><sub>1</sub>&hellip;<!--
 560      * --><i>s</i><sub><i>n</i>+<i>i</i></sub><code>.</code><!--
 561      * --><i>s</i><sub><i>n</i>+<i>i</i>+1</sub>&hellip;<!--
 562      * --><i>s</i><sub><i>n</i></sub>,
 563      * where there are exactly -<i>i</i> digits to the right of
 564      * the decimal point.
 565      * For example, 123 &times; 10<sup>-1</sup> is formatted as
 566      * {@code 12.3}.
 567      * </ul>
 568      * <li>Case <i>e</i> &lt; -3 or <i>e</i> &ge; 7:
 569      * computerized scientific notation is used to format
 570      * <i>d</i><sub><i>m</i></sub>.
 571      * Here <i>e</i> is formatted as by {@link Integer#toString(int)}.
 572      * <ul>
 573      * <li>Subcase <i>n</i> = 1:
 574      * <i>d</i><sub><i>m</i></sub> is formatted as
 575      * <i>s</i><sub>1</sub><code>.0E</code><i>e</i>.
 576      * For example, 1 &times; 10<sup>23</sup> is formatted as
 577      * {@code 1.0E23}.
 578      * <li>Subcase <i>n</i> &gt; 1:
 579      * <i>d</i><sub><i>m</i></sub> is formatted as
 580      * <i>s</i><sub>1</sub><code>.</code><i>s</i><sub>2</sub><!--
 581      * -->&hellip;<i>s</i><sub><i>n</i></sub><code>E</code><i>e</i>.
 582      * For example, 123 &times; 10<sup>-21</sup> is formatted as
 583      * {@code 1.23E-19}.
 584      * </ul>
 585      * </ul>
 586      *
 587      * <p>To create localized string representations of a floating-point
 588      * value, use subclasses of {@link java.text.NumberFormat}.
 589      *
 590      * @apiNote
 591      * This method corresponds to the general functionality of the
 592      * convertToDecimalCharacter operation defined in IEEE 754;
 593      * however, that operation is defined in terms of specifying the
 594      * number of significand digits used in the conversion.
 595      * Code to do such a conversion in the Java platform includes
 596      * converting the {@code double} to a {@link java.math.BigDecimal
 597      * BigDecimal} exactly and then rounding the {@code BigDecimal} to
 598      * the desired number of digits; sample code:
 599      * {@snippet lang=java :
 600      * double d = 0.1;
 601      * int digits = 25;
 602      * BigDecimal bd = new BigDecimal(d);
 603      * String result = bd.round(new MathContext(digits,  RoundingMode.HALF_UP));
 604      * // 0.1000000000000000055511151
 605      * }
 606      *
 607      * @param   d   the {@code double} to be converted.
 608      * @return a string representation of the argument.
 609      */
 610     public static String toString(double d) {
 611         return DoubleToDecimal.toString(d);
 612     }
 613 
 614     /**
 615      * Returns a hexadecimal string representation of the
 616      * {@code double} argument. All characters mentioned below
 617      * are ASCII characters.
 618      *
 619      * <ul>
 620      * <li>If the argument is NaN, the result is the string
 621      *     "{@code NaN}".
 622      * <li>Otherwise, the result is a string that represents the sign
 623      * and magnitude of the argument. If the sign is negative, the
 624      * first character of the result is '{@code -}'
 625      * ({@code '\u005Cu002D'}); if the sign is positive, no sign
 626      * character appears in the result. As for the magnitude <i>m</i>:
 627      *
 628      * <ul>
 629      * <li>If <i>m</i> is infinity, it is represented by the string
 630      * {@code "Infinity"}; thus, positive infinity produces the
 631      * result {@code "Infinity"} and negative infinity produces
 632      * the result {@code "-Infinity"}.
 633      *
 634      * <li>If <i>m</i> is zero, it is represented by the string
 635      * {@code "0x0.0p0"}; thus, negative zero produces the result
 636      * {@code "-0x0.0p0"} and positive zero produces the result
 637      * {@code "0x0.0p0"}.
 638      *
 639      * <li>If <i>m</i> is a {@code double} value with a
 640      * normalized representation, substrings are used to represent the
 641      * significand and exponent fields.  The significand is
 642      * represented by the characters {@code "0x1."}
 643      * followed by a lowercase hexadecimal representation of the rest
 644      * of the significand as a fraction.  Trailing zeros in the
 645      * hexadecimal representation are removed unless all the digits
 646      * are zero, in which case a single zero is used. Next, the
 647      * exponent is represented by {@code "p"} followed
 648      * by a decimal string of the unbiased exponent as if produced by
 649      * a call to {@link Integer#toString(int) Integer.toString} on the
 650      * exponent value.
 651      *
 652      * <li>If <i>m</i> is a {@code double} value with a subnormal
 653      * representation, the significand is represented by the
 654      * characters {@code "0x0."} followed by a
 655      * hexadecimal representation of the rest of the significand as a
 656      * fraction.  Trailing zeros in the hexadecimal representation are
 657      * removed. Next, the exponent is represented by
 658      * {@code "p-1022"}.  Note that there must be at
 659      * least one nonzero digit in a subnormal significand.
 660      *
 661      * </ul>
 662      *
 663      * </ul>
 664      *
 665      * <table class="striped">
 666      * <caption>Examples</caption>
 667      * <thead>
 668      * <tr><th scope="col">Floating-point Value</th><th scope="col">Hexadecimal String</th>
 669      * </thead>
 670      * <tbody style="text-align:right">
 671      * <tr><th scope="row">{@code 1.0}</th> <td>{@code 0x1.0p0}</td>
 672      * <tr><th scope="row">{@code -1.0}</th>        <td>{@code -0x1.0p0}</td>
 673      * <tr><th scope="row">{@code 2.0}</th> <td>{@code 0x1.0p1}</td>
 674      * <tr><th scope="row">{@code 3.0}</th> <td>{@code 0x1.8p1}</td>
 675      * <tr><th scope="row">{@code 0.5}</th> <td>{@code 0x1.0p-1}</td>
 676      * <tr><th scope="row">{@code 0.25}</th>        <td>{@code 0x1.0p-2}</td>
 677      * <tr><th scope="row">{@code Double.MAX_VALUE}</th>
 678      *     <td>{@code 0x1.fffffffffffffp1023}</td>
 679      * <tr><th scope="row">{@code Minimum Normal Value}</th>
 680      *     <td>{@code 0x1.0p-1022}</td>
 681      * <tr><th scope="row">{@code Maximum Subnormal Value}</th>
 682      *     <td>{@code 0x0.fffffffffffffp-1022}</td>
 683      * <tr><th scope="row">{@code Double.MIN_VALUE}</th>
 684      *     <td>{@code 0x0.0000000000001p-1022}</td>
 685      * </tbody>
 686      * </table>
 687      *
 688      * @apiNote
 689      * This method corresponds to the convertToHexCharacter operation
 690      * defined in IEEE 754.
 691      *
 692      * @param   d   the {@code double} to be converted.
 693      * @return a hex string representation of the argument.
 694      * @since 1.5
 695      */
 696     public static String toHexString(double d) {
 697         /*
 698          * Modeled after the "a" conversion specifier in C99, section
 699          * 7.19.6.1; however, the output of this method is more
 700          * tightly specified.
 701          */
 702         if (!isFinite(d) )
 703             // For infinity and NaN, use the decimal output.
 704             return Double.toString(d);
 705         else {
 706             // Initialized to maximum size of output.
 707             StringBuilder answer = new StringBuilder(24);
 708 
 709             if (Math.copySign(1.0, d) == -1.0)    // value is negative,
 710                 answer.append("-");                  // so append sign info
 711 
 712             answer.append("0x");
 713 
 714             d = Math.abs(d);
 715 
 716             if(d == 0.0) {
 717                 answer.append("0.0p0");
 718             } else {
 719                 boolean subnormal = (d < Double.MIN_NORMAL);
 720 
 721                 // Isolate significand bits and OR in a high-order bit
 722                 // so that the string representation has a known
 723                 // length.
 724                 long signifBits = (Double.doubleToLongBits(d)
 725                                    & DoubleConsts.SIGNIF_BIT_MASK) |
 726                     0x1000000000000000L;
 727 
 728                 // Subnormal values have a 0 implicit bit; normal
 729                 // values have a 1 implicit bit.
 730                 answer.append(subnormal ? "0." : "1.");
 731 
 732                 // Isolate the low-order 13 digits of the hex
 733                 // representation.  If all the digits are zero,
 734                 // replace with a single 0; otherwise, remove all
 735                 // trailing zeros.
 736                 String signif = Long.toHexString(signifBits).substring(3,16);
 737                 answer.append(signif.equals("0000000000000") ? // 13 zeros
 738                               "0":
 739                               signif.replaceFirst("0{1,12}$", ""));
 740 
 741                 answer.append('p');
 742                 // If the value is subnormal, use the E_min exponent
 743                 // value for double; otherwise, extract and report d's
 744                 // exponent (the representation of a subnormal uses
 745                 // E_min -1).
 746                 answer.append(subnormal ?
 747                               Double.MIN_EXPONENT:
 748                               Math.getExponent(d));
 749             }
 750             return answer.toString();
 751         }
 752     }
 753 
 754     /**
 755      * Returns a {@code Double} object holding the
 756      * {@code double} value represented by the argument string
 757      * {@code s}.
 758      *
 759      * <p>If {@code s} is {@code null}, then a
 760      * {@code NullPointerException} is thrown.
 761      *
 762      * <p>Leading and trailing whitespace characters in {@code s}
 763      * are ignored.  Whitespace is removed as if by the {@link
 764      * String#trim} method; that is, both ASCII space and control
 765      * characters are removed. The rest of {@code s} should
 766      * constitute a <i>FloatValue</i> as described by the lexical
 767      * syntax rules:
 768      *
 769      * <blockquote>
 770      * <dl>
 771      * <dt><i>FloatValue:</i>
 772      * <dd><i>Sign<sub>opt</sub></i> {@code NaN}
 773      * <dd><i>Sign<sub>opt</sub></i> {@code Infinity}
 774      * <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i>
 775      * <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i>
 776      * <dd><i>SignedInteger</i>
 777      * </dl>
 778      *
 779      * <dl>
 780      * <dt><i>HexFloatingPointLiteral</i>:
 781      * <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i>
 782      * </dl>
 783      *
 784      * <dl>
 785      * <dt><i>HexSignificand:</i>
 786      * <dd><i>HexNumeral</i>
 787      * <dd><i>HexNumeral</i> {@code .}
 788      * <dd>{@code 0x} <i>HexDigits<sub>opt</sub>
 789      *     </i>{@code .}<i> HexDigits</i>
 790      * <dd>{@code 0X}<i> HexDigits<sub>opt</sub>
 791      *     </i>{@code .} <i>HexDigits</i>
 792      * </dl>
 793      *
 794      * <dl>
 795      * <dt><i>BinaryExponent:</i>
 796      * <dd><i>BinaryExponentIndicator SignedInteger</i>
 797      * </dl>
 798      *
 799      * <dl>
 800      * <dt><i>BinaryExponentIndicator:</i>
 801      * <dd>{@code p}
 802      * <dd>{@code P}
 803      * </dl>
 804      *
 805      * </blockquote>
 806      *
 807      * where <i>Sign</i>, <i>FloatingPointLiteral</i>,
 808      * <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and
 809      * <i>FloatTypeSuffix</i> are as defined in the lexical structure
 810      * sections of
 811      * <cite>The Java Language Specification</cite>,
 812      * except that underscores are not accepted between digits.
 813      * If {@code s} does not have the form of
 814      * a <i>FloatValue</i>, then a {@code NumberFormatException}
 815      * is thrown. Otherwise, {@code s} is regarded as
 816      * representing an exact decimal value in the usual
 817      * "computerized scientific notation" or as an exact
 818      * hexadecimal value; this exact numerical value is then
 819      * conceptually converted to an "infinitely precise"
 820      * binary value that is then rounded to type {@code double}
 821      * by the usual round-to-nearest rule of IEEE 754 floating-point
 822      * arithmetic, which includes preserving the sign of a zero
 823      * value.
 824      *
 825      * Note that the round-to-nearest rule also implies overflow and
 826      * underflow behaviour; if the exact value of {@code s} is large
 827      * enough in magnitude (greater than or equal to ({@link
 828      * #MAX_VALUE} + {@link Math#ulp(double) ulp(MAX_VALUE)}/2),
 829      * rounding to {@code double} will result in an infinity and if the
 830      * exact value of {@code s} is small enough in magnitude (less
 831      * than or equal to {@link #MIN_VALUE}/2), rounding to float will
 832      * result in a zero.
 833      *
 834      * Finally, after rounding a {@code Double} object representing
 835      * this {@code double} value is returned.
 836      *
 837      * <p>Note that trailing format specifiers, specifiers that
 838      * determine the type of a floating-point literal
 839      * ({@code 1.0f} is a {@code float} value;
 840      * {@code 1.0d} is a {@code double} value), do
 841      * <em>not</em> influence the results of this method.  In other
 842      * words, the numerical value of the input string is converted
 843      * directly to the target floating-point type.  The two-step
 844      * sequence of conversions, string to {@code float} followed
 845      * by {@code float} to {@code double}, is <em>not</em>
 846      * equivalent to converting a string directly to
 847      * {@code double}. For example, the {@code float}
 848      * literal {@code 0.1f} is equal to the {@code double}
 849      * value {@code 0.10000000149011612}; the {@code float}
 850      * literal {@code 0.1f} represents a different numerical
 851      * value than the {@code double} literal
 852      * {@code 0.1}. (The numerical value 0.1 cannot be exactly
 853      * represented in a binary floating-point number.)
 854      *
 855      * <p>To avoid calling this method on an invalid string and having
 856      * a {@code NumberFormatException} be thrown, the regular
 857      * expression below can be used to screen the input string:
 858      *
 859      * {@snippet lang="java" :
 860      *  final String Digits     = "(\\p{Digit}+)";
 861      *  final String HexDigits  = "(\\p{XDigit}+)";
 862      *  // an exponent is 'e' or 'E' followed by an optionally
 863      *  // signed decimal integer.
 864      *  final String Exp        = "[eE][+-]?"+Digits;
 865      *  final String fpRegex    =
 866      *      ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
 867      *       "[+-]?(" + // Optional sign character
 868      *       "NaN|" +           // "NaN" string
 869      *       "Infinity|" +      // "Infinity" string
 870      *
 871      *       // A decimal floating-point string representing a finite positive
 872      *       // number without a leading sign has at most five basic pieces:
 873      *       // Digits . Digits ExponentPart FloatTypeSuffix
 874      *       //
 875      *       // Since this method allows integer-only strings as input
 876      *       // in addition to strings of floating-point literals, the
 877      *       // two sub-patterns below are simplifications of the grammar
 878      *       // productions from section 3.10.2 of
 879      *       // The Java Language Specification.
 880      *
 881      *       // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
 882      *       "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
 883      *
 884      *       // . Digits ExponentPart_opt FloatTypeSuffix_opt
 885      *       "(\\.("+Digits+")("+Exp+")?)|"+
 886      *
 887      *       // Hexadecimal strings
 888      *       "((" +
 889      *        // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
 890      *        "(0[xX]" + HexDigits + "(\\.)?)|" +
 891      *
 892      *        // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
 893      *        "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
 894      *
 895      *        ")[pP][+-]?" + Digits + "))" +
 896      *       "[fFdD]?))" +
 897      *       "[\\x00-\\x20]*");// Optional trailing "whitespace"
 898      *  // @link region substring="Pattern.matches" target ="java.util.regex.Pattern#matches"
 899      *  if (Pattern.matches(fpRegex, myString))
 900      *      Double.valueOf(myString); // Will not throw NumberFormatException
 901      * // @end
 902      *  else {
 903      *      // Perform suitable alternative action
 904      *  }
 905      * }
 906      *
 907      * @apiNote To interpret localized string representations of a
 908      * floating-point value, or string representations that have
 909      * non-ASCII digits, use {@link java.text.NumberFormat}. For
 910      * example,
 911      * {@snippet lang="java" :
 912      *     NumberFormat.getInstance(l).parse(s).doubleValue();
 913      * }
 914      * where {@code l} is the desired locale, or
 915      * {@link java.util.Locale#ROOT} if locale insensitive.
 916      *
 917      * @apiNote
 918      * This method corresponds to the convertFromDecimalCharacter and
 919      * convertFromHexCharacter operations defined in IEEE 754.
 920      *
 921      * @param      s   the string to be parsed.
 922      * @return     a {@code Double} object holding the value
 923      *             represented by the {@code String} argument.
 924      * @throws     NumberFormatException  if the string does not contain a
 925      *             parsable number.
 926      * @see Double##decimalToBinaryConversion Decimal &harr; Binary Conversion Issues
 927      */
 928     public static Double valueOf(String s) throws NumberFormatException {
 929         return new Double(parseDouble(s));
 930     }
 931 
 932     /**
 933      * Returns a {@code Double} instance representing the specified
 934      * {@code double} value.
 935      * If a new {@code Double} instance is not required, this method
 936      * should generally be used in preference to the constructor
 937      * {@link #Double(double)}, as this method is likely to yield
 938      * significantly better space and time performance by caching
 939      * frequently requested values.
 940      *
 941      * @param  d a double value.
 942      * @return a {@code Double} instance representing {@code d}.
 943      * @since  1.5
 944      */
 945     @IntrinsicCandidate
 946     public static Double valueOf(double d) {
 947         return new Double(d);
 948     }
 949 
 950     /**
 951      * Returns a new {@code double} initialized to the value
 952      * represented by the specified {@code String}, as performed
 953      * by the {@code valueOf} method of class
 954      * {@code Double}.
 955      *
 956      * @param  s   the string to be parsed.
 957      * @return the {@code double} value represented by the string
 958      *         argument.
 959      * @throws NullPointerException  if the string is null
 960      * @throws NumberFormatException if the string does not contain
 961      *         a parsable {@code double}.
 962      * @see    java.lang.Double#valueOf(String)
 963      * @see    Double##decimalToBinaryConversion Decimal &harr; Binary Conversion Issues
 964      * @since 1.2
 965      */
 966     public static double parseDouble(String s) throws NumberFormatException {
 967         return FloatingDecimal.parseDouble(s);
 968     }
 969 
 970     /**
 971      * Returns {@code true} if the specified number is a
 972      * Not-a-Number (NaN) value, {@code false} otherwise.
 973      *
 974      * @apiNote
 975      * This method corresponds to the isNaN operation defined in IEEE
 976      * 754.
 977      *
 978      * @param   v   the value to be tested.
 979      * @return  {@code true} if the value of the argument is NaN;
 980      *          {@code false} otherwise.
 981      */
 982     public static boolean isNaN(double v) {
 983         return (v != v);
 984     }
 985 
 986     /**
 987      * Returns {@code true} if the specified number is infinitely
 988      * large in magnitude, {@code false} otherwise.
 989      *
 990      * @apiNote
 991      * This method corresponds to the isInfinite operation defined in
 992      * IEEE 754.
 993      *
 994      * @param   v   the value to be tested.
 995      * @return  {@code true} if the value of the argument is positive
 996      *          infinity or negative infinity; {@code false} otherwise.
 997      */
 998     @IntrinsicCandidate
 999     public static boolean isInfinite(double v) {
1000         return Math.abs(v) > MAX_VALUE;
1001     }
1002 
1003     /**
1004      * Returns {@code true} if the argument is a finite floating-point
1005      * value; returns {@code false} otherwise (for NaN and infinity
1006      * arguments).
1007      *
1008      * @apiNote
1009      * This method corresponds to the isFinite operation defined in
1010      * IEEE 754.
1011      *
1012      * @param d the {@code double} value to be tested
1013      * @return {@code true} if the argument is a finite
1014      * floating-point value, {@code false} otherwise.
1015      * @since 1.8
1016      */
1017     @IntrinsicCandidate
1018     public static boolean isFinite(double d) {
1019         return Math.abs(d) <= Double.MAX_VALUE;
1020     }
1021 
1022     /**
1023      * The value of the Double.
1024      *
1025      * @serial
1026      */
1027     private final double value;
1028 
1029     /**
1030      * Constructs a newly allocated {@code Double} object that
1031      * represents the primitive {@code double} argument.
1032      *
1033      * @param   value   the value to be represented by the {@code Double}.
1034      *
1035      * @deprecated
1036      * It is rarely appropriate to use this constructor. The static factory
1037      * {@link #valueOf(double)} is generally a better choice, as it is
1038      * likely to yield significantly better space and time performance.
1039      */
1040     @Deprecated(since="9")
1041     public Double(double value) {
1042         this.value = value;
1043     }
1044 
1045     /**
1046      * Constructs a newly allocated {@code Double} object that
1047      * represents the floating-point value of type {@code double}
1048      * represented by the string. The string is converted to a
1049      * {@code double} value as if by the {@code valueOf} method.
1050      *
1051      * @param  s  a string to be converted to a {@code Double}.
1052      * @throws    NumberFormatException if the string does not contain a
1053      *            parsable number.
1054      *
1055      * @deprecated
1056      * It is rarely appropriate to use this constructor.
1057      * Use {@link #parseDouble(String)} to convert a string to a
1058      * {@code double} primitive, or use {@link #valueOf(String)}
1059      * to convert a string to a {@code Double} object.
1060      */
1061     @Deprecated(since="9")
1062     public Double(String s) throws NumberFormatException {
1063         value = parseDouble(s);
1064     }
1065 
1066     /**
1067      * Returns {@code true} if this {@code Double} value is
1068      * a Not-a-Number (NaN), {@code false} otherwise.
1069      *
1070      * @return  {@code true} if the value represented by this object is
1071      *          NaN; {@code false} otherwise.
1072      */
1073     public boolean isNaN() {
1074         return isNaN(value);
1075     }
1076 
1077     /**
1078      * Returns {@code true} if this {@code Double} value is
1079      * infinitely large in magnitude, {@code false} otherwise.
1080      *
1081      * @return  {@code true} if the value represented by this object is
1082      *          positive infinity or negative infinity;
1083      *          {@code false} otherwise.
1084      */
1085     public boolean isInfinite() {
1086         return isInfinite(value);
1087     }
1088 
1089     /**
1090      * Returns a string representation of this {@code Double} object.
1091      * The primitive {@code double} value represented by this
1092      * object is converted to a string exactly as if by the method
1093      * {@code toString} of one argument.
1094      *
1095      * @return  a {@code String} representation of this object.
1096      * @see java.lang.Double#toString(double)
1097      */
1098     public String toString() {
1099         return toString(value);
1100     }
1101 
1102     /**
1103      * Returns the value of this {@code Double} as a {@code byte}
1104      * after a narrowing primitive conversion.
1105      *
1106      * @return  the {@code double} value represented by this object
1107      *          converted to type {@code byte}
1108      * @jls 5.1.3 Narrowing Primitive Conversion
1109      * @since 1.1
1110      */
1111     @Override
1112     public byte byteValue() {
1113         return (byte)value;
1114     }
1115 
1116     /**
1117      * Returns the value of this {@code Double} as a {@code short}
1118      * after a narrowing primitive conversion.
1119      *
1120      * @return  the {@code double} value represented by this object
1121      *          converted to type {@code short}
1122      * @jls 5.1.3 Narrowing Primitive Conversion
1123      * @since 1.1
1124      */
1125     @Override
1126     public short shortValue() {
1127         return (short)value;
1128     }
1129 
1130     /**
1131      * Returns the value of this {@code Double} as an {@code int}
1132      * after a narrowing primitive conversion.
1133      * @jls 5.1.3 Narrowing Primitive Conversion
1134      *
1135      * @apiNote
1136      * This method corresponds to the convertToIntegerTowardZero
1137      * operation defined in IEEE 754.
1138      *
1139      * @return  the {@code double} value represented by this object
1140      *          converted to type {@code int}
1141      */
1142     @Override
1143     public int intValue() {
1144         return (int)value;
1145     }
1146 
1147     /**
1148      * Returns the value of this {@code Double} as a {@code long}
1149      * after a narrowing primitive conversion.
1150      *
1151      * @apiNote
1152      * This method corresponds to the convertToIntegerTowardZero
1153      * operation defined in IEEE 754.
1154      *
1155      * @return  the {@code double} value represented by this object
1156      *          converted to type {@code long}
1157      * @jls 5.1.3 Narrowing Primitive Conversion
1158      */
1159     @Override
1160     public long longValue() {
1161         return (long)value;
1162     }
1163 
1164     /**
1165      * Returns the value of this {@code Double} as a {@code float}
1166      * after a narrowing primitive conversion.
1167      *
1168      * @apiNote
1169      * This method corresponds to the convertFormat operation defined
1170      * in IEEE 754.
1171      *
1172      * @return  the {@code double} value represented by this object
1173      *          converted to type {@code float}
1174      * @jls 5.1.3 Narrowing Primitive Conversion
1175      * @since 1.0
1176      */
1177     @Override
1178     public float floatValue() {
1179         return (float)value;
1180     }
1181 
1182     /**
1183      * Returns the {@code double} value of this {@code Double} object.
1184      *
1185      * @return the {@code double} value represented by this object
1186      */
1187     @Override
1188     @IntrinsicCandidate
1189     public double doubleValue() {
1190         return value;
1191     }
1192 
1193     /**
1194      * Returns a hash code for this {@code Double} object. The
1195      * result is the exclusive OR of the two halves of the
1196      * {@code long} integer bit representation, exactly as
1197      * produced by the method {@link #doubleToLongBits(double)}, of
1198      * the primitive {@code double} value represented by this
1199      * {@code Double} object. That is, the hash code is the value
1200      * of the expression:
1201      *
1202      * <blockquote>
1203      *  {@code (int)(v^(v>>>32))}
1204      * </blockquote>
1205      *
1206      * where {@code v} is defined by:
1207      *
1208      * <blockquote>
1209      *  {@code long v = Double.doubleToLongBits(this.doubleValue());}
1210      * </blockquote>
1211      *
1212      * @return  a {@code hash code} value for this object.
1213      */
1214     @Override
1215     public int hashCode() {
1216         return Double.hashCode(value);
1217     }
1218 
1219     /**
1220      * Returns a hash code for a {@code double} value; compatible with
1221      * {@code Double.hashCode()}.
1222      *
1223      * @param value the value to hash
1224      * @return a hash code value for a {@code double} value.
1225      * @since 1.8
1226      */
1227     public static int hashCode(double value) {
1228         return Long.hashCode(doubleToLongBits(value));
1229     }
1230 
1231     /**
1232      * Compares this object against the specified object.  The result
1233      * is {@code true} if and only if the argument is not
1234      * {@code null} and is a {@code Double} object that
1235      * represents a {@code double} that has the same value as the
1236      * {@code double} represented by this object. For this
1237      * purpose, two {@code double} values are considered to be
1238      * the same if and only if the method {@link
1239      * #doubleToLongBits(double)} returns the identical
1240      * {@code long} value when applied to each.
1241      * In other words, {@linkplain ##repEquivalence representation
1242      * equivalence} is used to compare the {@code double} values.
1243      *
1244      * @apiNote
1245      * This method is defined in terms of {@link
1246      * #doubleToLongBits(double)} rather than the {@code ==} operator
1247      * on {@code double} values since the {@code ==} operator does
1248      * <em>not</em> define an equivalence relation and to satisfy the
1249      * {@linkplain Object#equals equals contract} an equivalence
1250      * relation must be implemented; see {@linkplain ##equivalenceRelation
1251      * this discussion for details of floating-point equality and equivalence}.
1252      *
1253      * @see java.lang.Double#doubleToLongBits(double)
1254      * @jls 15.21.1 Numerical Equality Operators == and !=
1255      */
1256     public boolean equals(Object obj) {
1257         return (obj instanceof Double d) &&
1258             (doubleToLongBits(d.value) == doubleToLongBits(value));
1259     }
1260 
1261     /**
1262      * Returns a representation of the specified floating-point value
1263      * according to the IEEE 754 floating-point "double
1264      * format" bit layout.
1265      *
1266      * <p>Bit 63 (the bit that is selected by the mask
1267      * {@code 0x8000000000000000L}) represents the sign of the
1268      * floating-point number. Bits
1269      * 62-52 (the bits that are selected by the mask
1270      * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
1271      * (the bits that are selected by the mask
1272      * {@code 0x000fffffffffffffL}) represent the significand
1273      * (sometimes called the mantissa) of the floating-point number.
1274      *
1275      * <p>If the argument is positive infinity, the result is
1276      * {@code 0x7ff0000000000000L}.
1277      *
1278      * <p>If the argument is negative infinity, the result is
1279      * {@code 0xfff0000000000000L}.
1280      *
1281      * <p>If the argument is NaN, the result is
1282      * {@code 0x7ff8000000000000L}.
1283      *
1284      * <p>In all cases, the result is a {@code long} integer that, when
1285      * given to the {@link #longBitsToDouble(long)} method, will produce a
1286      * floating-point value the same as the argument to
1287      * {@code doubleToLongBits} (except all NaN values are
1288      * collapsed to a single "canonical" NaN value).
1289      *
1290      * @param   value   a {@code double} precision floating-point number.
1291      * @return the bits that represent the floating-point number.
1292      */
1293     @IntrinsicCandidate
1294     public static long doubleToLongBits(double value) {
1295         if (!isNaN(value)) {
1296             return doubleToRawLongBits(value);
1297         }
1298         return 0x7ff8000000000000L;
1299     }
1300 
1301     /**
1302      * Returns a representation of the specified floating-point value
1303      * according to the IEEE 754 floating-point "double
1304      * format" bit layout, preserving Not-a-Number (NaN) values.
1305      *
1306      * <p>Bit 63 (the bit that is selected by the mask
1307      * {@code 0x8000000000000000L}) represents the sign of the
1308      * floating-point number. Bits
1309      * 62-52 (the bits that are selected by the mask
1310      * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
1311      * (the bits that are selected by the mask
1312      * {@code 0x000fffffffffffffL}) represent the significand
1313      * (sometimes called the mantissa) of the floating-point number.
1314      *
1315      * <p>If the argument is positive infinity, the result is
1316      * {@code 0x7ff0000000000000L}.
1317      *
1318      * <p>If the argument is negative infinity, the result is
1319      * {@code 0xfff0000000000000L}.
1320      *
1321      * <p>If the argument is NaN, the result is the {@code long}
1322      * integer representing the actual NaN value.  Unlike the
1323      * {@code doubleToLongBits} method,
1324      * {@code doubleToRawLongBits} does not collapse all the bit
1325      * patterns encoding a NaN to a single "canonical" NaN
1326      * value.
1327      *
1328      * <p>In all cases, the result is a {@code long} integer that,
1329      * when given to the {@link #longBitsToDouble(long)} method, will
1330      * produce a floating-point value the same as the argument to
1331      * {@code doubleToRawLongBits}.
1332      *
1333      * @param   value   a {@code double} precision floating-point number.
1334      * @return the bits that represent the floating-point number.
1335      * @since 1.3
1336      */
1337     @IntrinsicCandidate
1338     public static native long doubleToRawLongBits(double value);
1339 
1340     /**
1341      * Returns the {@code double} value corresponding to a given
1342      * bit representation.
1343      * The argument is considered to be a representation of a
1344      * floating-point value according to the IEEE 754 floating-point
1345      * "double format" bit layout.
1346      *
1347      * <p>If the argument is {@code 0x7ff0000000000000L}, the result
1348      * is positive infinity.
1349      *
1350      * <p>If the argument is {@code 0xfff0000000000000L}, the result
1351      * is negative infinity.
1352      *
1353      * <p>If the argument is any value in the range
1354      * {@code 0x7ff0000000000001L} through
1355      * {@code 0x7fffffffffffffffL} or in the range
1356      * {@code 0xfff0000000000001L} through
1357      * {@code 0xffffffffffffffffL}, the result is a NaN.  No IEEE
1358      * 754 floating-point operation provided by Java can distinguish
1359      * between two NaN values of the same type with different bit
1360      * patterns.  Distinct values of NaN are only distinguishable by
1361      * use of the {@code Double.doubleToRawLongBits} method.
1362      *
1363      * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three
1364      * values that can be computed from the argument:
1365      *
1366      * {@snippet lang="java" :
1367      * int s = ((bits >> 63) == 0) ? 1 : -1;
1368      * int e = (int)((bits >> 52) & 0x7ffL);
1369      * long m = (e == 0) ?
1370      *                 (bits & 0xfffffffffffffL) << 1 :
1371      *                 (bits & 0xfffffffffffffL) | 0x10000000000000L;
1372      * }
1373      *
1374      * Then the floating-point result equals the value of the mathematical
1375      * expression <i>s</i>&middot;<i>m</i>&middot;2<sup><i>e</i>-1075</sup>.
1376      *
1377      * <p>Note that this method may not be able to return a
1378      * {@code double} NaN with exactly same bit pattern as the
1379      * {@code long} argument.  IEEE 754 distinguishes between two
1380      * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>.  The
1381      * differences between the two kinds of NaN are generally not
1382      * visible in Java.  Arithmetic operations on signaling NaNs turn
1383      * them into quiet NaNs with a different, but often similar, bit
1384      * pattern.  However, on some processors merely copying a
1385      * signaling NaN also performs that conversion.  In particular,
1386      * copying a signaling NaN to return it to the calling method
1387      * may perform this conversion.  So {@code longBitsToDouble}
1388      * may not be able to return a {@code double} with a
1389      * signaling NaN bit pattern.  Consequently, for some
1390      * {@code long} values,
1391      * {@code doubleToRawLongBits(longBitsToDouble(start))} may
1392      * <i>not</i> equal {@code start}.  Moreover, which
1393      * particular bit patterns represent signaling NaNs is platform
1394      * dependent; although all NaN bit patterns, quiet or signaling,
1395      * must be in the NaN range identified above.
1396      *
1397      * @param   bits   any {@code long} integer.
1398      * @return  the {@code double} floating-point value with the same
1399      *          bit pattern.
1400      */
1401     @IntrinsicCandidate
1402     public static native double longBitsToDouble(long bits);
1403 
1404     /**
1405      * Compares two {@code Double} objects numerically.
1406      *
1407      * This method imposes a total order on {@code Double} objects
1408      * with two differences compared to the incomplete order defined by
1409      * the Java language numerical comparison operators ({@code <, <=,
1410      * ==, >=, >}) on {@code double} values.
1411      *
1412      * <ul><li> A NaN is <em>unordered</em> with respect to other
1413      *          values and unequal to itself under the comparison
1414      *          operators.  This method chooses to define {@code
1415      *          Double.NaN} to be equal to itself and greater than all
1416      *          other {@code double} values (including {@code
1417      *          Double.POSITIVE_INFINITY}).
1418      *
1419      *      <li> Positive zero and negative zero compare equal
1420      *      numerically, but are distinct and distinguishable values.
1421      *      This method chooses to define positive zero ({@code +0.0d}),
1422      *      to be greater than negative zero ({@code -0.0d}).
1423      * </ul>
1424      *
1425      * This ensures that the <i>natural ordering</i> of {@code Double}
1426      * objects imposed by this method is <i>consistent with
1427      * equals</i>; see {@linkplain ##equivalenceRelation this
1428      * discussion for details of floating-point comparison and
1429      * ordering}.
1430      *
1431      * @apiNote
1432      * The inclusion of a total order idiom in the Java SE API
1433      * predates the inclusion of that functionality in the IEEE 754
1434      * standard. The ordering of the totalOrder predicate chosen by
1435      * IEEE 754 differs from the total order chosen by this method.
1436      * While this method treats all NaN representations as being in
1437      * the same equivalence class, the IEEE 754 total order defines an
1438      * ordering based on the bit patterns of the NaN among the
1439      * different NaN representations. The IEEE 754 order regards
1440      * "negative" NaN representations, that is NaN representations
1441      * whose sign bit is set, to be less than any finite or infinite
1442      * value and less than any "positive" NaN. In addition, the IEEE
1443      * order regards all positive NaN values as greater than positive
1444      * infinity. See the IEEE 754 standard for full details of its
1445      * total ordering.
1446      *
1447      * @param   anotherDouble   the {@code Double} to be compared.
1448      * @return  the value {@code 0} if {@code anotherDouble} is
1449      *          numerically equal to this {@code Double}; a value
1450      *          less than {@code 0} if this {@code Double}
1451      *          is numerically less than {@code anotherDouble};
1452      *          and a value greater than {@code 0} if this
1453      *          {@code Double} is numerically greater than
1454      *          {@code anotherDouble}.
1455      *
1456      * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
1457      * @since   1.2
1458      */
1459     @Override
1460     public int compareTo(Double anotherDouble) {
1461         return Double.compare(value, anotherDouble.value);
1462     }
1463 
1464     /**
1465      * Compares the two specified {@code double} values. The sign
1466      * of the integer value returned is the same as that of the
1467      * integer that would be returned by the call:
1468      * <pre>
1469      *    Double.valueOf(d1).compareTo(Double.valueOf(d2))
1470      * </pre>
1471      *
1472      * @apiNote
1473      * One idiom to implement {@linkplain ##repEquivalence
1474      * representation equivalence} on {@code double} values is
1475      * {@snippet lang="java" :
1476      * Double.compare(a, b) == 0
1477      * }
1478      * @param   d1        the first {@code double} to compare
1479      * @param   d2        the second {@code double} to compare
1480      * @return  the value {@code 0} if {@code d1} is
1481      *          numerically equal to {@code d2}; a value less than
1482      *          {@code 0} if {@code d1} is numerically less than
1483      *          {@code d2}; and a value greater than {@code 0}
1484      *          if {@code d1} is numerically greater than
1485      *          {@code d2}.
1486      * @since 1.4
1487      */
1488     public static int compare(double d1, double d2) {
1489         if (d1 < d2)
1490             return -1;           // Neither val is NaN, thisVal is smaller
1491         if (d1 > d2)
1492             return 1;            // Neither val is NaN, thisVal is larger
1493 
1494         // Cannot use doubleToRawLongBits because of possibility of NaNs.
1495         long thisBits    = Double.doubleToLongBits(d1);
1496         long anotherBits = Double.doubleToLongBits(d2);
1497 
1498         return (thisBits == anotherBits ?  0 : // Values are equal
1499                 (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1500                  1));                          // (0.0, -0.0) or (NaN, !NaN)
1501     }
1502 
1503     /**
1504      * Adds two {@code double} values together as per the + operator.
1505      *
1506      * @apiNote This method corresponds to the addition operation
1507      * defined in IEEE 754.
1508      *
1509      * @param a the first operand
1510      * @param b the second operand
1511      * @return the sum of {@code a} and {@code b}
1512      * @jls 4.2.4 Floating-Point Operations
1513      * @see java.util.function.BinaryOperator
1514      * @since 1.8
1515      */
1516     public static double sum(double a, double b) {
1517         return a + b;
1518     }
1519 
1520     /**
1521      * Returns the greater of two {@code double} values
1522      * as if by calling {@link Math#max(double, double) Math.max}.
1523      *
1524      * @apiNote
1525      * This method corresponds to the maximum operation defined in
1526      * IEEE 754.
1527      *
1528      * @param a the first operand
1529      * @param b the second operand
1530      * @return the greater of {@code a} and {@code b}
1531      * @see java.util.function.BinaryOperator
1532      * @since 1.8
1533      */
1534     public static double max(double a, double b) {
1535         return Math.max(a, b);
1536     }
1537 
1538     /**
1539      * Returns the smaller of two {@code double} values
1540      * as if by calling {@link Math#min(double, double) Math.min}.
1541      *
1542      * @apiNote
1543      * This method corresponds to the minimum operation defined in
1544      * IEEE 754.
1545      *
1546      * @param a the first operand
1547      * @param b the second operand
1548      * @return the smaller of {@code a} and {@code b}.
1549      * @see java.util.function.BinaryOperator
1550      * @since 1.8
1551      */
1552     public static double min(double a, double b) {
1553         return Math.min(a, b);
1554     }
1555 
1556     /**
1557      * Returns an {@link Optional} containing the nominal descriptor for this
1558      * instance, which is the instance itself.
1559      *
1560      * @return an {@link Optional} describing the {@linkplain Double} instance
1561      * @since 12
1562      */
1563     @Override
1564     public Optional<Double> describeConstable() {
1565         return Optional.of(this);
1566     }
1567 
1568     /**
1569      * Resolves this instance as a {@link ConstantDesc}, the result of which is
1570      * the instance itself.
1571      *
1572      * @param lookup ignored
1573      * @return the {@linkplain Double} instance
1574      * @since 12
1575      */
1576     @Override
1577     public Double resolveConstantDesc(MethodHandles.Lookup lookup) {
1578         return this;
1579     }
1580 
1581     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1582     @java.io.Serial
1583     private static final long serialVersionUID = -9172774392245257468L;
1584 }