1 /*
   2  * Copyright (c) 1994, 2024, 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 java.lang.invoke.MethodHandles;
  29 import java.lang.constant.Constable;
  30 import java.lang.constant.ConstantDesc;
  31 import java.util.Optional;
  32 
  33 import jdk.internal.math.FloatingDecimal;
  34 import jdk.internal.math.DoubleConsts;
  35 import jdk.internal.math.DoubleToDecimal;
  36 import jdk.internal.vm.annotation.IntrinsicCandidate;
  37 
  38 /**
  39  * The {@code Double} class wraps a value of the primitive type
  40  * {@code double} in an object. An object of type
  41  * {@code Double} contains a single field whose type is
  42  * {@code double}.
  43  *
  44  * <p>In addition, this class provides several methods for converting a
  45  * {@code double} to a {@code String} and a
  46  * {@code String} to a {@code double}, as well as other
  47  * constants and methods useful when dealing with a
  48  * {@code double}.
  49  *
  50  * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
  51  * class; programmers should treat instances that are
  52  * {@linkplain #equals(Object) equal} as interchangeable and should not
  53  * use instances for synchronization, or unpredictable behavior may
  54  * occur. For example, in a future release, synchronization may fail.
  55  *
  56  * <h2><a id=equivalenceRelation>Floating-point Equality, Equivalence,
  57  * and Comparison</a></h2>
  58  *
  59  * IEEE 754 floating-point values include finite nonzero values,
  60  * signed zeros ({@code +0.0} and {@code -0.0}), signed infinities
  61  * ({@linkplain Double#POSITIVE_INFINITY positive infinity} and
  62  * {@linkplain Double#NEGATIVE_INFINITY negative infinity}), and
  63  * {@linkplain Double#NaN NaN} (not-a-number).
  64  *
  65  * <p>An <em>equivalence relation</em> on a set of values is a boolean
  66  * relation on pairs of values that is reflexive, symmetric, and
  67  * transitive. For more discussion of equivalence relations and object
  68  * equality, see the {@link Object#equals Object.equals}
  69  * specification. An equivalence relation partitions the values it
  70  * operates over into sets called <i>equivalence classes</i>.  All the
  71  * members of the equivalence class are equal to each other under the
  72  * relation. An equivalence class may contain only a single member. At
  73  * least for some purposes, all the members of an equivalence class
  74  * are substitutable for each other.  In particular, in a numeric
  75  * expression equivalent values can be <em>substituted</em> for one
  76  * another without changing the result of the expression, meaning
  77  * changing the equivalence class of the result of the expression.
  78  *
  79  * <p>Notably, the built-in {@code ==} operation on floating-point
  80  * values is <em>not</em> an equivalence relation. Despite not
  81  * defining an equivalence relation, the semantics of the IEEE 754
  82  * {@code ==} operator were deliberately designed to meet other needs
  83  * of numerical computation. There are two exceptions where the
  84  * properties of an equivalence relation are not satisfied by {@code
  85  * ==} on floating-point values:
  86  *
  87  * <ul>
  88  *
  89  * <li>If {@code v1} and {@code v2} are both NaN, then {@code v1
  90  * == v2} has the value {@code false}. Therefore, for two NaN
  91  * arguments the <em>reflexive</em> property of an equivalence
  92  * relation is <em>not</em> satisfied by the {@code ==} operator.
  93  *
  94  * <li>If {@code v1} represents {@code +0.0} while {@code v2}
  95  * represents {@code -0.0}, or vice versa, then {@code v1 == v2} has
  96  * the value {@code true} even though {@code +0.0} and {@code -0.0}
  97  * are distinguishable under various floating-point operations. For
  98  * example, {@code 1.0/+0.0} evaluates to positive infinity while
  99  * {@code 1.0/-0.0} evaluates to <em>negative</em> infinity and
 100  * positive infinity and negative infinity are neither equal to each
 101  * other nor equivalent to each other. Thus, while a signed zero input
 102  * most commonly determines the sign of a zero result, because of
 103  * dividing by zero, {@code +0.0} and {@code -0.0} may not be
 104  * substituted for each other in general. The sign of a zero input
 105  * also has a non-substitutable effect on the result of some math
 106  * library methods.
 107  *
 108  * </ul>
 109  *
 110  * <p>For ordered comparisons using the built-in comparison operators
 111  * ({@code <}, {@code <=}, etc.), NaN values have another anomalous
 112  * situation: a NaN is neither less than, nor greater than, nor equal
 113  * to any value, including itself. This means the <i>trichotomy of
 114  * comparison</i> does <em>not</em> hold.
 115  *
 116  * <p>To provide the appropriate semantics for {@code equals} and
 117  * {@code compareTo} methods, those methods cannot simply be wrappers
 118  * around {@code ==} or ordered comparison operations. Instead, {@link
 119  * Double#equals equals} uses <a href=#repEquivalence> representation
 120  * equivalence</a>, defining NaN arguments to be equal to each other,
 121  * restoring reflexivity, and defining {@code +0.0} to <em>not</em> be
 122  * equal to {@code -0.0}. For comparisons, {@link Double#compareTo
 123  * compareTo} defines a total order where {@code -0.0} is less than
 124  * {@code +0.0} and where a NaN is equal to itself and considered
 125  * greater than positive infinity.
 126  *
 127  * <p>The operational semantics of {@code equals} and {@code
 128  * compareTo} are expressed in terms of {@linkplain #doubleToLongBits
 129  * bit-wise converting} the floating-point values to integral values.
 130  *
 131  * <p>The <em>natural ordering</em> implemented by {@link #compareTo
 132  * compareTo} is {@linkplain Comparable consistent with equals}. That
 133  * is, two objects are reported as equal by {@code equals} if and only
 134  * if {@code compareTo} on those objects returns zero.
 135  *
 136  * <p>The adjusted behaviors defined for {@code equals} and {@code
 137  * compareTo} allow instances of wrapper classes to work properly with
 138  * conventional data structures. For example, defining NaN
 139  * values to be {@code equals} to one another allows NaN to be used as
 140  * an element of a {@link java.util.HashSet HashSet} or as the key of
 141  * a {@link java.util.HashMap HashMap}. Similarly, defining {@code
 142  * compareTo} as a total ordering, including {@code +0.0}, {@code
 143  * -0.0}, and NaN, allows instances of wrapper classes to be used as
 144  * elements of a {@link java.util.SortedSet SortedSet} or as keys of a
 145  * {@link java.util.SortedMap SortedMap}.
 146  *
 147  * <p>Comparing numerical equality to various useful equivalence
 148  * relations that can be defined over floating-point values:
 149  *
 150  * <dl>
 151  * <dt><a id=fpNumericalEq><i>numerical equality</i></a> ({@code ==}
 152  * operator): (<em>Not</em> an equivalence relation)</dt>
 153  * <dd>Two floating-point values represent the same extended real
 154  * number. The extended real numbers are the real numbers augmented
 155  * with positive infinity and negative infinity. Under numerical
 156  * equality, {@code +0.0} and {@code -0.0} are equal since they both
 157  * map to the same real value, 0. A NaN does not map to any real
 158  * number and is not equal to any value, including itself.
 159  * </dd>
 160  *
 161  * <dt><i>bit-wise equivalence</i>:</dt>
 162  * <dd>The bits of the two floating-point values are the same. This
 163  * equivalence relation for {@code double} values {@code a} and {@code
 164  * b} is implemented by the expression
 165  * <br>{@code Double.doubleTo}<code><b>Raw</b></code>{@code LongBits(a) == Double.doubleTo}<code><b>Raw</b></code>{@code LongBits(b)}<br>
 166  * Under this relation, {@code +0.0} and {@code -0.0} are
 167  * distinguished from each other and every bit pattern encoding a NaN
 168  * is distinguished from every other bit pattern encoding a NaN.
 169  * </dd>
 170  *
 171  * <dt><i><a id=repEquivalence>representation equivalence</a></i>:</dt>
 172  * <dd>The two floating-point values represent the same IEEE 754
 173  * <i>datum</i>. In particular, for {@linkplain #isFinite(double)
 174  * finite} values, the sign, {@linkplain Math#getExponent(double)
 175  * exponent}, and significand components of the floating-point values
 176  * are the same. Under this relation:
 177  * <ul>
 178  * <li> {@code +0.0} and {@code -0.0} are distinguished from each other.
 179  * <li> every bit pattern encoding a NaN is considered equivalent to each other
 180  * <li> positive infinity is equivalent to positive infinity; negative
 181  *      infinity is equivalent to negative infinity.
 182  * </ul>
 183  * Expressions implementing this equivalence relation include:
 184  * <ul>
 185  * <li>{@code Double.doubleToLongBits(a) == Double.doubleToLongBits(b)}
 186  * <li>{@code Double.valueOf(a).equals(Double.valueOf(b))}
 187  * <li>{@code Double.compare(a, b) == 0}
 188  * </ul>
 189  * Note that representation equivalence is often an appropriate notion
 190  * of equivalence to test the behavior of {@linkplain StrictMath math
 191  * libraries}.
 192  * </dd>
 193  * </dl>
 194  *
 195  * For two binary floating-point values {@code a} and {@code b}, if
 196  * neither of {@code a} and {@code b} is zero or NaN, then the three
 197  * relations numerical equality, bit-wise equivalence, and
 198  * representation equivalence of {@code a} and {@code b} have the same
 199  * {@code true}/{@code false} value. In other words, for binary
 200  * floating-point values, the three relations only differ if at least
 201  * one argument is zero or NaN.
 202  *
 203  * <h2><a id=decimalToBinaryConversion>Decimal &harr; Binary Conversion Issues</a></h2>
 204  *
 205  * Many surprising results of binary floating-point arithmetic trace
 206  * back to aspects of decimal to binary conversion and binary to
 207  * decimal conversion. While integer values can be exactly represented
 208  * in any base, which fractional values can be exactly represented in
 209  * a base is a function of the base. For example, in base 10, 1/3 is a
 210  * repeating fraction (0.33333....); but in base 3, 1/3 is exactly
 211  * 0.1<sub>(3)</sub>, that is 1&nbsp;&times;&nbsp;3<sup>-1</sup>.
 212  * Similarly, in base 10, 1/10 is exactly representable as 0.1
 213  * (1&nbsp;&times;&nbsp;10<sup>-1</sup>), but in base 2, it is a
 214  * repeating fraction (0.0001100110011...<sub>(2)</sub>).
 215  *
 216  * <p>Values of the {@code float} type have {@value Float#PRECISION}
 217  * bits of precision and values of the {@code double} type have
 218  * {@value Double#PRECISION} bits of precision. Therefore, since 0.1
 219  * is a repeating fraction in base 2 with a four-bit repeat, {@code
 220  * 0.1f} != {@code 0.1d}. In more detail, including hexadecimal
 221  * floating-point literals:
 222  *
 223  * <ul>
 224  * <li>The exact numerical value of {@code 0.1f} ({@code 0x1.99999a0000000p-4f}) is
 225  *     0.100000001490116119384765625.
 226  * <li>The exact numerical value of {@code 0.1d} ({@code 0x1.999999999999ap-4d}) is
 227  *     0.1000000000000000055511151231257827021181583404541015625.
 228  * </ul>
 229  *
 230  * These are the closest {@code float} and {@code double} values,
 231  * respectively, to the numerical value of 0.1.  These results are
 232  * consistent with a {@code float} value having the equivalent of 6 to
 233  * 9 digits of decimal precision and a {@code double} value having the
 234  * equivalent of 15 to 17 digits of decimal precision. (The
 235  * equivalent precision varies according to the different relative
 236  * densities of binary and decimal values at different points along the
 237  * real number line.)
 238  *
 239  * <p>This representation hazard of decimal fractions is one reason to
 240  * use caution when storing monetary values as {@code float} or {@code
 241  * double}. Alternatives include:
 242  * <ul>
 243  * <li>using {@link java.math.BigDecimal BigDecimal} to store decimal
 244  * fractional values exactly
 245  *
 246  * <li>scaling up so the monetary value is an integer &mdash; for
 247  * example, multiplying by 100 if the value is denominated in cents or
 248  * multiplying by 1000 if the value is denominated in mills &mdash;
 249  * and then storing that scaled value in an integer type
 250  *
 251  *</ul>
 252  *
 253  * <p>For each finite floating-point value and a given floating-point
 254  * type, there is a contiguous region of the real number line which
 255  * maps to that value. Under the default round to nearest rounding
 256  * policy (JLS {@jls 15.4}), this contiguous region for a value is
 257  * typically one {@linkplain Math#ulp ulp} (unit in the last place)
 258  * wide and centered around the exactly representable value. (At
 259  * exponent boundaries, the region is asymmetrical and larger on the
 260  * side with the larger exponent.) For example, for {@code 0.1f}, the
 261  * region can be computed as follows:
 262  *
 263  * <br>// Numeric values listed are exact values
 264  * <br>oneTenthApproxAsFloat = 0.100000001490116119384765625;
 265  * <br>ulpOfoneTenthApproxAsFloat = Math.ulp(0.1f) = 7.450580596923828125E-9;
 266  * <br>// Numeric range that is converted to the float closest to 0.1, _excludes_ endpoints
 267  * <br>(oneTenthApproxAsFloat - &frac12;ulpOfoneTenthApproxAsFloat, oneTenthApproxAsFloat + &frac12;ulpOfoneTenthApproxAsFloat) =
 268  * <br>(0.0999999977648258209228515625, 0.1000000052154064178466796875)
 269  *
 270  * <p>In particular, a correctly rounded decimal to binary conversion
 271  * of any string representing a number in this range, say by {@link
 272  * Float#parseFloat(String)}, will be converted to the same value:
 273  *
 274  * {@snippet lang="java" :
 275  * Float.parseFloat("0.0999999977648258209228515625000001"); // rounds up to oneTenthApproxAsFloat
 276  * Float.parseFloat("0.099999998");                          // rounds up to oneTenthApproxAsFloat
 277  * Float.parseFloat("0.1");                                  // rounds up to oneTenthApproxAsFloat
 278  * Float.parseFloat("0.100000001490116119384765625");        // exact conversion
 279  * Float.parseFloat("0.100000005215406417846679687");        // rounds down to oneTenthApproxAsFloat
 280  * Float.parseFloat("0.100000005215406417846679687499999");  // rounds down to oneTenthApproxAsFloat
 281  * }
 282  *
 283  * <p>Similarly, an analogous range can be constructed  for the {@code
 284  * double} type based on the exact value of {@code double}
 285  * approximation to {@code 0.1d} and the numerical value of {@code
 286  * Math.ulp(0.1d)} and likewise for other particular numerical values
 287  * in the {@code float} and {@code double} types.
 288  *
 289  * <p>As seen in the above conversions, compared to the exact
 290  * numerical value the operation would have without rounding, the same
 291  * floating-point value as a result can be:
 292  * <ul>
 293  * <li>greater than the exact result
 294  * <li>equal to the exact result
 295  * <li>less than the exact result
 296  * </ul>
 297  *
 298  * A floating-point value doesn't "know" whether it was the result of
 299  * rounding up, or rounding down, or an exact operation; it contains
 300  * no history of how it was computed. Consequently, the sum of
 301  * {@snippet lang="java" :
 302  * 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f;
 303  * // Numerical value of computed sum: 1.00000011920928955078125,
 304  * // the next floating-point value larger than 1.0f, equal to Math.nextUp(1.0f).
 305  * }
 306  * or
 307  * {@snippet lang="java" :
 308  * 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d;
 309  * // Numerical value of computed sum: 0.99999999999999988897769753748434595763683319091796875,
 310  * // the next floating-point value smaller than 1.0d, equal to Math.nextDown(1.0d).
 311  * }
 312  *
 313  * should <em>not</em> be expected to be exactly equal to 1.0, but
 314  * only to be close to 1.0. Consequently, the following code is an
 315  * infinite loop:
 316  *
 317  * {@snippet lang="java" :
 318  * double d = 0.0;
 319  * while (d != 1.0) { // Surprising infinite loop
 320  *   d += 0.1; // Sum never _exactly_ equals 1.0
 321  * }
 322  * }
 323  *
 324  * Instead, use an integer loop count for counted loops:
 325  *
 326  * {@snippet lang="java" :
 327  * double d = 0.0;
 328  * for (int i = 0; i < 10; i++) {
 329  *   d += 0.1;
 330  * } // Value of d is equal to Math.nextDown(1.0).
 331  * }
 332  *
 333  * or test against a floating-point limit using ordered comparisons
 334  * ({@code <}, {@code <=}, {@code >}, {@code >=}):
 335  *
 336  * {@snippet lang="java" :
 337  *  double d = 0.0;
 338  *  while (d <= 1.0) {
 339  *    d += 0.1;
 340  *  } // Value of d approximately 1.0999999999999999
 341  *  }
 342  *
 343  * While floating-point arithmetic may have surprising results, IEEE
 344  * 754 floating-point arithmetic follows a principled design and its
 345  * behavior is predictable on the Java platform.
 346  *
 347  * @jls 4.2.3 Floating-Point Types, Formats, and Values
 348  * @jls 4.2.4. Floating-Point Operations
 349  * @jls 15.21.1 Numerical Equality Operators == and !=
 350  * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
 351  *
 352  * @see <a href="https://standards.ieee.org/ieee/754/6210/">
 353  *      <cite>IEEE Standard for Floating-Point Arithmetic</cite></a>
 354  *
 355  * @author  Lee Boynton
 356  * @author  Arthur van Hoff
 357  * @author  Joseph D. Darcy
 358  * @since 1.0
 359  */
 360 @jdk.internal.MigratedValueClass
 361 @jdk.internal.ValueBased
 362 public final class Double extends Number
 363         implements Comparable<Double>, Constable, ConstantDesc {
 364     /**
 365      * A constant holding the positive infinity of type
 366      * {@code double}. It is equal to the value returned by
 367      * {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
 368      */
 369     public static final double POSITIVE_INFINITY = 1.0 / 0.0;
 370 
 371     /**
 372      * A constant holding the negative infinity of type
 373      * {@code double}. It is equal to the value returned by
 374      * {@code Double.longBitsToDouble(0xfff0000000000000L)}.
 375      */
 376     public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
 377 
 378     /**
 379      * A constant holding a Not-a-Number (NaN) value of type
 380      * {@code double}. It is equivalent to the value returned by
 381      * {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
 382      */
 383     public static final double NaN = 0.0d / 0.0;
 384 
 385     /**
 386      * A constant holding the largest positive finite value of type
 387      * {@code double},
 388      * (2-2<sup>-52</sup>)&middot;2<sup>1023</sup>.  It is equal to
 389      * the hexadecimal floating-point literal
 390      * {@code 0x1.fffffffffffffP+1023} and also equal to
 391      * {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
 392      */
 393     public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308
 394 
 395     /**
 396      * A constant holding the smallest positive normal value of type
 397      * {@code double}, 2<sup>-1022</sup>.  It is equal to the
 398      * hexadecimal floating-point literal {@code 0x1.0p-1022} and also
 399      * equal to {@code Double.longBitsToDouble(0x0010000000000000L)}.
 400      *
 401      * @since 1.6
 402      */
 403     public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308
 404 
 405     /**
 406      * A constant holding the smallest positive nonzero value of type
 407      * {@code double}, 2<sup>-1074</sup>. It is equal to the
 408      * hexadecimal floating-point literal
 409      * {@code 0x0.0000000000001P-1022} and also equal to
 410      * {@code Double.longBitsToDouble(0x1L)}.
 411      */
 412     public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324
 413 
 414     /**
 415      * The number of bits used to represent a {@code double} value.
 416      *
 417      * @since 1.5
 418      */
 419     public static final int SIZE = 64;
 420 
 421     /**
 422      * The number of bits in the significand of a {@code double} value.
 423      * This is the parameter N in section {@jls 4.2.3} of
 424      * <cite>The Java Language Specification</cite>.
 425      *
 426      * @since 19
 427      */
 428     public static final int PRECISION = 53;
 429 
 430     /**
 431      * Maximum exponent a finite {@code double} variable may have.
 432      * It is equal to the value returned by
 433      * {@code Math.getExponent(Double.MAX_VALUE)}.
 434      *
 435      * @since 1.6
 436      */
 437     public static final int MAX_EXPONENT = (1 << (SIZE - PRECISION - 1)) - 1; // 1023
 438 
 439     /**
 440      * Minimum exponent a normalized {@code double} variable may
 441      * have.  It is equal to the value returned by
 442      * {@code Math.getExponent(Double.MIN_NORMAL)}.
 443      *
 444      * @since 1.6
 445      */
 446     public static final int MIN_EXPONENT = 1 - MAX_EXPONENT; // -1022
 447 
 448     /**
 449      * The number of bytes used to represent a {@code double} value.
 450      *
 451      * @since 1.8
 452      */
 453     public static final int BYTES = SIZE / Byte.SIZE;
 454 
 455     /**
 456      * The {@code Class} instance representing the primitive type
 457      * {@code double}.
 458      *
 459      * @since 1.1
 460      */
 461     @SuppressWarnings("unchecked")
 462     public static final Class<Double>   TYPE = (Class<Double>) Class.getPrimitiveClass("double");
 463 
 464     /**
 465      * Returns a string representation of the {@code double}
 466      * argument. All characters mentioned below are ASCII characters.
 467      * <ul>
 468      * <li>If the argument is NaN, the result is the string
 469      *     "{@code NaN}".
 470      * <li>Otherwise, the result is a string that represents the sign and
 471      * magnitude (absolute value) of the argument. If the sign is negative,
 472      * the first character of the result is '{@code -}'
 473      * ({@code '\u005Cu002D'}); if the sign is positive, no sign character
 474      * appears in the result. As for the magnitude <i>m</i>:
 475      * <ul>
 476      * <li>If <i>m</i> is infinity, it is represented by the characters
 477      * {@code "Infinity"}; thus, positive infinity produces the result
 478      * {@code "Infinity"} and negative infinity produces the result
 479      * {@code "-Infinity"}.
 480      *
 481      * <li>If <i>m</i> is zero, it is represented by the characters
 482      * {@code "0.0"}; thus, negative zero produces the result
 483      * {@code "-0.0"} and positive zero produces the result
 484      * {@code "0.0"}.
 485      *
 486      * <li> Otherwise <i>m</i> is positive and finite.
 487      * It is converted to a string in two stages:
 488      * <ul>
 489      * <li> <em>Selection of a decimal</em>:
 490      * A well-defined decimal <i>d</i><sub><i>m</i></sub>
 491      * is selected to represent <i>m</i>.
 492      * This decimal is (almost always) the <em>shortest</em> one that
 493      * rounds to <i>m</i> according to the round to nearest
 494      * rounding policy of IEEE 754 floating-point arithmetic.
 495      * <li> <em>Formatting as a string</em>:
 496      * The decimal <i>d</i><sub><i>m</i></sub> is formatted as a string,
 497      * either in plain or in computerized scientific notation,
 498      * depending on its value.
 499      * </ul>
 500      * </ul>
 501      * </ul>
 502      *
 503      * <p>A <em>decimal</em> is a number of the form
 504      * <i>s</i>&times;10<sup><i>i</i></sup>
 505      * for some (unique) integers <i>s</i> &gt; 0 and <i>i</i> such that
 506      * <i>s</i> is not a multiple of 10.
 507      * These integers are the <em>significand</em> and
 508      * the <em>exponent</em>, respectively, of the decimal.
 509      * The <em>length</em> of the decimal is the (unique)
 510      * positive integer <i>n</i> meeting
 511      * 10<sup><i>n</i>-1</sup> &le; <i>s</i> &lt; 10<sup><i>n</i></sup>.
 512      *
 513      * <p>The decimal <i>d</i><sub><i>m</i></sub> for a finite positive <i>m</i>
 514      * is defined as follows:
 515      * <ul>
 516      * <li>Let <i>R</i> be the set of all decimals that round to <i>m</i>
 517      * according to the usual <em>round to nearest</em> rounding policy of
 518      * IEEE 754 floating-point arithmetic.
 519      * <li>Let <i>p</i> be the minimal length over all decimals in <i>R</i>.
 520      * <li>When <i>p</i> &ge; 2, let <i>T</i> be the set of all decimals
 521      * in <i>R</i> with length <i>p</i>.
 522      * Otherwise, let <i>T</i> be the set of all decimals
 523      * in <i>R</i> with length 1 or 2.
 524      * <li>Define <i>d</i><sub><i>m</i></sub> as the decimal in <i>T</i>
 525      * that is closest to <i>m</i>.
 526      * Or if there are two such decimals in <i>T</i>,
 527      * select the one with the even significand.
 528      * </ul>
 529      *
 530      * <p>The (uniquely) selected decimal <i>d</i><sub><i>m</i></sub>
 531      * is then formatted.
 532      * Let <i>s</i>, <i>i</i> and <i>n</i> be the significand, exponent and
 533      * length of <i>d</i><sub><i>m</i></sub>, respectively.
 534      * Further, let <i>e</i> = <i>n</i> + <i>i</i> - 1 and let
 535      * <i>s</i><sub>1</sub>&hellip;<i>s</i><sub><i>n</i></sub>
 536      * be the usual decimal expansion of <i>s</i>.
 537      * Note that <i>s</i><sub>1</sub> &ne; 0
 538      * and <i>s</i><sub><i>n</i></sub> &ne; 0.
 539      * Below, the decimal point {@code '.'} is {@code '\u005Cu002E'}
 540      * and the exponent indicator {@code 'E'} is {@code '\u005Cu0045'}.
 541      * <ul>
 542      * <li>Case -3 &le; <i>e</i> &lt; 0:
 543      * <i>d</i><sub><i>m</i></sub> is formatted as
 544      * <code>0.0</code>&hellip;<code>0</code><!--
 545      * --><i>s</i><sub>1</sub>&hellip;<i>s</i><sub><i>n</i></sub>,
 546      * where there are exactly -(<i>n</i> + <i>i</i>) zeroes between
 547      * the decimal point and <i>s</i><sub>1</sub>.
 548      * For example, 123 &times; 10<sup>-4</sup> is formatted as
 549      * {@code 0.0123}.
 550      * <li>Case 0 &le; <i>e</i> &lt; 7:
 551      * <ul>
 552      * <li>Subcase <i>i</i> &ge; 0:
 553      * <i>d</i><sub><i>m</i></sub> is formatted as
 554      * <i>s</i><sub>1</sub>&hellip;<i>s</i><sub><i>n</i></sub><!--
 555      * --><code>0</code>&hellip;<code>0.0</code>,
 556      * where there are exactly <i>i</i> zeroes
 557      * between <i>s</i><sub><i>n</i></sub> and the decimal point.
 558      * For example, 123 &times; 10<sup>2</sup> is formatted as
 559      * {@code 12300.0}.
 560      * <li>Subcase <i>i</i> &lt; 0:
 561      * <i>d</i><sub><i>m</i></sub> is formatted as
 562      * <i>s</i><sub>1</sub>&hellip;<!--
 563      * --><i>s</i><sub><i>n</i>+<i>i</i></sub><code>.</code><!--
 564      * --><i>s</i><sub><i>n</i>+<i>i</i>+1</sub>&hellip;<!--
 565      * --><i>s</i><sub><i>n</i></sub>,
 566      * where there are exactly -<i>i</i> digits to the right of
 567      * the decimal point.
 568      * For example, 123 &times; 10<sup>-1</sup> is formatted as
 569      * {@code 12.3}.
 570      * </ul>
 571      * <li>Case <i>e</i> &lt; -3 or <i>e</i> &ge; 7:
 572      * computerized scientific notation is used to format
 573      * <i>d</i><sub><i>m</i></sub>.
 574      * Here <i>e</i> is formatted as by {@link Integer#toString(int)}.
 575      * <ul>
 576      * <li>Subcase <i>n</i> = 1:
 577      * <i>d</i><sub><i>m</i></sub> is formatted as
 578      * <i>s</i><sub>1</sub><code>.0E</code><i>e</i>.
 579      * For example, 1 &times; 10<sup>23</sup> is formatted as
 580      * {@code 1.0E23}.
 581      * <li>Subcase <i>n</i> &gt; 1:
 582      * <i>d</i><sub><i>m</i></sub> is formatted as
 583      * <i>s</i><sub>1</sub><code>.</code><i>s</i><sub>2</sub><!--
 584      * -->&hellip;<i>s</i><sub><i>n</i></sub><code>E</code><i>e</i>.
 585      * For example, 123 &times; 10<sup>-21</sup> is formatted as
 586      * {@code 1.23E-19}.
 587      * </ul>
 588      * </ul>
 589      *
 590      * <p>To create localized string representations of a floating-point
 591      * value, use subclasses of {@link java.text.NumberFormat}.
 592      *
 593      * @param   d   the {@code double} to be converted.
 594      * @return a string representation of the argument.
 595      */
 596     public static String toString(double d) {
 597         return DoubleToDecimal.toString(d);
 598     }
 599 
 600     /**
 601      * Returns a hexadecimal string representation of the
 602      * {@code double} argument. All characters mentioned below
 603      * are ASCII characters.
 604      *
 605      * <ul>
 606      * <li>If the argument is NaN, the result is the string
 607      *     "{@code NaN}".
 608      * <li>Otherwise, the result is a string that represents the sign
 609      * and magnitude of the argument. If the sign is negative, the
 610      * first character of the result is '{@code -}'
 611      * ({@code '\u005Cu002D'}); if the sign is positive, no sign
 612      * character appears in the result. As for the magnitude <i>m</i>:
 613      *
 614      * <ul>
 615      * <li>If <i>m</i> is infinity, it is represented by the string
 616      * {@code "Infinity"}; thus, positive infinity produces the
 617      * result {@code "Infinity"} and negative infinity produces
 618      * the result {@code "-Infinity"}.
 619      *
 620      * <li>If <i>m</i> is zero, it is represented by the string
 621      * {@code "0x0.0p0"}; thus, negative zero produces the result
 622      * {@code "-0x0.0p0"} and positive zero produces the result
 623      * {@code "0x0.0p0"}.
 624      *
 625      * <li>If <i>m</i> is a {@code double} value with a
 626      * normalized representation, substrings are used to represent the
 627      * significand and exponent fields.  The significand is
 628      * represented by the characters {@code "0x1."}
 629      * followed by a lowercase hexadecimal representation of the rest
 630      * of the significand as a fraction.  Trailing zeros in the
 631      * hexadecimal representation are removed unless all the digits
 632      * are zero, in which case a single zero is used. Next, the
 633      * exponent is represented by {@code "p"} followed
 634      * by a decimal string of the unbiased exponent as if produced by
 635      * a call to {@link Integer#toString(int) Integer.toString} on the
 636      * exponent value.
 637      *
 638      * <li>If <i>m</i> is a {@code double} value with a subnormal
 639      * representation, the significand is represented by the
 640      * characters {@code "0x0."} followed by a
 641      * hexadecimal representation of the rest of the significand as a
 642      * fraction.  Trailing zeros in the hexadecimal representation are
 643      * removed. Next, the exponent is represented by
 644      * {@code "p-1022"}.  Note that there must be at
 645      * least one nonzero digit in a subnormal significand.
 646      *
 647      * </ul>
 648      *
 649      * </ul>
 650      *
 651      * <table class="striped">
 652      * <caption>Examples</caption>
 653      * <thead>
 654      * <tr><th scope="col">Floating-point Value</th><th scope="col">Hexadecimal String</th>
 655      * </thead>
 656      * <tbody style="text-align:right">
 657      * <tr><th scope="row">{@code 1.0}</th> <td>{@code 0x1.0p0}</td>
 658      * <tr><th scope="row">{@code -1.0}</th>        <td>{@code -0x1.0p0}</td>
 659      * <tr><th scope="row">{@code 2.0}</th> <td>{@code 0x1.0p1}</td>
 660      * <tr><th scope="row">{@code 3.0}</th> <td>{@code 0x1.8p1}</td>
 661      * <tr><th scope="row">{@code 0.5}</th> <td>{@code 0x1.0p-1}</td>
 662      * <tr><th scope="row">{@code 0.25}</th>        <td>{@code 0x1.0p-2}</td>
 663      * <tr><th scope="row">{@code Double.MAX_VALUE}</th>
 664      *     <td>{@code 0x1.fffffffffffffp1023}</td>
 665      * <tr><th scope="row">{@code Minimum Normal Value}</th>
 666      *     <td>{@code 0x1.0p-1022}</td>
 667      * <tr><th scope="row">{@code Maximum Subnormal Value}</th>
 668      *     <td>{@code 0x0.fffffffffffffp-1022}</td>
 669      * <tr><th scope="row">{@code Double.MIN_VALUE}</th>
 670      *     <td>{@code 0x0.0000000000001p-1022}</td>
 671      * </tbody>
 672      * </table>
 673      * @param   d   the {@code double} to be converted.
 674      * @return a hex string representation of the argument.
 675      * @since 1.5
 676      * @author Joseph D. Darcy
 677      */
 678     public static String toHexString(double d) {
 679         /*
 680          * Modeled after the "a" conversion specifier in C99, section
 681          * 7.19.6.1; however, the output of this method is more
 682          * tightly specified.
 683          */
 684         if (!isFinite(d) )
 685             // For infinity and NaN, use the decimal output.
 686             return Double.toString(d);
 687         else {
 688             // Initialized to maximum size of output.
 689             StringBuilder answer = new StringBuilder(24);
 690 
 691             if (Math.copySign(1.0, d) == -1.0)    // value is negative,
 692                 answer.append("-");                  // so append sign info
 693 
 694             answer.append("0x");
 695 
 696             d = Math.abs(d);
 697 
 698             if(d == 0.0) {
 699                 answer.append("0.0p0");
 700             } else {
 701                 boolean subnormal = (d < Double.MIN_NORMAL);
 702 
 703                 // Isolate significand bits and OR in a high-order bit
 704                 // so that the string representation has a known
 705                 // length.
 706                 long signifBits = (Double.doubleToLongBits(d)
 707                                    & DoubleConsts.SIGNIF_BIT_MASK) |
 708                     0x1000000000000000L;
 709 
 710                 // Subnormal values have a 0 implicit bit; normal
 711                 // values have a 1 implicit bit.
 712                 answer.append(subnormal ? "0." : "1.");
 713 
 714                 // Isolate the low-order 13 digits of the hex
 715                 // representation.  If all the digits are zero,
 716                 // replace with a single 0; otherwise, remove all
 717                 // trailing zeros.
 718                 String signif = Long.toHexString(signifBits).substring(3,16);
 719                 answer.append(signif.equals("0000000000000") ? // 13 zeros
 720                               "0":
 721                               signif.replaceFirst("0{1,12}$", ""));
 722 
 723                 answer.append('p');
 724                 // If the value is subnormal, use the E_min exponent
 725                 // value for double; otherwise, extract and report d's
 726                 // exponent (the representation of a subnormal uses
 727                 // E_min -1).
 728                 answer.append(subnormal ?
 729                               Double.MIN_EXPONENT:
 730                               Math.getExponent(d));
 731             }
 732             return answer.toString();
 733         }
 734     }
 735 
 736     /**
 737      * Returns a {@code Double} object holding the
 738      * {@code double} value represented by the argument string
 739      * {@code s}.
 740      *
 741      * <p>If {@code s} is {@code null}, then a
 742      * {@code NullPointerException} is thrown.
 743      *
 744      * <p>Leading and trailing whitespace characters in {@code s}
 745      * are ignored.  Whitespace is removed as if by the {@link
 746      * String#trim} method; that is, both ASCII space and control
 747      * characters are removed. The rest of {@code s} should
 748      * constitute a <i>FloatValue</i> as described by the lexical
 749      * syntax rules:
 750      *
 751      * <blockquote>
 752      * <dl>
 753      * <dt><i>FloatValue:</i>
 754      * <dd><i>Sign<sub>opt</sub></i> {@code NaN}
 755      * <dd><i>Sign<sub>opt</sub></i> {@code Infinity}
 756      * <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i>
 757      * <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i>
 758      * <dd><i>SignedInteger</i>
 759      * </dl>
 760      *
 761      * <dl>
 762      * <dt><i>HexFloatingPointLiteral</i>:
 763      * <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i>
 764      * </dl>
 765      *
 766      * <dl>
 767      * <dt><i>HexSignificand:</i>
 768      * <dd><i>HexNumeral</i>
 769      * <dd><i>HexNumeral</i> {@code .}
 770      * <dd>{@code 0x} <i>HexDigits<sub>opt</sub>
 771      *     </i>{@code .}<i> HexDigits</i>
 772      * <dd>{@code 0X}<i> HexDigits<sub>opt</sub>
 773      *     </i>{@code .} <i>HexDigits</i>
 774      * </dl>
 775      *
 776      * <dl>
 777      * <dt><i>BinaryExponent:</i>
 778      * <dd><i>BinaryExponentIndicator SignedInteger</i>
 779      * </dl>
 780      *
 781      * <dl>
 782      * <dt><i>BinaryExponentIndicator:</i>
 783      * <dd>{@code p}
 784      * <dd>{@code P}
 785      * </dl>
 786      *
 787      * </blockquote>
 788      *
 789      * where <i>Sign</i>, <i>FloatingPointLiteral</i>,
 790      * <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and
 791      * <i>FloatTypeSuffix</i> are as defined in the lexical structure
 792      * sections of
 793      * <cite>The Java Language Specification</cite>,
 794      * except that underscores are not accepted between digits.
 795      * If {@code s} does not have the form of
 796      * a <i>FloatValue</i>, then a {@code NumberFormatException}
 797      * is thrown. Otherwise, {@code s} is regarded as
 798      * representing an exact decimal value in the usual
 799      * "computerized scientific notation" or as an exact
 800      * hexadecimal value; this exact numerical value is then
 801      * conceptually converted to an "infinitely precise"
 802      * binary value that is then rounded to type {@code double}
 803      * by the usual round-to-nearest rule of IEEE 754 floating-point
 804      * arithmetic, which includes preserving the sign of a zero
 805      * value.
 806      *
 807      * Note that the round-to-nearest rule also implies overflow and
 808      * underflow behaviour; if the exact value of {@code s} is large
 809      * enough in magnitude (greater than or equal to ({@link
 810      * #MAX_VALUE} + {@link Math#ulp(double) ulp(MAX_VALUE)}/2),
 811      * rounding to {@code double} will result in an infinity and if the
 812      * exact value of {@code s} is small enough in magnitude (less
 813      * than or equal to {@link #MIN_VALUE}/2), rounding to float will
 814      * result in a zero.
 815      *
 816      * Finally, after rounding a {@code Double} object representing
 817      * this {@code double} value is returned.
 818      *
 819      * <p>Note that trailing format specifiers, specifiers that
 820      * determine the type of a floating-point literal
 821      * ({@code 1.0f} is a {@code float} value;
 822      * {@code 1.0d} is a {@code double} value), do
 823      * <em>not</em> influence the results of this method.  In other
 824      * words, the numerical value of the input string is converted
 825      * directly to the target floating-point type.  The two-step
 826      * sequence of conversions, string to {@code float} followed
 827      * by {@code float} to {@code double}, is <em>not</em>
 828      * equivalent to converting a string directly to
 829      * {@code double}. For example, the {@code float}
 830      * literal {@code 0.1f} is equal to the {@code double}
 831      * value {@code 0.10000000149011612}; the {@code float}
 832      * literal {@code 0.1f} represents a different numerical
 833      * value than the {@code double} literal
 834      * {@code 0.1}. (The numerical value 0.1 cannot be exactly
 835      * represented in a binary floating-point number.)
 836      *
 837      * <p>To avoid calling this method on an invalid string and having
 838      * a {@code NumberFormatException} be thrown, the regular
 839      * expression below can be used to screen the input string:
 840      *
 841      * {@snippet lang="java" :
 842      *  final String Digits     = "(\\p{Digit}+)";
 843      *  final String HexDigits  = "(\\p{XDigit}+)";
 844      *  // an exponent is 'e' or 'E' followed by an optionally
 845      *  // signed decimal integer.
 846      *  final String Exp        = "[eE][+-]?"+Digits;
 847      *  final String fpRegex    =
 848      *      ("[\\x00-\\x20]*"+  // Optional leading "whitespace"
 849      *       "[+-]?(" + // Optional sign character
 850      *       "NaN|" +           // "NaN" string
 851      *       "Infinity|" +      // "Infinity" string
 852      *
 853      *       // A decimal floating-point string representing a finite positive
 854      *       // number without a leading sign has at most five basic pieces:
 855      *       // Digits . Digits ExponentPart FloatTypeSuffix
 856      *       //
 857      *       // Since this method allows integer-only strings as input
 858      *       // in addition to strings of floating-point literals, the
 859      *       // two sub-patterns below are simplifications of the grammar
 860      *       // productions from section 3.10.2 of
 861      *       // The Java Language Specification.
 862      *
 863      *       // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
 864      *       "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
 865      *
 866      *       // . Digits ExponentPart_opt FloatTypeSuffix_opt
 867      *       "(\\.("+Digits+")("+Exp+")?)|"+
 868      *
 869      *       // Hexadecimal strings
 870      *       "((" +
 871      *        // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
 872      *        "(0[xX]" + HexDigits + "(\\.)?)|" +
 873      *
 874      *        // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
 875      *        "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
 876      *
 877      *        ")[pP][+-]?" + Digits + "))" +
 878      *       "[fFdD]?))" +
 879      *       "[\\x00-\\x20]*");// Optional trailing "whitespace"
 880      *  // @link region substring="Pattern.matches" target ="java.util.regex.Pattern#matches"
 881      *  if (Pattern.matches(fpRegex, myString))
 882      *      Double.valueOf(myString); // Will not throw NumberFormatException
 883      * // @end
 884      *  else {
 885      *      // Perform suitable alternative action
 886      *  }
 887      * }
 888      *
 889      * @apiNote To interpret localized string representations of a
 890      * floating-point value, or string representations that have
 891      * non-ASCII digits, use {@link java.text.NumberFormat}. For
 892      * example,
 893      * {@snippet lang="java" :
 894      *     NumberFormat.getInstance(l).parse(s).doubleValue();
 895      * }
 896      * where {@code l} is the desired locale, or
 897      * {@link java.util.Locale#ROOT} if locale insensitive.
 898      *
 899      * @param      s   the string to be parsed.
 900      * @return     a {@code Double} object holding the value
 901      *             represented by the {@code String} argument.
 902      * @throws     NumberFormatException  if the string does not contain a
 903      *             parsable number.
 904      * @see Double##decimalToBinaryConversion Decimal &harr; Binary Conversion Issues
 905      */
 906     public static Double valueOf(String s) throws NumberFormatException {
 907         return new Double(parseDouble(s));
 908     }
 909 
 910     /**
 911      * Returns a {@code Double} instance representing the specified
 912      * {@code double} value.
 913      * If a new {@code Double} instance is not required, this method
 914      * should generally be used in preference to the constructor
 915      * {@link #Double(double)}, as this method is likely to yield
 916      * significantly better space and time performance by caching
 917      * frequently requested values.
 918      *
 919      * @param  d a double value.
 920      * @return a {@code Double} instance representing {@code d}.
 921      * @since  1.5
 922      */
 923     @IntrinsicCandidate
 924     public static Double valueOf(double d) {
 925         return new Double(d);
 926     }
 927 
 928     /**
 929      * Returns a new {@code double} initialized to the value
 930      * represented by the specified {@code String}, as performed
 931      * by the {@code valueOf} method of class
 932      * {@code Double}.
 933      *
 934      * @param  s   the string to be parsed.
 935      * @return the {@code double} value represented by the string
 936      *         argument.
 937      * @throws NullPointerException  if the string is null
 938      * @throws NumberFormatException if the string does not contain
 939      *         a parsable {@code double}.
 940      * @see    java.lang.Double#valueOf(String)
 941      * @see    Double##decimalToBinaryConversion Decimal &harr; Binary Conversion Issues
 942      * @since 1.2
 943      */
 944     public static double parseDouble(String s) throws NumberFormatException {
 945         return FloatingDecimal.parseDouble(s);
 946     }
 947 
 948     /**
 949      * Returns {@code true} if the specified number is a
 950      * Not-a-Number (NaN) value, {@code false} otherwise.
 951      *
 952      * @apiNote
 953      * This method corresponds to the isNaN operation defined in IEEE
 954      * 754.
 955      *
 956      * @param   v   the value to be tested.
 957      * @return  {@code true} if the value of the argument is NaN;
 958      *          {@code false} otherwise.
 959      */
 960     public static boolean isNaN(double v) {
 961         return (v != v);
 962     }
 963 
 964     /**
 965      * Returns {@code true} if the specified number is infinitely
 966      * large in magnitude, {@code false} otherwise.
 967      *
 968      * @apiNote
 969      * This method corresponds to the isInfinite operation defined in
 970      * IEEE 754.
 971      *
 972      * @param   v   the value to be tested.
 973      * @return  {@code true} if the value of the argument is positive
 974      *          infinity or negative infinity; {@code false} otherwise.
 975      */
 976     @IntrinsicCandidate
 977     public static boolean isInfinite(double v) {
 978         return Math.abs(v) > MAX_VALUE;
 979     }
 980 
 981     /**
 982      * Returns {@code true} if the argument is a finite floating-point
 983      * value; returns {@code false} otherwise (for NaN and infinity
 984      * arguments).
 985      *
 986      * @apiNote
 987      * This method corresponds to the isFinite operation defined in
 988      * IEEE 754.
 989      *
 990      * @param d the {@code double} value to be tested
 991      * @return {@code true} if the argument is a finite
 992      * floating-point value, {@code false} otherwise.
 993      * @since 1.8
 994      */
 995     @IntrinsicCandidate
 996     public static boolean isFinite(double d) {
 997         return Math.abs(d) <= Double.MAX_VALUE;
 998     }
 999 
1000     /**
1001      * The value of the Double.
1002      *
1003      * @serial
1004      */
1005     private final double value;
1006 
1007     /**
1008      * Constructs a newly allocated {@code Double} object that
1009      * represents the primitive {@code double} argument.
1010      *
1011      * @param   value   the value to be represented by the {@code Double}.
1012      *
1013      * @deprecated
1014      * It is rarely appropriate to use this constructor. The static factory
1015      * {@link #valueOf(double)} is generally a better choice, as it is
1016      * likely to yield significantly better space and time performance.
1017      */
1018     @Deprecated(since="9", forRemoval = true)
1019     public Double(double value) {
1020         this.value = value;
1021     }
1022 
1023     /**
1024      * Constructs a newly allocated {@code Double} object that
1025      * represents the floating-point value of type {@code double}
1026      * represented by the string. The string is converted to a
1027      * {@code double} value as if by the {@code valueOf} method.
1028      *
1029      * @param  s  a string to be converted to a {@code Double}.
1030      * @throws    NumberFormatException if the string does not contain a
1031      *            parsable number.
1032      *
1033      * @deprecated
1034      * It is rarely appropriate to use this constructor.
1035      * Use {@link #parseDouble(String)} to convert a string to a
1036      * {@code double} primitive, or use {@link #valueOf(String)}
1037      * to convert a string to a {@code Double} object.
1038      */
1039     @Deprecated(since="9", forRemoval = true)
1040     public Double(String s) throws NumberFormatException {
1041         value = parseDouble(s);
1042     }
1043 
1044     /**
1045      * Returns {@code true} if this {@code Double} value is
1046      * a Not-a-Number (NaN), {@code false} otherwise.
1047      *
1048      * @return  {@code true} if the value represented by this object is
1049      *          NaN; {@code false} otherwise.
1050      */
1051     public boolean isNaN() {
1052         return isNaN(value);
1053     }
1054 
1055     /**
1056      * Returns {@code true} if this {@code Double} value is
1057      * infinitely large in magnitude, {@code false} otherwise.
1058      *
1059      * @return  {@code true} if the value represented by this object is
1060      *          positive infinity or negative infinity;
1061      *          {@code false} otherwise.
1062      */
1063     public boolean isInfinite() {
1064         return isInfinite(value);
1065     }
1066 
1067     /**
1068      * Returns a string representation of this {@code Double} object.
1069      * The primitive {@code double} value represented by this
1070      * object is converted to a string exactly as if by the method
1071      * {@code toString} of one argument.
1072      *
1073      * @return  a {@code String} representation of this object.
1074      * @see java.lang.Double#toString(double)
1075      */
1076     public String toString() {
1077         return toString(value);
1078     }
1079 
1080     /**
1081      * Returns the value of this {@code Double} as a {@code byte}
1082      * after a narrowing primitive conversion.
1083      *
1084      * @return  the {@code double} value represented by this object
1085      *          converted to type {@code byte}
1086      * @jls 5.1.3 Narrowing Primitive Conversion
1087      * @since 1.1
1088      */
1089     public byte byteValue() {
1090         return (byte)value;
1091     }
1092 
1093     /**
1094      * Returns the value of this {@code Double} as a {@code short}
1095      * after a narrowing primitive conversion.
1096      *
1097      * @return  the {@code double} value represented by this object
1098      *          converted to type {@code short}
1099      * @jls 5.1.3 Narrowing Primitive Conversion
1100      * @since 1.1
1101      */
1102     public short shortValue() {
1103         return (short)value;
1104     }
1105 
1106     /**
1107      * Returns the value of this {@code Double} as an {@code int}
1108      * after a narrowing primitive conversion.
1109      * @jls 5.1.3 Narrowing Primitive Conversion
1110      *
1111      * @return  the {@code double} value represented by this object
1112      *          converted to type {@code int}
1113      */
1114     public int intValue() {
1115         return (int)value;
1116     }
1117 
1118     /**
1119      * Returns the value of this {@code Double} as a {@code long}
1120      * after a narrowing primitive conversion.
1121      *
1122      * @return  the {@code double} value represented by this object
1123      *          converted to type {@code long}
1124      * @jls 5.1.3 Narrowing Primitive Conversion
1125      */
1126     public long longValue() {
1127         return (long)value;
1128     }
1129 
1130     /**
1131      * Returns the value of this {@code Double} as a {@code float}
1132      * after a narrowing primitive conversion.
1133      *
1134      * @apiNote
1135      * This method corresponds to the convertFormat operation defined
1136      * in IEEE 754.
1137      *
1138      * @return  the {@code double} value represented by this object
1139      *          converted to type {@code float}
1140      * @jls 5.1.3 Narrowing Primitive Conversion
1141      * @since 1.0
1142      */
1143     public float floatValue() {
1144         return (float)value;
1145     }
1146 
1147     /**
1148      * Returns the {@code double} value of this {@code Double} object.
1149      *
1150      * @return the {@code double} value represented by this object
1151      */
1152     @IntrinsicCandidate
1153     public double doubleValue() {
1154         return value;
1155     }
1156 
1157     /**
1158      * Returns a hash code for this {@code Double} object. The
1159      * result is the exclusive OR of the two halves of the
1160      * {@code long} integer bit representation, exactly as
1161      * produced by the method {@link #doubleToLongBits(double)}, of
1162      * the primitive {@code double} value represented by this
1163      * {@code Double} object. That is, the hash code is the value
1164      * of the expression:
1165      *
1166      * <blockquote>
1167      *  {@code (int)(v^(v>>>32))}
1168      * </blockquote>
1169      *
1170      * where {@code v} is defined by:
1171      *
1172      * <blockquote>
1173      *  {@code long v = Double.doubleToLongBits(this.doubleValue());}
1174      * </blockquote>
1175      *
1176      * @return  a {@code hash code} value for this object.
1177      */
1178     @Override
1179     public int hashCode() {
1180         return Double.hashCode(value);
1181     }
1182 
1183     /**
1184      * Returns a hash code for a {@code double} value; compatible with
1185      * {@code Double.hashCode()}.
1186      *
1187      * @param value the value to hash
1188      * @return a hash code value for a {@code double} value.
1189      * @since 1.8
1190      */
1191     public static int hashCode(double value) {
1192         return Long.hashCode(doubleToLongBits(value));
1193     }
1194 
1195     /**
1196      * Compares this object against the specified object.  The result
1197      * is {@code true} if and only if the argument is not
1198      * {@code null} and is a {@code Double} object that
1199      * represents a {@code double} that has the same value as the
1200      * {@code double} represented by this object. For this
1201      * purpose, two {@code double} values are considered to be
1202      * the same if and only if the method {@link
1203      * #doubleToLongBits(double)} returns the identical
1204      * {@code long} value when applied to each.
1205      *
1206      * @apiNote
1207      * This method is defined in terms of {@link
1208      * #doubleToLongBits(double)} rather than the {@code ==} operator
1209      * on {@code double} values since the {@code ==} operator does
1210      * <em>not</em> define an equivalence relation and to satisfy the
1211      * {@linkplain Object#equals equals contract} an equivalence
1212      * relation must be implemented; see <a
1213      * href="#equivalenceRelation">this discussion</a> for details of
1214      * floating-point equality and equivalence.
1215      *
1216      * @see java.lang.Double#doubleToLongBits(double)
1217      * @jls 15.21.1 Numerical Equality Operators == and !=
1218      */
1219     public boolean equals(Object obj) {
1220         return (obj instanceof Double)
1221                && (doubleToLongBits(((Double)obj).value) ==
1222                       doubleToLongBits(value));
1223     }
1224 
1225     /**
1226      * Returns a representation of the specified floating-point value
1227      * according to the IEEE 754 floating-point "double
1228      * format" bit layout.
1229      *
1230      * <p>Bit 63 (the bit that is selected by the mask
1231      * {@code 0x8000000000000000L}) represents the sign of the
1232      * floating-point number. Bits
1233      * 62-52 (the bits that are selected by the mask
1234      * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
1235      * (the bits that are selected by the mask
1236      * {@code 0x000fffffffffffffL}) represent the significand
1237      * (sometimes called the mantissa) of the floating-point number.
1238      *
1239      * <p>If the argument is positive infinity, the result is
1240      * {@code 0x7ff0000000000000L}.
1241      *
1242      * <p>If the argument is negative infinity, the result is
1243      * {@code 0xfff0000000000000L}.
1244      *
1245      * <p>If the argument is NaN, the result is
1246      * {@code 0x7ff8000000000000L}.
1247      *
1248      * <p>In all cases, the result is a {@code long} integer that, when
1249      * given to the {@link #longBitsToDouble(long)} method, will produce a
1250      * floating-point value the same as the argument to
1251      * {@code doubleToLongBits} (except all NaN values are
1252      * collapsed to a single "canonical" NaN value).
1253      *
1254      * @param   value   a {@code double} precision floating-point number.
1255      * @return the bits that represent the floating-point number.
1256      */
1257     @IntrinsicCandidate
1258     public static long doubleToLongBits(double value) {
1259         if (!isNaN(value)) {
1260             return doubleToRawLongBits(value);
1261         }
1262         return 0x7ff8000000000000L;
1263     }
1264 
1265     /**
1266      * Returns a representation of the specified floating-point value
1267      * according to the IEEE 754 floating-point "double
1268      * format" bit layout, preserving Not-a-Number (NaN) values.
1269      *
1270      * <p>Bit 63 (the bit that is selected by the mask
1271      * {@code 0x8000000000000000L}) represents the sign of the
1272      * floating-point number. Bits
1273      * 62-52 (the bits that are selected by the mask
1274      * {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
1275      * (the bits that are selected by the mask
1276      * {@code 0x000fffffffffffffL}) represent the significand
1277      * (sometimes called the mantissa) of the floating-point number.
1278      *
1279      * <p>If the argument is positive infinity, the result is
1280      * {@code 0x7ff0000000000000L}.
1281      *
1282      * <p>If the argument is negative infinity, the result is
1283      * {@code 0xfff0000000000000L}.
1284      *
1285      * <p>If the argument is NaN, the result is the {@code long}
1286      * integer representing the actual NaN value.  Unlike the
1287      * {@code doubleToLongBits} method,
1288      * {@code doubleToRawLongBits} does not collapse all the bit
1289      * patterns encoding a NaN to a single "canonical" NaN
1290      * value.
1291      *
1292      * <p>In all cases, the result is a {@code long} integer that,
1293      * when given to the {@link #longBitsToDouble(long)} method, will
1294      * produce a floating-point value the same as the argument to
1295      * {@code doubleToRawLongBits}.
1296      *
1297      * @param   value   a {@code double} precision floating-point number.
1298      * @return the bits that represent the floating-point number.
1299      * @since 1.3
1300      */
1301     @IntrinsicCandidate
1302     public static native long doubleToRawLongBits(double value);
1303 
1304     /**
1305      * Returns the {@code double} value corresponding to a given
1306      * bit representation.
1307      * The argument is considered to be a representation of a
1308      * floating-point value according to the IEEE 754 floating-point
1309      * "double format" bit layout.
1310      *
1311      * <p>If the argument is {@code 0x7ff0000000000000L}, the result
1312      * is positive infinity.
1313      *
1314      * <p>If the argument is {@code 0xfff0000000000000L}, the result
1315      * is negative infinity.
1316      *
1317      * <p>If the argument is any value in the range
1318      * {@code 0x7ff0000000000001L} through
1319      * {@code 0x7fffffffffffffffL} or in the range
1320      * {@code 0xfff0000000000001L} through
1321      * {@code 0xffffffffffffffffL}, the result is a NaN.  No IEEE
1322      * 754 floating-point operation provided by Java can distinguish
1323      * between two NaN values of the same type with different bit
1324      * patterns.  Distinct values of NaN are only distinguishable by
1325      * use of the {@code Double.doubleToRawLongBits} method.
1326      *
1327      * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three
1328      * values that can be computed from the argument:
1329      *
1330      * {@snippet lang="java" :
1331      * int s = ((bits >> 63) == 0) ? 1 : -1;
1332      * int e = (int)((bits >> 52) & 0x7ffL);
1333      * long m = (e == 0) ?
1334      *                 (bits & 0xfffffffffffffL) << 1 :
1335      *                 (bits & 0xfffffffffffffL) | 0x10000000000000L;
1336      * }
1337      *
1338      * Then the floating-point result equals the value of the mathematical
1339      * expression <i>s</i>&middot;<i>m</i>&middot;2<sup><i>e</i>-1075</sup>.
1340      *
1341      * <p>Note that this method may not be able to return a
1342      * {@code double} NaN with exactly same bit pattern as the
1343      * {@code long} argument.  IEEE 754 distinguishes between two
1344      * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>.  The
1345      * differences between the two kinds of NaN are generally not
1346      * visible in Java.  Arithmetic operations on signaling NaNs turn
1347      * them into quiet NaNs with a different, but often similar, bit
1348      * pattern.  However, on some processors merely copying a
1349      * signaling NaN also performs that conversion.  In particular,
1350      * copying a signaling NaN to return it to the calling method
1351      * may perform this conversion.  So {@code longBitsToDouble}
1352      * may not be able to return a {@code double} with a
1353      * signaling NaN bit pattern.  Consequently, for some
1354      * {@code long} values,
1355      * {@code doubleToRawLongBits(longBitsToDouble(start))} may
1356      * <i>not</i> equal {@code start}.  Moreover, which
1357      * particular bit patterns represent signaling NaNs is platform
1358      * dependent; although all NaN bit patterns, quiet or signaling,
1359      * must be in the NaN range identified above.
1360      *
1361      * @param   bits   any {@code long} integer.
1362      * @return  the {@code double} floating-point value with the same
1363      *          bit pattern.
1364      */
1365     @IntrinsicCandidate
1366     public static native double longBitsToDouble(long bits);
1367 
1368     /**
1369      * Compares two {@code Double} objects numerically.
1370      *
1371      * This method imposes a total order on {@code Double} objects
1372      * with two differences compared to the incomplete order defined by
1373      * the Java language numerical comparison operators ({@code <, <=,
1374      * ==, >=, >}) on {@code double} values.
1375      *
1376      * <ul><li> A NaN is <em>unordered</em> with respect to other
1377      *          values and unequal to itself under the comparison
1378      *          operators.  This method chooses to define {@code
1379      *          Double.NaN} to be equal to itself and greater than all
1380      *          other {@code double} values (including {@code
1381      *          Double.POSITIVE_INFINITY}).
1382      *
1383      *      <li> Positive zero and negative zero compare equal
1384      *      numerically, but are distinct and distinguishable values.
1385      *      This method chooses to define positive zero ({@code +0.0d}),
1386      *      to be greater than negative zero ({@code -0.0d}).
1387      * </ul>
1388 
1389      * This ensures that the <i>natural ordering</i> of {@code Double}
1390      * objects imposed by this method is <i>consistent with
1391      * equals</i>; see <a href="#equivalenceRelation">this
1392      * discussion</a> for details of floating-point comparison and
1393      * ordering.
1394      *
1395      * @param   anotherDouble   the {@code Double} to be compared.
1396      * @return  the value {@code 0} if {@code anotherDouble} is
1397      *          numerically equal to this {@code Double}; a value
1398      *          less than {@code 0} if this {@code Double}
1399      *          is numerically less than {@code anotherDouble};
1400      *          and a value greater than {@code 0} if this
1401      *          {@code Double} is numerically greater than
1402      *          {@code anotherDouble}.
1403      *
1404      * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
1405      * @since   1.2
1406      */
1407     public int compareTo(Double anotherDouble) {
1408         return Double.compare(value, anotherDouble.value);
1409     }
1410 
1411     /**
1412      * Compares the two specified {@code double} values. The sign
1413      * of the integer value returned is the same as that of the
1414      * integer that would be returned by the call:
1415      * <pre>
1416      *    Double.valueOf(d1).compareTo(Double.valueOf(d2))
1417      * </pre>
1418      *
1419      * @param   d1        the first {@code double} to compare
1420      * @param   d2        the second {@code double} to compare
1421      * @return  the value {@code 0} if {@code d1} is
1422      *          numerically equal to {@code d2}; a value less than
1423      *          {@code 0} if {@code d1} is numerically less than
1424      *          {@code d2}; and a value greater than {@code 0}
1425      *          if {@code d1} is numerically greater than
1426      *          {@code d2}.
1427      * @since 1.4
1428      */
1429     public static int compare(double d1, double d2) {
1430         if (d1 < d2)
1431             return -1;           // Neither val is NaN, thisVal is smaller
1432         if (d1 > d2)
1433             return 1;            // Neither val is NaN, thisVal is larger
1434 
1435         // Cannot use doubleToRawLongBits because of possibility of NaNs.
1436         long thisBits    = Double.doubleToLongBits(d1);
1437         long anotherBits = Double.doubleToLongBits(d2);
1438 
1439         return (thisBits == anotherBits ?  0 : // Values are equal
1440                 (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1441                  1));                          // (0.0, -0.0) or (NaN, !NaN)
1442     }
1443 
1444     /**
1445      * Adds two {@code double} values together as per the + operator.
1446      *
1447      * @apiNote This method corresponds to the addition operation
1448      * defined in IEEE 754.
1449      *
1450      * @param a the first operand
1451      * @param b the second operand
1452      * @return the sum of {@code a} and {@code b}
1453      * @jls 4.2.4 Floating-Point Operations
1454      * @see java.util.function.BinaryOperator
1455      * @since 1.8
1456      */
1457     public static double sum(double a, double b) {
1458         return a + b;
1459     }
1460 
1461     /**
1462      * Returns the greater of two {@code double} values
1463      * as if by calling {@link Math#max(double, double) Math.max}.
1464      *
1465      * @apiNote
1466      * This method corresponds to the maximum operation defined in
1467      * IEEE 754.
1468      *
1469      * @param a the first operand
1470      * @param b the second operand
1471      * @return the greater of {@code a} and {@code b}
1472      * @see java.util.function.BinaryOperator
1473      * @since 1.8
1474      */
1475     public static double max(double a, double b) {
1476         return Math.max(a, b);
1477     }
1478 
1479     /**
1480      * Returns the smaller of two {@code double} values
1481      * as if by calling {@link Math#min(double, double) Math.min}.
1482      *
1483      * @apiNote
1484      * This method corresponds to the minimum operation defined in
1485      * IEEE 754.
1486      *
1487      * @param a the first operand
1488      * @param b the second operand
1489      * @return the smaller of {@code a} and {@code b}.
1490      * @see java.util.function.BinaryOperator
1491      * @since 1.8
1492      */
1493     public static double min(double a, double b) {
1494         return Math.min(a, b);
1495     }
1496 
1497     /**
1498      * Returns an {@link Optional} containing the nominal descriptor for this
1499      * instance, which is the instance itself.
1500      *
1501      * @return an {@link Optional} describing the {@linkplain Double} instance
1502      * @since 12
1503      */
1504     @Override
1505     public Optional<Double> describeConstable() {
1506         return Optional.of(this);
1507     }
1508 
1509     /**
1510      * Resolves this instance as a {@link ConstantDesc}, the result of which is
1511      * the instance itself.
1512      *
1513      * @param lookup ignored
1514      * @return the {@linkplain Double} instance
1515      * @since 12
1516      */
1517     @Override
1518     public Double resolveConstantDesc(MethodHandles.Lookup lookup) {
1519         return this;
1520     }
1521 
1522     /** use serialVersionUID from JDK 1.0.2 for interoperability */
1523     @java.io.Serial
1524     private static final long serialVersionUID = -9172774392245257468L;
1525 }