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