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