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