1 /*
   2  * Copyright (c) 1994, 2018, 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.HotSpotIntrinsicCandidate;
  37 
  38 /**
  39  * The {@code Double} class wraps a value of the primitive type
  40  * {@code double} in an object. An object of type
  41  * {@code Double} contains a single field whose type is
  42  * {@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  * @author  Lee Boynton
  51  * @author  Arthur van Hoff
  52  * @author  Joseph D. Darcy
  53  * @since 1.0
  54  */
  55 public final class Double extends Number
  56         implements Comparable<Double>, Constable, ConstantDesc {
  57     /**
  58      * A constant holding the positive infinity of type
  59      * {@code double}. It is equal to the value returned by
  60      * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
  61      */
  62     public static final double POSITIVE_INFINITY = 1.0 / 0.0;
  63 
  64     /**
  65      * A constant holding the negative infinity of type
  66      * {@code double}. It is equal to the value returned by
  67      * {@code Double.longBitsToDouble(0xfff0000000000000L)}.
  68      */
  69     public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
  70 
  71     /**
  72      * A constant holding a Not-a-Number (NaN) value of type
  73      * {@code double}. It is equivalent to the value returned by
  74      * {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
  75      */
  76     public static final double NaN = 0.0d / 0.0;
  77 
  78     /**
  79      * A constant holding the largest positive finite value of type
  80      * {@code double},
  81      * (2-2<sup>-52</sup>)&middot;2<sup>1023</sup>.  It is equal to
  82      * the hexadecimal floating-point literal
  83      * {@code 0x1.fffffffffffffP+1023} and also equal to
  84      * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
  85      */
  86     public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308
  87 
  88     /**
  89      * A constant holding the smallest positive normal value of type
  90      * {@code double}, 2<sup>-1022</sup>.  It is equal to the
  91      * hexadecimal floating-point literal {@code 0x1.0p-1022} and also
  92      * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}.
  93      *
  94      * @since 1.6
  95      */
  96     public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308
  97 
  98     /**
  99      * A constant holding the smallest positive nonzero value of type
 100      * {@code double}, 2<sup>-1074</sup>. It is equal to the
 101      * hexadecimal floating-point literal
 102      * {@code 0x0.0000000000001P-1022} and also equal to
 103      * {@code Double.longBitsToDouble(0x1L)}.
 104      */
 105     public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324
 106 
 107     /**
 108      * Maximum exponent a finite {@code double} variable may have.
 109      * It is equal to the value returned by
 110      * {@code Math.getExponent(Double.MAX_VALUE)}.
 111      *
 112      * @since 1.6
 113      */
 114     public static final int MAX_EXPONENT = 1023;
 115 
 116     /**
 117      * Minimum exponent a normalized {@code double} variable may
 118      * have.  It is equal to the value returned by
 119      * {@code Math.getExponent(Double.MIN_NORMAL)}.
 120      *
 121      * @since 1.6
 122      */
 123     public static final int MIN_EXPONENT = -1022;
 124 
 125     /**
 126      * The number of bits used to represent a {@code double} value.
 127      *
 128      * @since 1.5
 129      */
 130     public static final int SIZE = 64;
 131 
 132     /**
 133      * The number of bytes used to represent a {@code double} value.
 134      *
 135      * @since 1.8
 136      */
 137     public static final int BYTES = SIZE / Byte.SIZE;
 138 
 139     /**
 140      * The {@code Class} instance representing the primitive type
 141      * {@code double}.
 142      *
 143      * @since 1.1
 144      */
 145     @SuppressWarnings("unchecked")
 146     public static final Class<Double>   TYPE = (Class<Double>) Class.getPrimitiveClass("double");
 147 
 148     /**
 149      * Returns a string rendering of the {@code double} argument.
 150      *
 151      * <p>The characters of the result are all drawn from the ASCII set.
 152      * <ul>
 153      * <li> Any NaN, whether quiet or signaling, is rendered as
 154      * {@code "NaN"}, regardless of the sign bit.
 155      * <li> The infinities +&infin; and -&infin; are rendered as
 156      * {@code "Infinity"} and {@code "-Infinity"}, respectively.
 157      * <li> The positive and negative zeroes are rendered as
 158      * {@code "0.0"} and {@code "-0.0"}, respectively.
 159      * <li> A finite negative {@code v} is rendered as the sign
 160      * '{@code -}' followed by the rendering of the magnitude -{@code v}.
 161      * <li> A finite positive {@code v} is rendered in two stages:
 162      * <ul>
 163      * <li> <em>Selection of a decimal</em>: A well-defined
 164      * decimal <i>d</i><sub><code>v</code></sub> is selected
 165      * to represent {@code v}.
 166      * <li> <em>Formatting as a string</em>: The decimal
 167      * <i>d</i><sub><code>v</code></sub> is formatted as a string,
 168      * either in plain or in computerized scientific notation,
 169      * depending on its value.
 170      * </ul>
 171      * </ul>
 172      *
 173      * <p>A <em>decimal</em> is a number of the form
 174      * <i>d</i>&times;10<sup><i>i</i></sup>
 175      * for some (unique) integers <i>d</i> &gt; 0 and <i>i</i> such that
 176      * <i>d</i> is not a multiple of 10.
 177      * These integers are the <em>significand</em> and
 178      * the <em>exponent</em>, respectively, of the decimal.
 179      * The <em>length</em> of the decimal is the (unique)
 180      * integer <i>n</i> meeting
 181      * 10<sup><i>n</i>-1</sup> &le; <i>d</i> &lt; 10<sup><i>n</i></sup>.
 182      *
 183      * <p>The decimal <i>d</i><sub><code>v</code></sub>
 184      * for a finite positive {@code v} is defined as follows:
 185      * <ul>
 186      * <li>Let <i>R</i> be the set of all decimals that round to {@code v}
 187      * according to the usual round-to-closest rule of
 188      * IEEE 754 floating-point arithmetic.
 189      * <li>Let <i>m</i> be the minimal length over all decimals in <i>R</i>.
 190      * <li>When <i>m</i> &ge; 2, let <i>T</i> be the set of all decimals
 191      * in <i>R</i> with length <i>m</i>.
 192      * Otherwise, let <i>T</i> be the set of all decimals
 193      * in <i>R</i> with length 1 or 2.
 194      * <li>Define <i>d</i><sub><code>v</code></sub> as
 195      * the decimal in <i>T</i> that is closest to {@code v}.
 196      * Or if there are two such decimals in <i>T</i>,
 197      * select the one with the even significand (there is exactly one).
 198      * </ul>
 199      *
 200      * <p>The (uniquely) selected decimal <i>d</i><sub><code>v</code></sub>
 201      * is then formatted.
 202      *
 203      * <p>Let <i>d</i>, <i>i</i> and <i>n</i> be the significand, exponent and
 204      * length of <i>d</i><sub><code>v</code></sub>, respectively.
 205      * Further, let <i>e</i> = <i>n</i> + <i>i</i> - 1 and let
 206      * <i>d</i><sub>1</sub>&hellip;<i>d</i><sub><i>n</i></sub>
 207      * be the usual decimal expansion of the significand.
 208      * Note that <i>d</i><sub>1</sub> &ne; 0 &ne; <i>d</i><sub><i>n</i></sub>.
 209      * <ul>
 210      * <li>Case -3 &le; <i>e</i> &lt; 0:
 211      * <i>d</i><sub><code>v</code></sub> is formatted as
 212      * <code>0.0</code>&hellip;<code>0</code><!--
 213      * --><i>d</i><sub>1</sub>&hellip;<i>d</i><sub><i>n</i></sub>,
 214      * where there are exactly -(<i>n</i> + <i>i</i>) zeroes between
 215      * the decimal point and <i>d</i><sub>1</sub>.
 216      * For example, 123 &times; 10<sup>-4</sup> is formatted as
 217      * {@code 0.0123}.
 218      * <li>Case 0 &le; <i>e</i> &lt; 7:
 219      * <ul>
 220      * <li>Subcase <i>i</i> &ge; 0:
 221      * <i>d</i><sub><code>v</code></sub> is formatted as
 222      * <i>d</i><sub>1</sub>&hellip;<i>d</i><sub><i>n</i></sub><!--
 223      * --><code>0</code>&hellip;<code>0.0</code>,
 224      * where there are exactly <i>i</i> zeroes
 225      * between <i>d</i><sub><i>n</i></sub> and the decimal point.
 226      * For example, 123 &times; 10<sup>2</sup> is formatted as
 227      * {@code 12300.0}.
 228      * <li>Subcase <i>i</i> &lt; 0:
 229      * <i>d</i><sub><code>v</code></sub> is formatted as
 230      * <i>d</i><sub>1</sub>&hellip;<!--
 231      * --><i>d</i><sub><i>n</i>+<i>i</i></sub>.<!--
 232      * --><i>d</i><sub><i>n</i>+<i>i</i>+1</sub>&hellip;<!--
 233      * --><i>d</i><sub><i>n</i></sub>.
 234      * There are exactly -<i>i</i> digits to the right of
 235      * the decimal point.
 236      * For example, 123 &times; 10<sup>-1</sup> is formatted as
 237      * {@code 12.3}.
 238      * </ul>
 239      * <li>Case <i>e</i> &lt; -3 or <i>e</i> &ge; 7:
 240      * computerized scientific notation is used to format
 241      * <i>d</i><sub><code>v</code></sub>.
 242      * Here <i>e</i> is formatted as by {@link Integer#toString(int)}.
 243      * <ul>
 244      * <li>Subcase <i>n</i> = 1:
 245      * <i>d</i><sub><code>v</code></sub> is formatted as
 246      * <i>d</i><sub>1</sub><code>.0E</code><i>e</i>.
 247      * For example, 1 &times; 10<sup>23</sup> is formatted as
 248      * {@code 1.0E23}.
 249      * <li>Subcase <i>n</i> &gt; 1:
 250      * <i>d</i><sub><code>v</code></sub> is formatted as
 251      * <i>d</i><sub>1</sub><code>.</code><i>d</i><sub>2</sub><!--
 252      * -->&hellip;<i>d</i><sub><i>n</i></sub><code>E</code><i>e</i>.
 253      * For example, 123 &times; 10<sup>-21</sup> is formatted as
 254      * {@code 1.23E-19}.
 255      * </ul>
 256      * </ul>
 257      *
 258      * @param v the {@code double} to be rendered.
 259      * @return a string rendering of the argument.
 260      */
 261     public static String toString(double v) {
 262         return DoubleToDecimal.toString(v);
 263     }
 264 
 265     /**
 266      * Returns a hexadecimal string representation of the
 267      * {@code double} argument. All characters mentioned below
 268      * are ASCII characters.
 269      *
 270      * <ul>
 271      * <li>If the argument is NaN, the result is the string
 272      *     "{@code NaN}".
 273      * <li>Otherwise, the result is a string that represents the sign
 274      * and magnitude of the argument. If the sign is negative, the
 275      * first character of the result is '{@code -}'
 276      * ({@code '\u005Cu002D'}); if the sign is positive, no sign
 277      * character appears in the result. As for the magnitude <i>m</i>:
 278      *
 279      * <ul>
 280      * <li>If <i>m</i> is infinity, it is represented by the string
 281      * {@code "Infinity"}; thus, positive infinity produces the
 282      * result {@code "Infinity"} and negative infinity produces
 283      * the result {@code "-Infinity"}.
 284      *
 285      * <li>If <i>m</i> is zero, it is represented by the string
 286      * {@code "0x0.0p0"}; thus, negative zero produces the result
 287      * {@code "-0x0.0p0"} and positive zero produces the result
 288      * {@code "0x0.0p0"}.
 289      *
 290      * <li>If <i>m</i> is a {@code double} value with a
 291      * normalized representation, substrings are used to represent the
 292      * significand and exponent fields.  The significand is
 293      * represented by the characters {@code "0x1."}
 294      * followed by a lowercase hexadecimal representation of the rest
 295      * of the significand as a fraction.  Trailing zeros in the
 296      * hexadecimal representation are removed unless all the digits
 297      * are zero, in which case a single zero is used. Next, the
 298      * exponent is represented by {@code "p"} followed
 299      * by a decimal string of the unbiased exponent as if produced by
 300      * a call to {@link Integer#toString(int) Integer.toString} on the
 301      * exponent value.
 302      *
 303      * <li>If <i>m</i> is a {@code double} value with a subnormal
 304      * representation, the significand is represented by the
 305      * characters {@code "0x0."} followed by a
 306      * hexadecimal representation of the rest of the significand as a
 307      * fraction.  Trailing zeros in the hexadecimal representation are
 308      * removed. Next, the exponent is represented by
 309      * {@code "p-1022"}.  Note that there must be at
 310      * least one nonzero digit in a subnormal significand.
 311      *
 312      * </ul>
 313      *
 314      * </ul>
 315      *
 316      * <table class="striped">
 317      * <caption>Examples</caption>
 318      * <thead>
 319      * <tr><th scope="col">Floating-point Value</th><th scope="col">Hexadecimal String</th>
 320      * </thead>
 321      * <tbody style="text-align:right">
 322      * <tr><th scope="row">{@code 1.0}</th> <td>{@code 0x1.0p0}</td>
 323      * <tr><th scope="row">{@code -1.0}</th>        <td>{@code -0x1.0p0}</td>
 324      * <tr><th scope="row">{@code 2.0}</th> <td>{@code 0x1.0p1}</td>
 325      * <tr><th scope="row">{@code 3.0}</th> <td>{@code 0x1.8p1}</td>
 326      * <tr><th scope="row">{@code 0.5}</th> <td>{@code 0x1.0p-1}</td>
 327      * <tr><th scope="row">{@code 0.25}</th>        <td>{@code 0x1.0p-2}</td>
 328      * <tr><th scope="row">{@code Double.MAX_VALUE}</th>
 329      *     <td>{@code 0x1.fffffffffffffp1023}</td>
 330      * <tr><th scope="row">{@code Minimum Normal Value}</th>
 331      *     <td>{@code 0x1.0p-1022}</td>
 332      * <tr><th scope="row">{@code Maximum Subnormal Value}</th>
 333      *     <td>{@code 0x0.fffffffffffffp-1022}</td>
 334      * <tr><th scope="row">{@code Double.MIN_VALUE}</th>
 335      *     <td>{@code 0x0.0000000000001p-1022}</td>
 336      * </tbody>
 337      * </table>
 338      * @param   d   the {@code double} to be converted.
 339      * @return a hex string representation of the argument.
 340      * @since 1.5
 341      * @author Joseph D. Darcy
 342      */
 343     public static String toHexString(double d) {
 344         /*
 345          * Modeled after the "a" conversion specifier in C99, section
 346          * 7.19.6.1; however, the output of this method is more
 347          * tightly specified.
 348          */
 349         if (!isFinite(d) )
 350             // For infinity and NaN, use the decimal output.
 351             return Double.toString(d);
 352         else {
 353             // Initialized to maximum size of output.
 354             StringBuilder answer = new StringBuilder(24);
 355 
 356             if (Math.copySign(1.0, d) == -1.0)    // value is negative,
 357                 answer.append("-");                  // so append sign info
 358 
 359             answer.append("0x");
 360 
 361             d = Math.abs(d);
 362 
 363             if(d == 0.0) {
 364                 answer.append("0.0p0");
 365             } else {
 366                 boolean subnormal = (d < Double.MIN_NORMAL);
 367 
 368                 // Isolate significand bits and OR in a high-order bit
 369                 // so that the string representation has a known
 370                 // length.
 371                 long signifBits = (Double.doubleToLongBits(d)
 372                                    & DoubleConsts.SIGNIF_BIT_MASK) |
 373                     0x1000000000000000L;
 374 
 375                 // Subnormal values have a 0 implicit bit; normal
 376                 // values have a 1 implicit bit.
 377                 answer.append(subnormal ? "0." : "1.");
 378 
 379                 // Isolate the low-order 13 digits of the hex
 380                 // representation.  If all the digits are zero,
 381                 // replace with a single 0; otherwise, remove all
 382                 // trailing zeros.
 383                 String signif = Long.toHexString(signifBits).substring(3,16);
 384                 answer.append(signif.equals("0000000000000") ? // 13 zeros
 385                               "0":
 386                               signif.replaceFirst("0{1,12}$", ""));
 387 
 388                 answer.append('p');
 389                 // If the value is subnormal, use the E_min exponent
 390                 // value for double; otherwise, extract and report d's
 391                 // exponent (the representation of a subnormal uses
 392                 // E_min -1).
 393                 answer.append(subnormal ?
 394                               Double.MIN_EXPONENT:
 395                               Math.getExponent(d));
 396             }
 397             return answer.toString();
 398         }
 399     }
 400 
 401     /**
 402      * Returns a {@code Double} object holding the
 403      * {@code double} value represented by the argument string
 404      * {@code s}.
 405      *
 406      * <p>If {@code s} is {@code null}, then a
 407      * {@code NullPointerException} is thrown.
 408      *
 409      * <p>Leading and trailing whitespace characters in {@code s}
 410      * are ignored.  Whitespace is removed as if by the {@link
 411      * String#trim} method; that is, both ASCII space and control
 412      * characters are removed. The rest of {@code s} should
 413      * constitute a <i>FloatValue</i> as described by the lexical
 414      * syntax rules:
 415      *
 416      * <blockquote>
 417      * <dl>
 418      * <dt><i>FloatValue:</i>
 419      * <dd><i>Sign<sub>opt</sub></i> {@code NaN}
 420      * <dd><i>Sign<sub>opt</sub></i> {@code Infinity}
 421      * <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i>
 422      * <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i>
 423      * <dd><i>SignedInteger</i>
 424      * </dl>
 425      *
 426      * <dl>
 427      * <dt><i>HexFloatingPointLiteral</i>:
 428      * <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i>
 429      * </dl>
 430      *
 431      * <dl>
 432      * <dt><i>HexSignificand:</i>
 433      * <dd><i>HexNumeral</i>
 434      * <dd><i>HexNumeral</i> {@code .}
 435      * <dd>{@code 0x} <i>HexDigits<sub>opt</sub>
 436      *     </i>{@code .}<i> HexDigits</i>
 437      * <dd>{@code 0X}<i> HexDigits<sub>opt</sub>
 438      *     </i>{@code .} <i>HexDigits</i>
 439      * </dl>
 440      *
 441      * <dl>
 442      * <dt><i>BinaryExponent:</i>
 443      * <dd><i>BinaryExponentIndicator SignedInteger</i>
 444      * </dl>
 445      *
 446      * <dl>
 447      * <dt><i>BinaryExponentIndicator:</i>
 448      * <dd>{@code p}
 449      * <dd>{@code P}
 450      * </dl>
 451      *
 452      * </blockquote>
 453      *
 454      * where <i>Sign</i>, <i>FloatingPointLiteral</i>,
 455      * <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and
 456      * <i>FloatTypeSuffix</i> are as defined in the lexical structure
 457      * sections of
 458      * <cite>The Java&trade; Language Specification</cite>,
 459      * except that underscores are not accepted between digits.
 460      * If {@code s} does not have the form of
 461      * a <i>FloatValue</i>, then a {@code NumberFormatException}
 462      * is thrown. Otherwise, {@code s} is regarded as
 463      * representing an exact decimal value in the usual
 464      * "computerized scientific notation" or as an exact
 465      * hexadecimal value; this exact numerical value is then
 466      * conceptually converted to an "infinitely precise"
 467      * binary value that is then rounded to type {@code double}
 468      * by the usual round-to-nearest rule of IEEE 754 floating-point
 469      * arithmetic, which includes preserving the sign of a zero
 470      * value.
 471      *
 472      * Note that the round-to-nearest rule also implies overflow and
 473      * underflow behaviour; if the exact value of {@code s} is large
 474      * enough in magnitude (greater than or equal to ({@link
 475      * #MAX_VALUE} + {@link Math#ulp(double) ulp(MAX_VALUE)}/2),
 476      * rounding to {@code double} will result in an infinity and if the
 477      * exact value of {@code s} is small enough in magnitude (less
 478      * than or equal to {@link #MIN_VALUE}/2), rounding to float will
 479      * result in a zero.
 480      *
 481      * Finally, after rounding a {@code Double} object representing
 482      * this {@code double} value is returned.
 483      *
 484      * <p> To interpret localized string representations of a
 485      * floating-point value, use subclasses of {@link
 486      * java.text.NumberFormat}.
 487      *
 488      * <p>Note that trailing format specifiers, specifiers that
 489      * determine the type of a floating-point literal
 490      * ({@code 1.0f} is a {@code float} value;
 491      * {@code 1.0d} is a {@code double} value), do
 492      * <em>not</em> influence the results of this method.  In other
 493      * words, the numerical value of the input string is converted
 494      * directly to the target floating-point type.  The two-step
 495      * sequence of conversions, string to {@code float} followed
 496      * by {@code float} to {@code double}, is <em>not</em>
 497      * equivalent to converting a string directly to
 498      * {@code double}. For example, the {@code float}
 499      * literal {@code 0.1f} is equal to the {@code double}
 500      * value {@code 0.10000000149011612}; the {@code float}
 501      * literal {@code 0.1f} represents a different numerical
 502      * value than the {@code double} literal
 503      * {@code 0.1}. (The numerical value 0.1 cannot be exactly
 504      * represented in a binary floating-point number.)
 505      *
 506      * <p>To avoid calling this method on an invalid string and having
 507      * a {@code NumberFormatException} be thrown, the regular
 508      * expression below can be used to screen the input string:
 509      *
 510      * <pre>{@code
 511      *  final String Digits     = "(\\p{Digit}+)";
 512      *  final String HexDigits  = "(\\p{XDigit}+)";
 513      *  // an exponent is 'e' or 'E' followed by an optionally
 514      *  // signed decimal integer.
 515      *  final String Exp        = "[eE][+-]?"+Digits;
 516      *  final String fpRegex    =
 517      *      ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
 518      *       "[+-]?(" + // Optional sign character
 519      *       "NaN|" +           // "NaN" string
 520      *       "Infinity|" +      // "Infinity" string
 521      *
 522      *       // A decimal floating-point string representing a finite positive
 523      *       // number without a leading sign has at most five basic pieces:
 524      *       // Digits . Digits ExponentPart FloatTypeSuffix
 525      *       //
 526      *       // Since this method allows integer-only strings as input
 527      *       // in addition to strings of floating-point literals, the
 528      *       // two sub-patterns below are simplifications of the grammar
 529      *       // productions from section 3.10.2 of
 530      *       // The Java Language Specification.
 531      *
 532      *       // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
 533      *       "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
 534      *
 535      *       // . Digits ExponentPart_opt FloatTypeSuffix_opt
 536      *       "(\\.("+Digits+")("+Exp+")?)|"+
 537      *
 538      *       // Hexadecimal strings
 539      *       "((" +
 540      *        // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
 541      *        "(0[xX]" + HexDigits + "(\\.)?)|" +
 542      *
 543      *        // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
 544      *        "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
 545      *
 546      *        ")[pP][+-]?" + Digits + "))" +
 547      *       "[fFdD]?))" +
 548      *       "[\\x00-\\x20]*");// Optional trailing "whitespace"
 549      *
 550      *  if (Pattern.matches(fpRegex, myString))
 551      *      Double.valueOf(myString); // Will not throw NumberFormatException
 552      *  else {
 553      *      // Perform suitable alternative action
 554      *  }
 555      * }</pre>
 556      *
 557      * @param      s   the string to be parsed.
 558      * @return     a {@code Double} object holding the value
 559      *             represented by the {@code String} argument.
 560      * @throws     NumberFormatException  if the string does not contain a
 561      *             parsable number.
 562      */
 563     public static Double valueOf(String s) throws NumberFormatException {
 564         return new Double(parseDouble(s));
 565     }
 566 
 567     /**
 568      * Returns a {@code Double} instance representing the specified
 569      * {@code double} value.
 570      * If a new {@code Double} instance is not required, this method
 571      * should generally be used in preference to the constructor
 572      * {@link #Double(double)}, as this method is likely to yield
 573      * significantly better space and time performance by caching
 574      * frequently requested values.
 575      *
 576      * @param  d a double value.
 577      * @return a {@code Double} instance representing {@code d}.
 578      * @since  1.5
 579      */
 580     @HotSpotIntrinsicCandidate
 581     public static Double valueOf(double d) {
 582         return new Double(d);
 583     }
 584 
 585     /**
 586      * Returns a new {@code double} initialized to the value
 587      * represented by the specified {@code String}, as performed
 588      * by the {@code valueOf} method of class
 589      * {@code Double}.
 590      *
 591      * @param  s   the string to be parsed.
 592      * @return the {@code double} value represented by the string
 593      *         argument.
 594      * @throws NullPointerException  if the string is null
 595      * @throws NumberFormatException if the string does not contain
 596      *         a parsable {@code double}.
 597      * @see    java.lang.Double#valueOf(String)
 598      * @since 1.2
 599      */
 600     public static double parseDouble(String s) throws NumberFormatException {
 601         return FloatingDecimal.parseDouble(s);
 602     }
 603 
 604     /**
 605      * Returns {@code true} if the specified number is a
 606      * Not-a-Number (NaN) value, {@code false} otherwise.
 607      *
 608      * @param   v   the value to be tested.
 609      * @return  {@code true} if the value of the argument is NaN;
 610      *          {@code false} otherwise.
 611      */
 612     public static boolean isNaN(double v) {
 613         return (v != v);
 614     }
 615 
 616     /**
 617      * Returns {@code true} if the specified number is infinitely
 618      * large in magnitude, {@code false} otherwise.
 619      *
 620      * @param   v   the value to be tested.
 621      * @return  {@code true} if the value of the argument is positive
 622      *          infinity or negative infinity; {@code false} otherwise.
 623      */
 624     public static boolean isInfinite(double v) {
 625         return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY);
 626     }
 627 
 628     /**
 629      * Returns {@code true} if the argument is a finite floating-point
 630      * value; returns {@code false} otherwise (for NaN and infinity
 631      * arguments).
 632      *
 633      * @param d the {@code double} value to be tested
 634      * @return {@code true} if the argument is a finite
 635      * floating-point value, {@code false} otherwise.
 636      * @since 1.8
 637      */
 638     public static boolean isFinite(double d) {
 639         return Math.abs(d) <= Double.MAX_VALUE;
 640     }
 641 
 642     /**
 643      * The value of the Double.
 644      *
 645      * @serial
 646      */
 647     private final double value;
 648 
 649     /**
 650      * Constructs a newly allocated {@code Double} object that
 651      * represents the primitive {@code double} argument.
 652      *
 653      * @param   value   the value to be represented by the {@code Double}.
 654      *
 655      * @deprecated
 656      * It is rarely appropriate to use this constructor. The static factory
 657      * {@link #valueOf(double)} is generally a better choice, as it is
 658      * likely to yield significantly better space and time performance.
 659      */
 660     @Deprecated(since="9")
 661     public Double(double value) {
 662         this.value = value;
 663     }
 664 
 665     /**
 666      * Constructs a newly allocated {@code Double} object that
 667      * represents the floating-point value of type {@code double}
 668      * represented by the string. The string is converted to a
 669      * {@code double} value as if by the {@code valueOf} method.
 670      *
 671      * @param  s  a string to be converted to a {@code Double}.
 672      * @throws    NumberFormatException if the string does not contain a
 673      *            parsable number.
 674      *
 675      * @deprecated
 676      * It is rarely appropriate to use this constructor.
 677      * Use {@link #parseDouble(String)} to convert a string to a
 678      * {@code double} primitive, or use {@link #valueOf(String)}
 679      * to convert a string to a {@code Double} object.
 680      */
 681     @Deprecated(since="9")
 682     public Double(String s) throws NumberFormatException {
 683         value = parseDouble(s);
 684     }
 685 
 686     /**
 687      * Returns {@code true} if this {@code Double} value is
 688      * a Not-a-Number (NaN), {@code false} otherwise.
 689      *
 690      * @return  {@code true} if the value represented by this object is
 691      *          NaN; {@code false} otherwise.
 692      */
 693     public boolean isNaN() {
 694         return isNaN(value);
 695     }
 696 
 697     /**
 698      * Returns {@code true} if this {@code Double} value is
 699      * infinitely large in magnitude, {@code false} otherwise.
 700      *
 701      * @return  {@code true} if the value represented by this object is
 702      *          positive infinity or negative infinity;
 703      *          {@code false} otherwise.
 704      */
 705     public boolean isInfinite() {
 706         return isInfinite(value);
 707     }
 708 
 709     /**
 710      * Returns a string representation of this {@code Double} object.
 711      * The primitive {@code double} value represented by this
 712      * object is converted to a string exactly as if by the method
 713      * {@code toString} of one argument.
 714      *
 715      * @return  a {@code String} representation of this object.
 716      * @see java.lang.Double#toString(double)
 717      */
 718     public String toString() {
 719         return toString(value);
 720     }
 721 
 722     /**
 723      * Returns the value of this {@code Double} as a {@code byte}
 724      * after a narrowing primitive conversion.
 725      *
 726      * @return  the {@code double} value represented by this object
 727      *          converted to type {@code byte}
 728      * @jls 5.1.3 Narrowing Primitive Conversions
 729      * @since 1.1
 730      */
 731     public byte byteValue() {
 732         return (byte)value;
 733     }
 734 
 735     /**
 736      * Returns the value of this {@code Double} as a {@code short}
 737      * after a narrowing primitive conversion.
 738      *
 739      * @return  the {@code double} value represented by this object
 740      *          converted to type {@code short}
 741      * @jls 5.1.3 Narrowing Primitive Conversions
 742      * @since 1.1
 743      */
 744     public short shortValue() {
 745         return (short)value;
 746     }
 747 
 748     /**
 749      * Returns the value of this {@code Double} as an {@code int}
 750      * after a narrowing primitive conversion.
 751      * @jls 5.1.3 Narrowing Primitive Conversions
 752      *
 753      * @return  the {@code double} value represented by this object
 754      *          converted to type {@code int}
 755      */
 756     public int intValue() {
 757         return (int)value;
 758     }
 759 
 760     /**
 761      * Returns the value of this {@code Double} as a {@code long}
 762      * after a narrowing primitive conversion.
 763      *
 764      * @return  the {@code double} value represented by this object
 765      *          converted to type {@code long}
 766      * @jls 5.1.3 Narrowing Primitive Conversions
 767      */
 768     public long longValue() {
 769         return (long)value;
 770     }
 771 
 772     /**
 773      * Returns the value of this {@code Double} as a {@code float}
 774      * after a narrowing primitive conversion.
 775      *
 776      * @return  the {@code double} value represented by this object
 777      *          converted to type {@code float}
 778      * @jls 5.1.3 Narrowing Primitive Conversions
 779      * @since 1.0
 780      */
 781     public float floatValue() {
 782         return (float)value;
 783     }
 784 
 785     /**
 786      * Returns the {@code double} value of this {@code Double} object.
 787      *
 788      * @return the {@code double} value represented by this object
 789      */
 790     @HotSpotIntrinsicCandidate
 791     public double doubleValue() {
 792         return value;
 793     }
 794 
 795     /**
 796      * Returns a hash code for this {@code Double} object. The
 797      * result is the exclusive OR of the two halves of the
 798      * {@code long} integer bit representation, exactly as
 799      * produced by the method {@link #doubleToLongBits(double)}, of
 800      * the primitive {@code double} value represented by this
 801      * {@code Double} object. That is, the hash code is the value
 802      * of the expression:
 803      *
 804      * <blockquote>
 805      *  {@code (int)(v^(v>>>32))}
 806      * </blockquote>
 807      *
 808      * where {@code v} is defined by:
 809      *
 810      * <blockquote>
 811      *  {@code long v = Double.doubleToLongBits(this.doubleValue());}
 812      * </blockquote>
 813      *
 814      * @return  a {@code hash code} value for this object.
 815      */
 816     @Override
 817     public int hashCode() {
 818         return Double.hashCode(value);
 819     }
 820 
 821     /**
 822      * Returns a hash code for a {@code double} value; compatible with
 823      * {@code Double.hashCode()}.
 824      *
 825      * @param value the value to hash
 826      * @return a hash code value for a {@code double} value.
 827      * @since 1.8
 828      */
 829     public static int hashCode(double value) {
 830         long bits = doubleToLongBits(value);
 831         return (int)(bits ^ (bits >>> 32));
 832     }
 833 
 834     /**
 835      * Compares this object against the specified object.  The result
 836      * is {@code true} if and only if the argument is not
 837      * {@code null} and is a {@code Double} object that
 838      * represents a {@code double} that has the same value as the
 839      * {@code double} represented by this object. For this
 840      * purpose, two {@code double} values are considered to be
 841      * the same if and only if the method {@link
 842      * #doubleToLongBits(double)} returns the identical
 843      * {@code long} value when applied to each.
 844      *
 845      * <p>Note that in most cases, for two instances of class
 846      * {@code Double}, {@code d1} and {@code d2}, the
 847      * value of {@code d1.equals(d2)} is {@code true} if and
 848      * only if
 849      *
 850      * <blockquote>
 851      *  {@code d1.doubleValue() == d2.doubleValue()}
 852      * </blockquote>
 853      *
 854      * <p>also has the value {@code true}. However, there are two
 855      * exceptions:
 856      * <ul>
 857      * <li>If {@code d1} and {@code d2} both represent
 858      *     {@code Double.NaN}, then the {@code equals} method
 859      *     returns {@code true}, even though
 860      *     {@code Double.NaN==Double.NaN} has the value
 861      *     {@code false}.
 862      * <li>If {@code d1} represents {@code +0.0} while
 863      *     {@code d2} represents {@code -0.0}, or vice versa,
 864      *     the {@code equal} test has the value {@code false},
 865      *     even though {@code +0.0==-0.0} has the value {@code true}.
 866      * </ul>
 867      * This definition allows hash tables to operate properly.
 868      * @param   obj   the object to compare with.
 869      * @return  {@code true} if the objects are the same;
 870      *          {@code false} otherwise.
 871      * @see java.lang.Double#doubleToLongBits(double)
 872      */
 873     public boolean equals(Object obj) {
 874         return (obj instanceof Double)
 875                && (doubleToLongBits(((Double)obj).value) ==
 876                       doubleToLongBits(value));
 877     }
 878 
 879     /**
 880      * Returns a representation of the specified floating-point value
 881      * according to the IEEE 754 floating-point "double
 882      * format" bit layout.
 883      *
 884      * <p>Bit 63 (the bit that is selected by the mask
 885      * {@code 0x8000000000000000L}) represents the sign of the
 886      * floating-point number. Bits
 887      * 62-52 (the bits that are selected by the mask
 888      * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
 889      * (the bits that are selected by the mask
 890      * {@code 0x000fffffffffffffL}) represent the significand
 891      * (sometimes called the mantissa) of the floating-point number.
 892      *
 893      * <p>If the argument is positive infinity, the result is
 894      * {@code 0x7ff0000000000000L}.
 895      *
 896      * <p>If the argument is negative infinity, the result is
 897      * {@code 0xfff0000000000000L}.
 898      *
 899      * <p>If the argument is NaN, the result is
 900      * {@code 0x7ff8000000000000L}.
 901      *
 902      * <p>In all cases, the result is a {@code long} integer that, when
 903      * given to the {@link #longBitsToDouble(long)} method, will produce a
 904      * floating-point value the same as the argument to
 905      * {@code doubleToLongBits} (except all NaN values are
 906      * collapsed to a single "canonical" NaN value).
 907      *
 908      * @param   value   a {@code double} precision floating-point number.
 909      * @return the bits that represent the floating-point number.
 910      */
 911     @HotSpotIntrinsicCandidate
 912     public static long doubleToLongBits(double value) {
 913         if (!isNaN(value)) {
 914             return doubleToRawLongBits(value);
 915         }
 916         return 0x7ff8000000000000L;
 917     }
 918 
 919     /**
 920      * Returns a representation of the specified floating-point value
 921      * according to the IEEE 754 floating-point "double
 922      * format" bit layout, preserving Not-a-Number (NaN) values.
 923      *
 924      * <p>Bit 63 (the bit that is selected by the mask
 925      * {@code 0x8000000000000000L}) represents the sign of the
 926      * floating-point number. Bits
 927      * 62-52 (the bits that are selected by the mask
 928      * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
 929      * (the bits that are selected by the mask
 930      * {@code 0x000fffffffffffffL}) represent the significand
 931      * (sometimes called the mantissa) of the floating-point number.
 932      *
 933      * <p>If the argument is positive infinity, the result is
 934      * {@code 0x7ff0000000000000L}.
 935      *
 936      * <p>If the argument is negative infinity, the result is
 937      * {@code 0xfff0000000000000L}.
 938      *
 939      * <p>If the argument is NaN, the result is the {@code long}
 940      * integer representing the actual NaN value.  Unlike the
 941      * {@code doubleToLongBits} method,
 942      * {@code doubleToRawLongBits} does not collapse all the bit
 943      * patterns encoding a NaN to a single "canonical" NaN
 944      * value.
 945      *
 946      * <p>In all cases, the result is a {@code long} integer that,
 947      * when given to the {@link #longBitsToDouble(long)} method, will
 948      * produce a floating-point value the same as the argument to
 949      * {@code doubleToRawLongBits}.
 950      *
 951      * @param   value   a {@code double} precision floating-point number.
 952      * @return the bits that represent the floating-point number.
 953      * @since 1.3
 954      */
 955     @HotSpotIntrinsicCandidate
 956     public static native long doubleToRawLongBits(double value);
 957 
 958     /**
 959      * Returns the {@code double} value corresponding to a given
 960      * bit representation.
 961      * The argument is considered to be a representation of a
 962      * floating-point value according to the IEEE 754 floating-point
 963      * "double format" bit layout.
 964      *
 965      * <p>If the argument is {@code 0x7ff0000000000000L}, the result
 966      * is positive infinity.
 967      *
 968      * <p>If the argument is {@code 0xfff0000000000000L}, the result
 969      * is negative infinity.
 970      *
 971      * <p>If the argument is any value in the range
 972      * {@code 0x7ff0000000000001L} through
 973      * {@code 0x7fffffffffffffffL} or in the range
 974      * {@code 0xfff0000000000001L} through
 975      * {@code 0xffffffffffffffffL}, the result is a NaN.  No IEEE
 976      * 754 floating-point operation provided by Java can distinguish
 977      * between two NaN values of the same type with different bit
 978      * patterns.  Distinct values of NaN are only distinguishable by
 979      * use of the {@code Double.doubleToRawLongBits} method.
 980      *
 981      * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three
 982      * values that can be computed from the argument:
 983      *
 984      * <blockquote><pre>{@code
 985      * int s = ((bits >> 63) == 0) ? 1 : -1;
 986      * int e = (int)((bits >> 52) & 0x7ffL);
 987      * long m = (e == 0) ?
 988      *                 (bits & 0xfffffffffffffL) << 1 :
 989      *                 (bits & 0xfffffffffffffL) | 0x10000000000000L;
 990      * }</pre></blockquote>
 991      *
 992      * Then the floating-point result equals the value of the mathematical
 993      * expression <i>s</i>&middot;<i>m</i>&middot;2<sup><i>e</i>-1075</sup>.
 994      *
 995      * <p>Note that this method may not be able to return a
 996      * {@code double} NaN with exactly same bit pattern as the
 997      * {@code long} argument.  IEEE 754 distinguishes between two
 998      * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>.  The
 999      * differences between the two kinds of NaN are generally not
1000      * visible in Java.  Arithmetic operations on signaling NaNs turn
1001      * them into quiet NaNs with a different, but often similar, bit
1002      * pattern.  However, on some processors merely copying a
1003      * signaling NaN also performs that conversion.  In particular,
1004      * copying a signaling NaN to return it to the calling method
1005      * may perform this conversion.  So {@code longBitsToDouble}
1006      * may not be able to return a {@code double} with a
1007      * signaling NaN bit pattern.  Consequently, for some
1008      * {@code long} values,
1009      * {@code doubleToRawLongBits(longBitsToDouble(start))} may
1010      * <i>not</i> equal {@code start}.  Moreover, which
1011      * particular bit patterns represent signaling NaNs is platform
1012      * dependent; although all NaN bit patterns, quiet or signaling,
1013      * must be in the NaN range identified above.
1014      *
1015      * @param   bits   any {@code long} integer.
1016      * @return  the {@code double} floating-point value with the same
1017      *          bit pattern.
1018      */
1019     @HotSpotIntrinsicCandidate
1020     public static native double longBitsToDouble(long bits);
1021 
1022     /**
1023      * Compares two {@code Double} objects numerically.  There
1024      * are two ways in which comparisons performed by this method
1025      * differ from those performed by the Java language numerical
1026      * comparison operators ({@code <, <=, ==, >=, >})
1027      * when applied to primitive {@code double} values:
1028      * <ul><li>
1029      *          {@code Double.NaN} is considered by this method
1030      *          to be equal to itself and greater than all other
1031      *          {@code double} values (including
1032      *          {@code Double.POSITIVE_INFINITY}).
1033      * <li>
1034      *          {@code 0.0d} is considered by this method to be greater
1035      *          than {@code -0.0d}.
1036      * </ul>
1037      * This ensures that the <i>natural ordering</i> of
1038      * {@code Double} objects imposed by this method is <i>consistent
1039      * with equals</i>.
1040      *
1041      * @param   anotherDouble   the {@code Double} to be compared.
1042      * @return  the value {@code 0} if {@code anotherDouble} is
1043      *          numerically equal to this {@code Double}; a value
1044      *          less than {@code 0} if this {@code Double}
1045      *          is numerically less than {@code anotherDouble};
1046      *          and a value greater than {@code 0} if this
1047      *          {@code Double} is numerically greater than
1048      *          {@code anotherDouble}.
1049      *
1050      * @since   1.2
1051      */
1052     public int compareTo(Double anotherDouble) {
1053         return Double.compare(value, anotherDouble.value);
1054     }
1055 
1056     /**
1057      * Compares the two specified {@code double} values. The sign
1058      * of the integer value returned is the same as that of the
1059      * integer that would be returned by the call:
1060      * <pre>
1061      *    new Double(d1).compareTo(new Double(d2))
1062      * </pre>
1063      *
1064      * @param   d1        the first {@code double} to compare
1065      * @param   d2        the second {@code double} to compare
1066      * @return  the value {@code 0} if {@code d1} is
1067      *          numerically equal to {@code d2}; a value less than
1068      *          {@code 0} if {@code d1} is numerically less than
1069      *          {@code d2}; and a value greater than {@code 0}
1070      *          if {@code d1} is numerically greater than
1071      *          {@code d2}.
1072      * @since 1.4
1073      */
1074     public static int compare(double d1, double d2) {
1075         if (d1 < d2)
1076             return -1;           // Neither val is NaN, thisVal is smaller
1077         if (d1 > d2)
1078             return 1;            // Neither val is NaN, thisVal is larger
1079 
1080         // Cannot use doubleToRawLongBits because of possibility of NaNs.
1081         long thisBits    = Double.doubleToLongBits(d1);
1082         long anotherBits = Double.doubleToLongBits(d2);
1083 
1084         return (thisBits == anotherBits ?  0 : // Values are equal
1085                 (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1086                  1));                          // (0.0, -0.0) or (NaN, !NaN)
1087     }
1088 
1089     /**
1090      * Adds two {@code double} values together as per the + operator.
1091      *
1092      * @param a the first operand
1093      * @param b the second operand
1094      * @return the sum of {@code a} and {@code b}
1095      * @jls 4.2.4 Floating-Point Operations
1096      * @see java.util.function.BinaryOperator
1097      * @since 1.8
1098      */
1099     public static double sum(double a, double b) {
1100         return a + b;
1101     }
1102 
1103     /**
1104      * Returns the greater of two {@code double} values
1105      * as if by calling {@link Math#max(double, double) Math.max}.
1106      *
1107      * @param a the first operand
1108      * @param b the second operand
1109      * @return the greater of {@code a} and {@code b}
1110      * @see java.util.function.BinaryOperator
1111      * @since 1.8
1112      */
1113     public static double max(double a, double b) {
1114         return Math.max(a, b);
1115     }
1116 
1117     /**
1118      * Returns the smaller of two {@code double} values
1119      * as if by calling {@link Math#min(double, double) Math.min}.
1120      *
1121      * @param a the first operand
1122      * @param b the second operand
1123      * @return the smaller of {@code a} and {@code b}.
1124      * @see java.util.function.BinaryOperator
1125      * @since 1.8
1126      */
1127     public static double min(double a, double b) {
1128         return Math.min(a, b);
1129     }
1130 
1131     /**
1132      * Returns an {@link Optional} containing the nominal descriptor for this
1133      * instance, which is the instance itself.
1134      *
1135      * @return an {@link Optional} describing the {@linkplain Double} instance
1136      * @since 12
1137      */
1138     @Override
1139     public Optional<Double> describeConstable() {
1140         return Optional.of(this);
1141     }
1142 
1143     /**
1144      * Resolves this instance as a {@link ConstantDesc}, the result of which is
1145      * the instance itself.
1146      *
1147      * @param lookup ignored
1148      * @return the {@linkplain Double} instance
1149      * @since 12
1150      */
1151     @Override
1152     public Double resolveConstantDesc(MethodHandles.Lookup lookup) {
1153         return this;
1154     }
1155 
1156     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1157     private static final long serialVersionUID = -9172774392245257468L;
1158 }