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