Source for java.lang.Double

   1: /* Double.java -- object wrapper for double
   2:    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
   3:    Free Software Foundation, Inc.
   4: 
   5: This file is part of GNU Classpath.
   6: 
   7: GNU Classpath is free software; you can redistribute it and/or modify
   8: it under the terms of the GNU General Public License as published by
   9: the Free Software Foundation; either version 2, or (at your option)
  10: any later version.
  11: 
  12: GNU Classpath is distributed in the hope that it will be useful, but
  13: WITHOUT ANY WARRANTY; without even the implied warranty of
  14: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15: General Public License for more details.
  16: 
  17: You should have received a copy of the GNU General Public License
  18: along with GNU Classpath; see the file COPYING.  If not, write to the
  19: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  20: 02110-1301 USA.
  21: 
  22: Linking this library statically or dynamically with other modules is
  23: making a combined work based on this library.  Thus, the terms and
  24: conditions of the GNU General Public License cover the whole
  25: combination.
  26: 
  27: As a special exception, the copyright holders of this library give you
  28: permission to link this library with independent modules to produce an
  29: executable, regardless of the license terms of these independent
  30: modules, and to copy and distribute the resulting executable under
  31: terms of your choice, provided that you also meet, for each linked
  32: independent module, the terms and conditions of the license of that
  33: module.  An independent module is a module which is not derived from
  34: or based on this library.  If you modify this library, you may extend
  35: this exception to your version of the library, but you are not
  36: obligated to do so.  If you do not wish to do so, delete this
  37: exception statement from your version. */
  38: 
  39: package java.lang;
  40: 
  41: 
  42: /**
  43:  * Instances of class <code>Double</code> represent primitive
  44:  * <code>double</code> values.
  45:  *
  46:  * Additionally, this class provides various helper functions and variables
  47:  * related to doubles.
  48:  *
  49:  * @author Paul Fisher
  50:  * @author Andrew Haley (aph@cygnus.com)
  51:  * @author Eric Blake (ebb9@email.byu.edu)
  52:  * @author Tom Tromey (tromey@redhat.com)
  53:  * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  54:  * @since 1.0
  55:  * @status partly updated to 1.5
  56:  */
  57: public final class Double extends Number implements Comparable<Double>
  58: {
  59:   /**
  60:    * Compatible with JDK 1.0+.
  61:    */
  62:   private static final long serialVersionUID = -9172774392245257468L;
  63: 
  64:   /**
  65:    * The maximum positive value a <code>double</code> may represent
  66:    * is 1.7976931348623157e+308.
  67:    */
  68:   public static final double MAX_VALUE = 1.7976931348623157e+308;
  69: 
  70:   /**
  71:    * The minimum positive value a <code>double</code> may represent
  72:    * is 5e-324.
  73:    */
  74:   public static final double MIN_VALUE = 5e-324;
  75: 
  76:   /**
  77:    * The value of a double representation -1.0/0.0, negative
  78:    * infinity.
  79:    */
  80:   public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
  81: 
  82:   /**
  83:    * The value of a double representing 1.0/0.0, positive infinity.
  84:    */
  85:   public static final double POSITIVE_INFINITY = 1.0 / 0.0;
  86: 
  87:   /**
  88:    * All IEEE 754 values of NaN have the same value in Java.
  89:    */
  90:   public static final double NaN = 0.0 / 0.0;
  91: 
  92:   /**
  93:    * The number of bits needed to represent a <code>double</code>.
  94:    * @since 1.5
  95:    */
  96:   public static final int SIZE = 64;
  97: 
  98:  /**
  99:    * The primitive type <code>double</code> is represented by this
 100:    * <code>Class</code> object.
 101:    * @since 1.1
 102:    */
 103:   public static final Class<Double> TYPE = (Class<Double>) VMClassLoader.getPrimitiveClass('D');
 104: 
 105:   /**
 106:    * The immutable value of this Double.
 107:    *
 108:    * @serial the wrapped double
 109:    */
 110:   private final double value;
 111: 
 112:   /**
 113:    * Create a <code>Double</code> from the primitive <code>double</code>
 114:    * specified.
 115:    *
 116:    * @param value the <code>double</code> argument
 117:    */
 118:   public Double(double value)
 119:   {
 120:     this.value = value;
 121:   }
 122: 
 123:   /**
 124:    * Create a <code>Double</code> from the specified <code>String</code>.
 125:    * This method calls <code>Double.parseDouble()</code>.
 126:    *
 127:    * @param s the <code>String</code> to convert
 128:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 129:    *         <code>double</code>
 130:    * @throws NullPointerException if <code>s</code> is null
 131:    * @see #parseDouble(String)
 132:    */
 133:   public Double(String s)
 134:   {
 135:     value = parseDouble(s);
 136:   }
 137: 
 138:   /**
 139:    * Convert the <code>double</code> to a <code>String</code>.
 140:    * Floating-point string representation is fairly complex: here is a
 141:    * rundown of the possible values.  "<code>[-]</code>" indicates that a
 142:    * negative sign will be printed if the value (or exponent) is negative.
 143:    * "<code>&lt;number&gt;</code>" means a string of digits ('0' to '9').
 144:    * "<code>&lt;digit&gt;</code>" means a single digit ('0' to '9').<br>
 145:    *
 146:    * <table border=1>
 147:    * <tr><th>Value of Double</th><th>String Representation</th></tr>
 148:    * <tr><td>[+-] 0</td> <td><code>[-]0.0</code></td></tr>
 149:    * <tr><td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
 150:    *     <td><code>[-]number.number</code></td></tr>
 151:    * <tr><td>Other numeric value</td>
 152:    *     <td><code>[-]&lt;digit&gt;.&lt;number&gt;
 153:    *          E[-]&lt;number&gt;</code></td></tr>
 154:    * <tr><td>[+-] infinity</td> <td><code>[-]Infinity</code></td></tr>
 155:    * <tr><td>NaN</td> <td><code>NaN</code></td></tr>
 156:    * </table>
 157:    *
 158:    * Yes, negative zero <em>is</em> a possible value.  Note that there is
 159:    * <em>always</em> a <code>.</code> and at least one digit printed after
 160:    * it: even if the number is 3, it will be printed as <code>3.0</code>.
 161:    * After the ".", all digits will be printed except trailing zeros. The
 162:    * result is rounded to the shortest decimal number which will parse back
 163:    * to the same double.
 164:    *
 165:    * <p>To create other output formats, use {@link java.text.NumberFormat}.
 166:    *
 167:    * @XXX specify where we are not in accord with the spec.
 168:    *
 169:    * @param d the <code>double</code> to convert
 170:    * @return the <code>String</code> representing the <code>double</code>
 171:    */
 172:   public static String toString(double d)
 173:   {
 174:     return VMDouble.toString(d, false);
 175:   }
 176: 
 177:   /**
 178:    * Convert a double value to a hexadecimal string.  This converts as
 179:    * follows:
 180:    * <ul>
 181:    * <li> A NaN value is converted to the string "NaN".
 182:    * <li> Positive infinity is converted to the string "Infinity".
 183:    * <li> Negative infinity is converted to the string "-Infinity".
 184:    * <li> For all other values, the first character of the result is '-'
 185:    * if the value is negative.  This is followed by '0x1.' if the
 186:    * value is normal, and '0x0.' if the value is denormal.  This is
 187:    * then followed by a (lower-case) hexadecimal representation of the
 188:    * mantissa, with leading zeros as required for denormal values.
 189:    * The next character is a 'p', and this is followed by a decimal
 190:    * representation of the unbiased exponent.
 191:    * </ul>
 192:    * @param d the double value
 193:    * @return the hexadecimal string representation
 194:    * @since 1.5
 195:    */
 196:   public static String toHexString(double d)
 197:   {
 198:     if (isNaN(d))
 199:       return "NaN";
 200:     if (isInfinite(d))
 201:       return d < 0 ? "-Infinity" : "Infinity";
 202: 
 203:     long bits = doubleToLongBits(d);
 204:     StringBuilder result = new StringBuilder();
 205:     
 206:     if (bits < 0)
 207:       result.append('-');
 208:     result.append("0x");
 209: 
 210:     final int mantissaBits = 52;
 211:     final int exponentBits = 11;
 212:     long mantMask = (1L << mantissaBits) - 1;
 213:     long mantissa = bits & mantMask;
 214:     long expMask = (1L << exponentBits) - 1;
 215:     long exponent = (bits >>> mantissaBits) & expMask;
 216: 
 217:     result.append(exponent == 0 ? '0' : '1');
 218:     result.append('.');
 219:     result.append(Long.toHexString(mantissa));
 220:     if (exponent == 0 && mantissa != 0)
 221:       {
 222:         // Treat denormal specially by inserting '0's to make
 223:         // the length come out right.  The constants here are
 224:         // to account for things like the '0x'.
 225:         int offset = 4 + ((bits < 0) ? 1 : 0);
 226:         // The silly +3 is here to keep the code the same between
 227:         // the Float and Double cases.  In Float the value is
 228:         // not a multiple of 4.
 229:         int desiredLength = offset + (mantissaBits + 3) / 4;
 230:         while (result.length() < desiredLength)
 231:           result.insert(offset, '0');
 232:       }
 233:     result.append('p');
 234:     if (exponent == 0 && mantissa == 0)
 235:       {
 236:         // Zero, so do nothing special.
 237:       }
 238:     else
 239:       {
 240:         // Apply bias.
 241:         boolean denormal = exponent == 0;
 242:         exponent -= (1 << (exponentBits - 1)) - 1;
 243:         // Handle denormal.
 244:         if (denormal)
 245:           ++exponent;
 246:       }
 247: 
 248:     result.append(Long.toString(exponent));
 249:     return result.toString();
 250:   }
 251: 
 252:   /**
 253:    * Returns a <code>Double</code> object wrapping the value.
 254:    * In contrast to the <code>Double</code> constructor, this method
 255:    * may cache some values.  It is used by boxing conversion.
 256:    *
 257:    * @param val the value to wrap
 258:    * @return the <code>Double</code>
 259:    * @since 1.5
 260:    */
 261:   public static Double valueOf(double val)
 262:   {
 263:     // We don't actually cache, but we could.
 264:     return new Double(val);
 265:   }
 266: 
 267:  /**
 268:    * Create a new <code>Double</code> object using the <code>String</code>.
 269:    *
 270:    * @param s the <code>String</code> to convert
 271:    * @return the new <code>Double</code>
 272:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 273:    *         <code>double</code>
 274:    * @throws NullPointerException if <code>s</code> is null.
 275:    * @see #parseDouble(String)
 276:    */
 277:   public static Double valueOf(String s)
 278:   {
 279:     return new Double(parseDouble(s));
 280:   }
 281: 
 282:   /**
 283:    * Parse the specified <code>String</code> as a <code>double</code>. The
 284:    * extended BNF grammar is as follows:<br>
 285:    * <pre>
 286:    * <em>DecodableString</em>:
 287:    *      ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
 288:    *    | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
 289:    *    | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
 290:    *              [ <code>f</code> | <code>F</code> | <code>d</code>
 291:    *                | <code>D</code>] )
 292:    * <em>FloatingPoint</em>:
 293:    *      ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
 294:    *              [ <em>Exponent</em> ] )
 295:    *    | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
 296:    * <em>Exponent</em>:
 297:    *      ( ( <code>e</code> | <code>E</code> )
 298:    *              [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
 299:    * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
 300:    * </pre>
 301:    *
 302:    * <p>NaN and infinity are special cases, to allow parsing of the output
 303:    * of toString.  Otherwise, the result is determined by calculating
 304:    * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
 305:    * to the nearest double. Remember that many numbers cannot be precisely
 306:    * represented in floating point. In case of overflow, infinity is used,
 307:    * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
 308:    * this does not accept Unicode digits outside the ASCII range.
 309:    *
 310:    * <p>If an unexpected character is found in the <code>String</code>, a
 311:    * <code>NumberFormatException</code> will be thrown.  Leading and trailing
 312:    * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
 313:    * internal to the actual number are not allowed.
 314:    *
 315:    * <p>To parse numbers according to another format, consider using
 316:    * {@link java.text.NumberFormat}.
 317:    *
 318:    * @XXX specify where/how we are not in accord with the spec.
 319:    *
 320:    * @param str the <code>String</code> to convert
 321:    * @return the <code>double</code> value of <code>s</code>
 322:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 323:    *         <code>double</code>
 324:    * @throws NullPointerException if <code>s</code> is null
 325:    * @see #MIN_VALUE
 326:    * @see #MAX_VALUE
 327:    * @see #POSITIVE_INFINITY
 328:    * @see #NEGATIVE_INFINITY
 329:    * @since 1.2
 330:    */
 331:   public static double parseDouble(String str)
 332:   {
 333:     return VMDouble.parseDouble(str);
 334:   }
 335: 
 336:   /**
 337:    * Return <code>true</code> if the <code>double</code> has the same
 338:    * value as <code>NaN</code>, otherwise return <code>false</code>.
 339:    *
 340:    * @param v the <code>double</code> to compare
 341:    * @return whether the argument is <code>NaN</code>.
 342:    */
 343:   public static boolean isNaN(double v)
 344:   {
 345:     // This works since NaN != NaN is the only reflexive inequality
 346:     // comparison which returns true.
 347:     return v != v;
 348:   }
 349: 
 350:   /**
 351:    * Return <code>true</code> if the <code>double</code> has a value
 352:    * equal to either <code>NEGATIVE_INFINITY</code> or
 353:    * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
 354:    *
 355:    * @param v the <code>double</code> to compare
 356:    * @return whether the argument is (-/+) infinity.
 357:    */
 358:   public static boolean isInfinite(double v)
 359:   {
 360:     return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
 361:   }
 362: 
 363:   /**
 364:    * Return <code>true</code> if the value of this <code>Double</code>
 365:    * is the same as <code>NaN</code>, otherwise return <code>false</code>.
 366:    *
 367:    * @return whether this <code>Double</code> is <code>NaN</code>
 368:    */
 369:   public boolean isNaN()
 370:   {
 371:     return isNaN(value);
 372:   }
 373: 
 374:   /**
 375:    * Return <code>true</code> if the value of this <code>Double</code>
 376:    * is the same as <code>NEGATIVE_INFINITY</code> or
 377:    * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
 378:    *
 379:    * @return whether this <code>Double</code> is (-/+) infinity
 380:    */
 381:   public boolean isInfinite()
 382:   {
 383:     return isInfinite(value);
 384:   }
 385: 
 386:   /**
 387:    * Convert the <code>double</code> value of this <code>Double</code>
 388:    * to a <code>String</code>.  This method calls
 389:    * <code>Double.toString(double)</code> to do its dirty work.
 390:    *
 391:    * @return the <code>String</code> representation
 392:    * @see #toString(double)
 393:    */
 394:   public String toString()
 395:   {
 396:     return toString(value);
 397:   }
 398: 
 399:   /**
 400:    * Return the value of this <code>Double</code> as a <code>byte</code>.
 401:    *
 402:    * @return the byte value
 403:    * @since 1.1
 404:    */
 405:   public byte byteValue()
 406:   {
 407:     return (byte) value;
 408:   }
 409: 
 410:   /**
 411:    * Return the value of this <code>Double</code> as a <code>short</code>.
 412:    *
 413:    * @return the short value
 414:    * @since 1.1
 415:    */
 416:   public short shortValue()
 417:   {
 418:     return (short) value;
 419:   }
 420: 
 421:   /**
 422:    * Return the value of this <code>Double</code> as an <code>int</code>.
 423:    *
 424:    * @return the int value
 425:    */
 426:   public int intValue()
 427:   {
 428:     return (int) value;
 429:   }
 430: 
 431:   /**
 432:    * Return the value of this <code>Double</code> as a <code>long</code>.
 433:    *
 434:    * @return the long value
 435:    */
 436:   public long longValue()
 437:   {
 438:     return (long) value;
 439:   }
 440: 
 441:   /**
 442:    * Return the value of this <code>Double</code> as a <code>float</code>.
 443:    *
 444:    * @return the float value
 445:    */
 446:   public float floatValue()
 447:   {
 448:     return (float) value;
 449:   }
 450: 
 451:   /**
 452:    * Return the value of this <code>Double</code>.
 453:    *
 454:    * @return the double value
 455:    */
 456:   public double doubleValue()
 457:   {
 458:     return value;
 459:   }
 460: 
 461:   /**
 462:    * Return a hashcode representing this Object. <code>Double</code>'s hash
 463:    * code is calculated by:<br>
 464:    * <code>long v = Double.doubleToLongBits(doubleValue());<br>
 465:    *    int hash = (int)(v^(v&gt;&gt;32))</code>.
 466:    *
 467:    * @return this Object's hash code
 468:    * @see #doubleToLongBits(double)
 469:    */
 470:   public int hashCode()
 471:   {
 472:     long v = doubleToLongBits(value);
 473:     return (int) (v ^ (v >>> 32));
 474:   }
 475: 
 476:   /**
 477:    * Returns <code>true</code> if <code>obj</code> is an instance of
 478:    * <code>Double</code> and represents the same double value. Unlike comparing
 479:    * two doubles with <code>==</code>, this treats two instances of
 480:    * <code>Double.NaN</code> as equal, but treats <code>0.0</code> and
 481:    * <code>-0.0</code> as unequal.
 482:    *
 483:    * <p>Note that <code>d1.equals(d2)</code> is identical to
 484:    * <code>doubleToLongBits(d1.doubleValue()) ==
 485:    *    doubleToLongBits(d2.doubleValue())</code>.
 486:    *
 487:    * @param obj the object to compare
 488:    * @return whether the objects are semantically equal
 489:    */
 490:   public boolean equals(Object obj)
 491:   {
 492:     if (! (obj instanceof Double))
 493:       return false;
 494: 
 495:     double d = ((Double) obj).value;
 496: 
 497:     // Avoid call to native method. However, some implementations, like gcj,
 498:     // are better off using floatToIntBits(value) == floatToIntBits(f).
 499:     // Check common case first, then check NaN and 0.
 500:     if (value == d)
 501:       return (value != 0) || (1 / value == 1 / d);
 502:     return isNaN(value) && isNaN(d);
 503:   }
 504: 
 505:   /**
 506:    * Convert the double to the IEEE 754 floating-point "double format" bit
 507:    * layout. Bit 63 (the most significant) is the sign bit, bits 62-52
 508:    * (masked by 0x7ff0000000000000L) represent the exponent, and bits 51-0
 509:    * (masked by 0x000fffffffffffffL) are the mantissa. This function
 510:    * collapses all versions of NaN to 0x7ff8000000000000L. The result of this
 511:    * function can be used as the argument to
 512:    * <code>Double.longBitsToDouble(long)</code> to obtain the original
 513:    * <code>double</code> value.
 514:    *
 515:    * @param value the <code>double</code> to convert
 516:    * @return the bits of the <code>double</code>
 517:    * @see #longBitsToDouble(long)
 518:    */
 519:   public static long doubleToLongBits(double value)
 520:   {
 521:     return VMDouble.doubleToLongBits(value);
 522:   }
 523: 
 524:   /**
 525:    * Convert the double to the IEEE 754 floating-point "double format" bit
 526:    * layout. Bit 63 (the most significant) is the sign bit, bits 62-52
 527:    * (masked by 0x7ff0000000000000L) represent the exponent, and bits 51-0
 528:    * (masked by 0x000fffffffffffffL) are the mantissa. This function
 529:    * leaves NaN alone, rather than collapsing to a canonical value. The
 530:    * result of this function can be used as the argument to
 531:    * <code>Double.longBitsToDouble(long)</code> to obtain the original
 532:    * <code>double</code> value.
 533:    *
 534:    * @param value the <code>double</code> to convert
 535:    * @return the bits of the <code>double</code>
 536:    * @see #longBitsToDouble(long)
 537:    */
 538:   public static long doubleToRawLongBits(double value)
 539:   {
 540:     return VMDouble.doubleToRawLongBits(value);
 541:   }
 542: 
 543:   /**
 544:    * Convert the argument in IEEE 754 floating-point "double format" bit
 545:    * layout to the corresponding float. Bit 63 (the most significant) is the
 546:    * sign bit, bits 62-52 (masked by 0x7ff0000000000000L) represent the
 547:    * exponent, and bits 51-0 (masked by 0x000fffffffffffffL) are the mantissa.
 548:    * This function leaves NaN alone, so that you can recover the bit pattern
 549:    * with <code>Double.doubleToRawLongBits(double)</code>.
 550:    *
 551:    * @param bits the bits to convert
 552:    * @return the <code>double</code> represented by the bits
 553:    * @see #doubleToLongBits(double)
 554:    * @see #doubleToRawLongBits(double)
 555:    */
 556:   public static double longBitsToDouble(long bits)
 557:   {
 558:     return VMDouble.longBitsToDouble(bits);
 559:   }
 560: 
 561:   /**
 562:    * Compare two Doubles numerically by comparing their <code>double</code>
 563:    * values. The result is positive if the first is greater, negative if the
 564:    * second is greater, and 0 if the two are equal. However, this special
 565:    * cases NaN and signed zero as follows: NaN is considered greater than
 566:    * all other doubles, including <code>POSITIVE_INFINITY</code>, and positive
 567:    * zero is considered greater than negative zero.
 568:    *
 569:    * @param d the Double to compare
 570:    * @return the comparison
 571:    * @since 1.2
 572:    */
 573:   public int compareTo(Double d)
 574:   {
 575:     return compare(value, d.value);
 576:   }
 577: 
 578:   /**
 579:    * Behaves like <code>new Double(x).compareTo(new Double(y))</code>; in
 580:    * other words this compares two doubles, special casing NaN and zero,
 581:    * without the overhead of objects.
 582:    *
 583:    * @param x the first double to compare
 584:    * @param y the second double to compare
 585:    * @return the comparison
 586:    * @since 1.4
 587:    */
 588:   public static int compare(double x, double y)
 589:   {
 590:     if (isNaN(x))
 591:       return isNaN(y) ? 0 : 1;
 592:     if (isNaN(y))
 593:       return -1;
 594:     // recall that 0.0 == -0.0, so we convert to infinites and try again
 595:     if (x == 0 && y == 0)
 596:       return (int) (1 / x - 1 / y);
 597:     if (x == y)
 598:       return 0;
 599: 
 600:     return x > y ? 1 : -1;
 601:   }
 602: }