1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27package java.lang; 28 29import sun.misc.FpUtils; 30import 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 */ 49public 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>)·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>) double[].class.getComponentType(); 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>'\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>'\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> ≤ <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 ≤ <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>'\u002E'</code>), followed by decimal digits 178 * representing the fractional part of <i>a</i>, followed by the 179 * letter '{@code E}' (<code>'\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 FloatingDecimal.getThreadLocalInstance().loadDouble(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>'\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 (FpUtils.rawCopySign(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 FpUtils.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™ 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™ 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.getThreadLocalInstance().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.getThreadLocalInstance().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 * Returns {@code true} if the argument is a finite floating-point 576 * value; returns {@code false} otherwise (for NaN and infinity 577 * arguments). 578 * 579 * @param d the {@code double} value to be tested 580 * @return {@code true} if the argument is a finite 581 * floating-point value, {@code false} otherwise. 582 * @since 1.8 583 */ 584 public static boolean isFinite(double d) { 585 return Math.abs(d) <= DoubleConsts.MAX_VALUE; 586 } 587 588 /** 589 * The value of the Double. 590 * 591 * @serial 592 */ 593 private final double value; 594 595 /** 596 * Constructs a newly allocated {@code Double} object that 597 * represents the primitive {@code double} argument. 598 * 599 * @param value the value to be represented by the {@code Double}. 600 */ 601 public Double(double value) { 602 this.value = value; 603 } 604 605 /** 606 * Constructs a newly allocated {@code Double} object that 607 * represents the floating-point value of type {@code double} 608 * represented by the string. The string is converted to a 609 * {@code double} value as if by the {@code valueOf} method. 610 * 611 * @param s a string to be converted to a {@code Double}. 612 * @throws NumberFormatException if the string does not contain a 613 * parsable number. 614 * @see java.lang.Double#valueOf(java.lang.String) 615 */ 616 public Double(String s) throws NumberFormatException { 617 // REMIND: this is inefficient 618 this(valueOf(s).doubleValue()); 619 } 620 621 /** 622 * Returns {@code true} if this {@code Double} value is 623 * a Not-a-Number (NaN), {@code false} otherwise. 624 * 625 * @return {@code true} if the value represented by this object is 626 * NaN; {@code false} otherwise. 627 */ 628 public boolean isNaN() { 629 return isNaN(value); 630 } 631 632 /** 633 * Returns {@code true} if this {@code Double} value is 634 * infinitely large in magnitude, {@code false} otherwise. 635 * 636 * @return {@code true} if the value represented by this object is 637 * positive infinity or negative infinity; 638 * {@code false} otherwise. 639 */ 640 public boolean isInfinite() { 641 return isInfinite(value); 642 } 643 644 /** 645 * Returns a string representation of this {@code Double} object. 646 * The primitive {@code double} value represented by this 647 * object is converted to a string exactly as if by the method 648 * {@code toString} of one argument. 649 * 650 * @return a {@code String} representation of this object. 651 * @see java.lang.Double#toString(double) 652 */ 653 public String toString() { 654 return toString(value); 655 } 656 657 /** 658 * Returns the value of this {@code Double} as a {@code byte} (by 659 * casting to a {@code byte}). 660 * 661 * @return the {@code double} value represented by this object 662 * converted to type {@code byte} 663 * @since JDK1.1 664 */ 665 public byte byteValue() { 666 return (byte)value; 667 } 668 669 /** 670 * Returns the value of this {@code Double} as a 671 * {@code short} (by casting to a {@code short}). 672 * 673 * @return the {@code double} value represented by this object 674 * converted to type {@code short} 675 * @since JDK1.1 676 */ 677 public short shortValue() { 678 return (short)value; 679 } 680 681 /** 682 * Returns the value of this {@code Double} as an 683 * {@code int} (by casting to type {@code int}). 684 * 685 * @return the {@code double} value represented by this object 686 * converted to type {@code int} 687 */ 688 public int intValue() { 689 return (int)value; 690 } 691 692 /** 693 * Returns the value of this {@code Double} as a 694 * {@code long} (by casting to type {@code long}). 695 * 696 * @return the {@code double} value represented by this object 697 * converted to type {@code long} 698 */ 699 public long longValue() { 700 return (long)value; 701 } 702 703 /** 704 * Returns the {@code float} value of this 705 * {@code Double} object. 706 * 707 * @return the {@code double} value represented by this object 708 * converted to type {@code float} 709 * @since JDK1.0 710 */ 711 public float floatValue() { 712 return (float)value; 713 } 714 715 /** 716 * Returns the {@code double} value of this 717 * {@code Double} object. 718 * 719 * @return the {@code double} value represented by this object 720 */ 721 public double doubleValue() { 722 return (double)value; 723 } 724 725 /** 726 * Returns a hash code for this {@code Double} object. The 727 * result is the exclusive OR of the two halves of the 728 * {@code long} integer bit representation, exactly as 729 * produced by the method {@link #doubleToLongBits(double)}, of 730 * the primitive {@code double} value represented by this 731 * {@code Double} object. That is, the hash code is the value 732 * of the expression: 733 * 734 * <blockquote> 735 * {@code (int)(v^(v>>>32))} 736 * </blockquote> 737 * 738 * where {@code v} is defined by: 739 * 740 * <blockquote> 741 * {@code long v = Double.doubleToLongBits(this.doubleValue());} 742 * </blockquote> 743 * 744 * @return a {@code hash code} value for this object. 745 */ 746 public int hashCode() { 747 return Double.hashCode(value); 748 } 749 750 /** 751 * Returns a hash code for a {@code double} value; compatible with 752 * {@code Double.hashCode()}. 753 * 754 * @param value the value to hash 755 * @return a hash code value for a {@code double} value. 756 * @since 1.8 757 */ 758 public static int hashCode(double value) { 759 long bits = doubleToLongBits(value); 760 return (int)(bits ^ (bits >>> 32)); 761 } 762 763 /** 764 * Compares this object against the specified object. The result 765 * is {@code true} if and only if the argument is not 766 * {@code null} and is a {@code Double} object that 767 * represents a {@code double} that has the same value as the 768 * {@code double} represented by this object. For this 769 * purpose, two {@code double} values are considered to be 770 * the same if and only if the method {@link 771 * #doubleToLongBits(double)} returns the identical 772 * {@code long} value when applied to each. 773 * 774 * <p>Note that in most cases, for two instances of class 775 * {@code Double}, {@code d1} and {@code d2}, the 776 * value of {@code d1.equals(d2)} is {@code true} if and 777 * only if 778 * 779 * <blockquote> 780 * {@code d1.doubleValue() == d2.doubleValue()} 781 * </blockquote> 782 * 783 * <p>also has the value {@code true}. However, there are two 784 * exceptions: 785 * <ul> 786 * <li>If {@code d1} and {@code d2} both represent 787 * {@code Double.NaN}, then the {@code equals} method 788 * returns {@code true}, even though 789 * {@code Double.NaN==Double.NaN} has the value 790 * {@code false}. 791 * <li>If {@code d1} represents {@code +0.0} while 792 * {@code d2} represents {@code -0.0}, or vice versa, 793 * the {@code equal} test has the value {@code false}, 794 * even though {@code +0.0==-0.0} has the value {@code true}. 795 * </ul> 796 * This definition allows hash tables to operate properly. 797 * @param obj the object to compare with. 798 * @return {@code true} if the objects are the same; 799 * {@code false} otherwise. 800 * @see java.lang.Double#doubleToLongBits(double) 801 */ 802 public boolean equals(Object obj) { 803 return (obj instanceof Double) 804 && (doubleToLongBits(((Double)obj).value) == 805 doubleToLongBits(value)); 806 } 807 808 /** 809 * Returns a representation of the specified floating-point value 810 * according to the IEEE 754 floating-point "double 811 * format" bit layout. 812 * 813 * <p>Bit 63 (the bit that is selected by the mask 814 * {@code 0x8000000000000000L}) represents the sign of the 815 * floating-point number. Bits 816 * 62-52 (the bits that are selected by the mask 817 * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0 818 * (the bits that are selected by the mask 819 * {@code 0x000fffffffffffffL}) represent the significand 820 * (sometimes called the mantissa) of the floating-point number. 821 * 822 * <p>If the argument is positive infinity, the result is 823 * {@code 0x7ff0000000000000L}. 824 * 825 * <p>If the argument is negative infinity, the result is 826 * {@code 0xfff0000000000000L}. 827 * 828 * <p>If the argument is NaN, the result is 829 * {@code 0x7ff8000000000000L}. 830 * 831 * <p>In all cases, the result is a {@code long} integer that, when 832 * given to the {@link #longBitsToDouble(long)} method, will produce a 833 * floating-point value the same as the argument to 834 * {@code doubleToLongBits} (except all NaN values are 835 * collapsed to a single "canonical" NaN value). 836 * 837 * @param value a {@code double} precision floating-point number. 838 * @return the bits that represent the floating-point number. 839 */ 840 public static long doubleToLongBits(double value) { 841 long result = doubleToRawLongBits(value); 842 // Check for NaN based on values of bit fields, maximum 843 // exponent and nonzero significand. 844 if ( ((result & DoubleConsts.EXP_BIT_MASK) == 845 DoubleConsts.EXP_BIT_MASK) && 846 (result & DoubleConsts.SIGNIF_BIT_MASK) != 0L) 847 result = 0x7ff8000000000000L; 848 return result; 849 } 850 851 /** 852 * Returns a representation of the specified floating-point value 853 * according to the IEEE 754 floating-point "double 854 * format" bit layout, preserving Not-a-Number (NaN) values. 855 * 856 * <p>Bit 63 (the bit that is selected by the mask 857 * {@code 0x8000000000000000L}) represents the sign of the 858 * floating-point number. Bits 859 * 62-52 (the bits that are selected by the mask 860 * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0 861 * (the bits that are selected by the mask 862 * {@code 0x000fffffffffffffL}) represent the significand 863 * (sometimes called the mantissa) of the floating-point number. 864 * 865 * <p>If the argument is positive infinity, the result is 866 * {@code 0x7ff0000000000000L}. 867 * 868 * <p>If the argument is negative infinity, the result is 869 * {@code 0xfff0000000000000L}. 870 * 871 * <p>If the argument is NaN, the result is the {@code long} 872 * integer representing the actual NaN value. Unlike the 873 * {@code doubleToLongBits} method, 874 * {@code doubleToRawLongBits} does not collapse all the bit 875 * patterns encoding a NaN to a single "canonical" NaN 876 * value. 877 * 878 * <p>In all cases, the result is a {@code long} integer that, 879 * when given to the {@link #longBitsToDouble(long)} method, will 880 * produce a floating-point value the same as the argument to 881 * {@code doubleToRawLongBits}. 882 * 883 * @param value a {@code double} precision floating-point number. 884 * @return the bits that represent the floating-point number. 885 * @since 1.3 886 */ 887 public static native long doubleToRawLongBits(double value); 888 889 /** 890 * Returns the {@code double} value corresponding to a given 891 * bit representation. 892 * The argument is considered to be a representation of a 893 * floating-point value according to the IEEE 754 floating-point 894 * "double format" bit layout. 895 * 896 * <p>If the argument is {@code 0x7ff0000000000000L}, the result 897 * is positive infinity. 898 * 899 * <p>If the argument is {@code 0xfff0000000000000L}, the result 900 * is negative infinity. 901 * 902 * <p>If the argument is any value in the range 903 * {@code 0x7ff0000000000001L} through 904 * {@code 0x7fffffffffffffffL} or in the range 905 * {@code 0xfff0000000000001L} through 906 * {@code 0xffffffffffffffffL}, the result is a NaN. No IEEE 907 * 754 floating-point operation provided by Java can distinguish 908 * between two NaN values of the same type with different bit 909 * patterns. Distinct values of NaN are only distinguishable by 910 * use of the {@code Double.doubleToRawLongBits} method. 911 * 912 * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three 913 * values that can be computed from the argument: 914 * 915 * <blockquote><pre> 916 * int s = ((bits >> 63) == 0) ? 1 : -1; 917 * int e = (int)((bits >> 52) & 0x7ffL); 918 * long m = (e == 0) ? 919 * (bits & 0xfffffffffffffL) << 1 : 920 * (bits & 0xfffffffffffffL) | 0x10000000000000L; 921 * </pre></blockquote> 922 * 923 * Then the floating-point result equals the value of the mathematical 924 * expression <i>s</i>·<i>m</i>·2<sup><i>e</i>-1075</sup>. 925 * 926 * <p>Note that this method may not be able to return a 927 * {@code double} NaN with exactly same bit pattern as the 928 * {@code long} argument. IEEE 754 distinguishes between two 929 * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>. The 930 * differences between the two kinds of NaN are generally not 931 * visible in Java. Arithmetic operations on signaling NaNs turn 932 * them into quiet NaNs with a different, but often similar, bit 933 * pattern. However, on some processors merely copying a 934 * signaling NaN also performs that conversion. In particular, 935 * copying a signaling NaN to return it to the calling method 936 * may perform this conversion. So {@code longBitsToDouble} 937 * may not be able to return a {@code double} with a 938 * signaling NaN bit pattern. Consequently, for some 939 * {@code long} values, 940 * {@code doubleToRawLongBits(longBitsToDouble(start))} may 941 * <i>not</i> equal {@code start}. Moreover, which 942 * particular bit patterns represent signaling NaNs is platform 943 * dependent; although all NaN bit patterns, quiet or signaling, 944 * must be in the NaN range identified above. 945 * 946 * @param bits any {@code long} integer. 947 * @return the {@code double} floating-point value with the same 948 * bit pattern. 949 */ 950 public static native double longBitsToDouble(long bits); 951 952 /** 953 * Compares two {@code Double} objects numerically. There 954 * are two ways in which comparisons performed by this method 955 * differ from those performed by the Java language numerical 956 * comparison operators ({@code <, <=, ==, >=, >}) 957 * when applied to primitive {@code double} values: 958 * <ul><li> 959 * {@code Double.NaN} is considered by this method 960 * to be equal to itself and greater than all other 961 * {@code double} values (including 962 * {@code Double.POSITIVE_INFINITY}). 963 * <li> 964 * {@code 0.0d} is considered by this method to be greater 965 * than {@code -0.0d}. 966 * </ul> 967 * This ensures that the <i>natural ordering</i> of 968 * {@code Double} objects imposed by this method is <i>consistent 969 * with equals</i>. 970 * 971 * @param anotherDouble the {@code Double} to be compared. 972 * @return the value {@code 0} if {@code anotherDouble} is 973 * numerically equal to this {@code Double}; a value 974 * less than {@code 0} if this {@code Double} 975 * is numerically less than {@code anotherDouble}; 976 * and a value greater than {@code 0} if this 977 * {@code Double} is numerically greater than 978 * {@code anotherDouble}. 979 * 980 * @since 1.2 981 */ 982 public int compareTo(Double anotherDouble) { 983 return Double.compare(value, anotherDouble.value); 984 } 985 986 /** 987 * Compares the two specified {@code double} values. The sign 988 * of the integer value returned is the same as that of the 989 * integer that would be returned by the call: 990 * <pre> 991 * new Double(d1).compareTo(new Double(d2)) 992 * </pre> 993 * 994 * @param d1 the first {@code double} to compare 995 * @param d2 the second {@code double} to compare 996 * @return the value {@code 0} if {@code d1} is 997 * numerically equal to {@code d2}; a value less than 998 * {@code 0} if {@code d1} is numerically less than 999 * {@code d2}; and a value greater than {@code 0} 1000 * if {@code d1} is numerically greater than 1001 * {@code d2}. 1002 * @since 1.4 1003 */ 1004 public static int compare(double d1, double d2) { 1005 if (d1 < d2) 1006 return -1; // Neither val is NaN, thisVal is smaller 1007 if (d1 > d2) 1008 return 1; // Neither val is NaN, thisVal is larger 1009 1010 // Cannot use doubleToRawLongBits because of possibility of NaNs. 1011 long thisBits = Double.doubleToLongBits(d1); 1012 long anotherBits = Double.doubleToLongBits(d2); 1013 1014 return (thisBits == anotherBits ? 0 : // Values are equal 1015 (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 1016 1)); // (0.0, -0.0) or (NaN, !NaN) 1017 } 1018 1019 /** 1020 * Adds two {@code double} values together as per the + operator. 1021 * 1022 * @param a the first operand 1023 * @param b the second operand 1024 * @return the sum of {@code a} and {@code b} 1025 * @jls 4.2.4 Floating-Point Operations 1026 * @see java.util.function.BinaryOperator 1027 * @since 1.8 1028 */ 1029 public static double sum(double a, double b) { 1030 return a + b; 1031 } 1032 1033 /** 1034 * Returns the greater of two {@code double} values 1035 * as if by calling {@link Math#max(double, double) Math.max}. 1036 * 1037 * @param a the first operand 1038 * @param b the second operand 1039 * @return the greater of {@code a} and {@code b} 1040 * @see java.util.function.BinaryOperator 1041 * @since 1.8 1042 */ 1043 public static double max(double a, double b) { 1044 return Math.max(a, b); 1045 } 1046 1047 /** 1048 * Returns the smaller of two {@code double} values 1049 * as if by calling {@link Math#min(double, double) Math.min}. 1050 * 1051 * @param a the first operand 1052 * @param b the second operand 1053 * @return the smaller of {@code a} and {@code b}. 1054 * @see java.util.function.BinaryOperator 1055 * @since 1.8 1056 */ 1057 public static double min(double a, double b) { 1058 return Math.min(a, b); 1059 } 1060 1061 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1062 private static final long serialVersionUID = -9172774392245257468L; 1063} 1064