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