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