Path: blob/master/src/java.base/share/classes/java/lang/Double.java
41152 views
/*1* Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.lang;2627import java.lang.invoke.MethodHandles;28import java.lang.constant.Constable;29import java.lang.constant.ConstantDesc;30import java.util.Optional;3132import jdk.internal.math.FloatingDecimal;33import jdk.internal.math.DoubleConsts;34import jdk.internal.vm.annotation.IntrinsicCandidate;3536/**37* The {@code Double} class wraps a value of the primitive type38* {@code double} in an object. An object of type39* {@code Double} contains a single field whose type is40* {@code double}.41*42* <p>In addition, this class provides several methods for converting a43* {@code double} to a {@code String} and a44* {@code String} to a {@code double}, as well as other45* constants and methods useful when dealing with a46* {@code double}.47*48* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>49* class; programmers should treat instances that are50* {@linkplain #equals(Object) equal} as interchangeable and should not51* use instances for synchronization, or unpredictable behavior may52* occur. For example, in a future release, synchronization may fail.53*54* <h2><a id=equivalenceRelation>Floating-point Equality, Equivalence,55* and Comparison</a></h2>56*57* IEEE 754 floating-point values include finite nonzero values,58* signed zeros ({@code +0.0} and {@code -0.0}), signed infinities59* {@linkplain Double#POSITIVE_INFINITY positive infinity} and60* {@linkplain Double#NEGATIVE_INFINITY negative infinity}), and61* {@linkplain Double#NaN NaN} (not-a-number).62*63* <p>An <em>equivalence relation</em> on a set of values is a boolean64* relation on pairs of values that is reflexive, symmetric, and65* transitive. For more discussion of equivalence relations and object66* equality, see the {@link Object#equals Object.equals}67* specification. An equivalence relation partitions the values it68* operates over into sets called <i>equivalence classes</i>. All the69* members of the equivalence class are equal to each other under the70* relation. An equivalence class may contain only a single member. At71* least for some purposes, all the members of an equivalence class72* are substitutable for each other. In particular, in a numeric73* expression equivalent values can be <em>substituted</em> for one74* another without changing the result of the expression, meaning75* changing the equivalence class of the result of the expression.76*77* <p>Notably, the built-in {@code ==} operation on floating-point78* values is <em>not</em> an equivalence relation. Despite not79* defining an equivalence relation, the semantics of the IEEE 75480* {@code ==} operator were deliberately designed to meet other needs81* of numerical computation. There are two exceptions where the82* properties of an equivalence relation are not satisfied by {@code83* ==} on floating-point values:84*85* <ul>86*87* <li>If {@code v1} and {@code v2} are both NaN, then {@code v188* == v2} has the value {@code false}. Therefore, for two NaN89* arguments the <em>reflexive</em> property of an equivalence90* relation is <em>not</em> satisfied by the {@code ==} operator.91*92* <li>If {@code v1} represents {@code +0.0} while {@code v2}93* represents {@code -0.0}, or vice versa, then {@code v1 == v2} has94* the value {@code true} even though {@code +0.0} and {@code -0.0}95* are distinguishable under various floating-point operations. For96* example, {@code 1.0/+0.0} evaluates to positive infinity while97* {@code 1.0/-0.0} evaluates to <em>negative</em> infinity and98* positive infinity and negative infinity are neither equal to each99* other nor equivalent to each other. Thus, while a signed zero input100* most commonly determines the sign of a zero result, because of101* dividing by zero, {@code +0.0} and {@code -0.0} may not be102* substituted for each other in general. The sign of a zero input103* also has a non-substitutable effect on the result of some math104* library methods.105*106* </ul>107*108* <p>For ordered comparisons using the built-in comparison operators109* ({@code <}, {@code <=}, etc.), NaN values have another anomalous110* situation: a NaN is neither less than, nor greater than, nor equal111* to any value, including itself. This means the <i>trichotomy of112* comparison</i> does <em>not</em> hold.113*114* <p>To provide the appropriate semantics for {@code equals} and115* {@code compareTo} methods, those methods cannot simply be wrappers116* around {@code ==} or ordered comparison operations. Instead, {@link117* Double#equals equals} defines NaN arguments to be equal to each118* other and defines {@code +0.0} to <em>not</em> be equal to {@code119* -0.0}, restoring reflexivity. For comparisons, {@link120* Double#compareTo compareTo} defines a total order where {@code121* -0.0} is less than {@code +0.0} and where a NaN is equal to itself122* and considered greater than positive infinity.123*124* <p>The operational semantics of {@code equals} and {@code125* compareTo} are expressed in terms of {@linkplain #doubleToLongBits126* bit-wise converting} the floating-point values to integral values.127*128* <p>The <em>natural ordering</em> implemented by {@link #compareTo129* compareTo} is {@linkplain Comparable consistent with equals}. That130* is, two objects are reported as equal by {@code equals} if and only131* if {@code compareTo} on those objects returns zero.132*133* <p>The adjusted behaviors defined for {@code equals} and {@code134* compareTo} allow instances of wrapper classes to work properly with135* conventional data structures. For example, defining NaN136* values to be {@code equals} to one another allows NaN to be used as137* an element of a {@link java.util.HashSet HashSet} or as the key of138* a {@link java.util.HashMap HashMap}. Similarly, defining {@code139* compareTo} as a total ordering, including {@code +0.0}, {@code140* -0.0}, and NaN, allows instances of wrapper classes to be used as141* elements of a {@link java.util.SortedSet SortedSet} or as keys of a142* {@link java.util.SortedMap SortedMap}.143*144* @jls 4.2.3 Floating-Point Types, Formats, and Values145* @jls 4.2.4. Floating-Point Operations146* @jls 15.21.1 Numerical Equality Operators == and !=147* @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}148*149* @author Lee Boynton150* @author Arthur van Hoff151* @author Joseph D. Darcy152* @since 1.0153*/154@jdk.internal.ValueBased155public final class Double extends Number156implements Comparable<Double>, Constable, ConstantDesc {157/**158* A constant holding the positive infinity of type159* {@code double}. It is equal to the value returned by160* {@code Double.longBitsToDouble(0x7ff0000000000000L)}.161*/162public static final double POSITIVE_INFINITY = 1.0 / 0.0;163164/**165* A constant holding the negative infinity of type166* {@code double}. It is equal to the value returned by167* {@code Double.longBitsToDouble(0xfff0000000000000L)}.168*/169public static final double NEGATIVE_INFINITY = -1.0 / 0.0;170171/**172* A constant holding a Not-a-Number (NaN) value of type173* {@code double}. It is equivalent to the value returned by174* {@code Double.longBitsToDouble(0x7ff8000000000000L)}.175*/176public static final double NaN = 0.0d / 0.0;177178/**179* A constant holding the largest positive finite value of type180* {@code double},181* (2-2<sup>-52</sup>)·2<sup>1023</sup>. It is equal to182* the hexadecimal floating-point literal183* {@code 0x1.fffffffffffffP+1023} and also equal to184* {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.185*/186public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308187188/**189* A constant holding the smallest positive normal value of type190* {@code double}, 2<sup>-1022</sup>. It is equal to the191* hexadecimal floating-point literal {@code 0x1.0p-1022} and also192* equal to {@code Double.longBitsToDouble(0x0010000000000000L)}.193*194* @since 1.6195*/196public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308197198/**199* A constant holding the smallest positive nonzero value of type200* {@code double}, 2<sup>-1074</sup>. It is equal to the201* hexadecimal floating-point literal202* {@code 0x0.0000000000001P-1022} and also equal to203* {@code Double.longBitsToDouble(0x1L)}.204*/205public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324206207/**208* Maximum exponent a finite {@code double} variable may have.209* It is equal to the value returned by210* {@code Math.getExponent(Double.MAX_VALUE)}.211*212* @since 1.6213*/214public static final int MAX_EXPONENT = 1023;215216/**217* Minimum exponent a normalized {@code double} variable may218* have. It is equal to the value returned by219* {@code Math.getExponent(Double.MIN_NORMAL)}.220*221* @since 1.6222*/223public static final int MIN_EXPONENT = -1022;224225/**226* The number of bits used to represent a {@code double} value.227*228* @since 1.5229*/230public static final int SIZE = 64;231232/**233* The number of bytes used to represent a {@code double} value.234*235* @since 1.8236*/237public static final int BYTES = SIZE / Byte.SIZE;238239/**240* The {@code Class} instance representing the primitive type241* {@code double}.242*243* @since 1.1244*/245@SuppressWarnings("unchecked")246public static final Class<Double> TYPE = (Class<Double>) Class.getPrimitiveClass("double");247248/**249* Returns a string representation of the {@code double}250* argument. All characters mentioned below are ASCII characters.251* <ul>252* <li>If the argument is NaN, the result is the string253* "{@code NaN}".254* <li>Otherwise, the result is a string that represents the sign and255* magnitude (absolute value) of the argument. If the sign is negative,256* the first character of the result is '{@code -}'257* ({@code '\u005Cu002D'}); if the sign is positive, no sign character258* appears in the result. As for the magnitude <i>m</i>:259* <ul>260* <li>If <i>m</i> is infinity, it is represented by the characters261* {@code "Infinity"}; thus, positive infinity produces the result262* {@code "Infinity"} and negative infinity produces the result263* {@code "-Infinity"}.264*265* <li>If <i>m</i> is zero, it is represented by the characters266* {@code "0.0"}; thus, negative zero produces the result267* {@code "-0.0"} and positive zero produces the result268* {@code "0.0"}.269*270* <li>If <i>m</i> is greater than or equal to 10<sup>-3</sup> but less271* than 10<sup>7</sup>, then it is represented as the integer part of272* <i>m</i>, in decimal form with no leading zeroes, followed by273* '{@code .}' ({@code '\u005Cu002E'}), followed by one or274* more decimal digits representing the fractional part of <i>m</i>.275*276* <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or277* equal to 10<sup>7</sup>, then it is represented in so-called278* "computerized scientific notation." Let <i>n</i> be the unique279* integer such that 10<sup><i>n</i></sup> ≤ <i>m</i> {@literal <}280* 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the281* mathematically exact quotient of <i>m</i> and282* 10<sup><i>n</i></sup> so that 1 ≤ <i>a</i> {@literal <} 10. The283* magnitude is then represented as the integer part of <i>a</i>,284* as a single decimal digit, followed by '{@code .}'285* ({@code '\u005Cu002E'}), followed by decimal digits286* representing the fractional part of <i>a</i>, followed by the287* letter '{@code E}' ({@code '\u005Cu0045'}), followed288* by a representation of <i>n</i> as a decimal integer, as289* produced by the method {@link Integer#toString(int)}.290* </ul>291* </ul>292* How many digits must be printed for the fractional part of293* <i>m</i> or <i>a</i>? There must be at least one digit to represent294* the fractional part, and beyond that as many, but only as many, more295* digits as are needed to uniquely distinguish the argument value from296* adjacent values of type {@code double}. That is, suppose that297* <i>x</i> is the exact mathematical value represented by the decimal298* representation produced by this method for a finite nonzero argument299* <i>d</i>. Then <i>d</i> must be the {@code double} value nearest300* to <i>x</i>; or if two {@code double} values are equally close301* to <i>x</i>, then <i>d</i> must be one of them and the least302* significant bit of the significand of <i>d</i> must be {@code 0}.303*304* <p>To create localized string representations of a floating-point305* value, use subclasses of {@link java.text.NumberFormat}.306*307* @param d the {@code double} to be converted.308* @return a string representation of the argument.309*/310public static String toString(double d) {311return FloatingDecimal.toJavaFormatString(d);312}313314/**315* Returns a hexadecimal string representation of the316* {@code double} argument. All characters mentioned below317* are ASCII characters.318*319* <ul>320* <li>If the argument is NaN, the result is the string321* "{@code NaN}".322* <li>Otherwise, the result is a string that represents the sign323* and magnitude of the argument. If the sign is negative, the324* first character of the result is '{@code -}'325* ({@code '\u005Cu002D'}); if the sign is positive, no sign326* character appears in the result. As for the magnitude <i>m</i>:327*328* <ul>329* <li>If <i>m</i> is infinity, it is represented by the string330* {@code "Infinity"}; thus, positive infinity produces the331* result {@code "Infinity"} and negative infinity produces332* the result {@code "-Infinity"}.333*334* <li>If <i>m</i> is zero, it is represented by the string335* {@code "0x0.0p0"}; thus, negative zero produces the result336* {@code "-0x0.0p0"} and positive zero produces the result337* {@code "0x0.0p0"}.338*339* <li>If <i>m</i> is a {@code double} value with a340* normalized representation, substrings are used to represent the341* significand and exponent fields. The significand is342* represented by the characters {@code "0x1."}343* followed by a lowercase hexadecimal representation of the rest344* of the significand as a fraction. Trailing zeros in the345* hexadecimal representation are removed unless all the digits346* are zero, in which case a single zero is used. Next, the347* exponent is represented by {@code "p"} followed348* by a decimal string of the unbiased exponent as if produced by349* a call to {@link Integer#toString(int) Integer.toString} on the350* exponent value.351*352* <li>If <i>m</i> is a {@code double} value with a subnormal353* representation, the significand is represented by the354* characters {@code "0x0."} followed by a355* hexadecimal representation of the rest of the significand as a356* fraction. Trailing zeros in the hexadecimal representation are357* removed. Next, the exponent is represented by358* {@code "p-1022"}. Note that there must be at359* least one nonzero digit in a subnormal significand.360*361* </ul>362*363* </ul>364*365* <table class="striped">366* <caption>Examples</caption>367* <thead>368* <tr><th scope="col">Floating-point Value</th><th scope="col">Hexadecimal String</th>369* </thead>370* <tbody style="text-align:right">371* <tr><th scope="row">{@code 1.0}</th> <td>{@code 0x1.0p0}</td>372* <tr><th scope="row">{@code -1.0}</th> <td>{@code -0x1.0p0}</td>373* <tr><th scope="row">{@code 2.0}</th> <td>{@code 0x1.0p1}</td>374* <tr><th scope="row">{@code 3.0}</th> <td>{@code 0x1.8p1}</td>375* <tr><th scope="row">{@code 0.5}</th> <td>{@code 0x1.0p-1}</td>376* <tr><th scope="row">{@code 0.25}</th> <td>{@code 0x1.0p-2}</td>377* <tr><th scope="row">{@code Double.MAX_VALUE}</th>378* <td>{@code 0x1.fffffffffffffp1023}</td>379* <tr><th scope="row">{@code Minimum Normal Value}</th>380* <td>{@code 0x1.0p-1022}</td>381* <tr><th scope="row">{@code Maximum Subnormal Value}</th>382* <td>{@code 0x0.fffffffffffffp-1022}</td>383* <tr><th scope="row">{@code Double.MIN_VALUE}</th>384* <td>{@code 0x0.0000000000001p-1022}</td>385* </tbody>386* </table>387* @param d the {@code double} to be converted.388* @return a hex string representation of the argument.389* @since 1.5390* @author Joseph D. Darcy391*/392public static String toHexString(double d) {393/*394* Modeled after the "a" conversion specifier in C99, section395* 7.19.6.1; however, the output of this method is more396* tightly specified.397*/398if (!isFinite(d) )399// For infinity and NaN, use the decimal output.400return Double.toString(d);401else {402// Initialized to maximum size of output.403StringBuilder answer = new StringBuilder(24);404405if (Math.copySign(1.0, d) == -1.0) // value is negative,406answer.append("-"); // so append sign info407408answer.append("0x");409410d = Math.abs(d);411412if(d == 0.0) {413answer.append("0.0p0");414} else {415boolean subnormal = (d < Double.MIN_NORMAL);416417// Isolate significand bits and OR in a high-order bit418// so that the string representation has a known419// length.420long signifBits = (Double.doubleToLongBits(d)421& DoubleConsts.SIGNIF_BIT_MASK) |4220x1000000000000000L;423424// Subnormal values have a 0 implicit bit; normal425// values have a 1 implicit bit.426answer.append(subnormal ? "0." : "1.");427428// Isolate the low-order 13 digits of the hex429// representation. If all the digits are zero,430// replace with a single 0; otherwise, remove all431// trailing zeros.432String signif = Long.toHexString(signifBits).substring(3,16);433answer.append(signif.equals("0000000000000") ? // 13 zeros434"0":435signif.replaceFirst("0{1,12}$", ""));436437answer.append('p');438// If the value is subnormal, use the E_min exponent439// value for double; otherwise, extract and report d's440// exponent (the representation of a subnormal uses441// E_min -1).442answer.append(subnormal ?443Double.MIN_EXPONENT:444Math.getExponent(d));445}446return answer.toString();447}448}449450/**451* Returns a {@code Double} object holding the452* {@code double} value represented by the argument string453* {@code s}.454*455* <p>If {@code s} is {@code null}, then a456* {@code NullPointerException} is thrown.457*458* <p>Leading and trailing whitespace characters in {@code s}459* are ignored. Whitespace is removed as if by the {@link460* String#trim} method; that is, both ASCII space and control461* characters are removed. The rest of {@code s} should462* constitute a <i>FloatValue</i> as described by the lexical463* syntax rules:464*465* <blockquote>466* <dl>467* <dt><i>FloatValue:</i>468* <dd><i>Sign<sub>opt</sub></i> {@code NaN}469* <dd><i>Sign<sub>opt</sub></i> {@code Infinity}470* <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i>471* <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i>472* <dd><i>SignedInteger</i>473* </dl>474*475* <dl>476* <dt><i>HexFloatingPointLiteral</i>:477* <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i>478* </dl>479*480* <dl>481* <dt><i>HexSignificand:</i>482* <dd><i>HexNumeral</i>483* <dd><i>HexNumeral</i> {@code .}484* <dd>{@code 0x} <i>HexDigits<sub>opt</sub>485* </i>{@code .}<i> HexDigits</i>486* <dd>{@code 0X}<i> HexDigits<sub>opt</sub>487* </i>{@code .} <i>HexDigits</i>488* </dl>489*490* <dl>491* <dt><i>BinaryExponent:</i>492* <dd><i>BinaryExponentIndicator SignedInteger</i>493* </dl>494*495* <dl>496* <dt><i>BinaryExponentIndicator:</i>497* <dd>{@code p}498* <dd>{@code P}499* </dl>500*501* </blockquote>502*503* where <i>Sign</i>, <i>FloatingPointLiteral</i>,504* <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and505* <i>FloatTypeSuffix</i> are as defined in the lexical structure506* sections of507* <cite>The Java Language Specification</cite>,508* except that underscores are not accepted between digits.509* If {@code s} does not have the form of510* a <i>FloatValue</i>, then a {@code NumberFormatException}511* is thrown. Otherwise, {@code s} is regarded as512* representing an exact decimal value in the usual513* "computerized scientific notation" or as an exact514* hexadecimal value; this exact numerical value is then515* conceptually converted to an "infinitely precise"516* binary value that is then rounded to type {@code double}517* by the usual round-to-nearest rule of IEEE 754 floating-point518* arithmetic, which includes preserving the sign of a zero519* value.520*521* Note that the round-to-nearest rule also implies overflow and522* underflow behaviour; if the exact value of {@code s} is large523* enough in magnitude (greater than or equal to ({@link524* #MAX_VALUE} + {@link Math#ulp(double) ulp(MAX_VALUE)}/2),525* rounding to {@code double} will result in an infinity and if the526* exact value of {@code s} is small enough in magnitude (less527* than or equal to {@link #MIN_VALUE}/2), rounding to float will528* result in a zero.529*530* Finally, after rounding a {@code Double} object representing531* this {@code double} value is returned.532*533* <p> To interpret localized string representations of a534* floating-point value, use subclasses of {@link535* java.text.NumberFormat}.536*537* <p>Note that trailing format specifiers, specifiers that538* determine the type of a floating-point literal539* ({@code 1.0f} is a {@code float} value;540* {@code 1.0d} is a {@code double} value), do541* <em>not</em> influence the results of this method. In other542* words, the numerical value of the input string is converted543* directly to the target floating-point type. The two-step544* sequence of conversions, string to {@code float} followed545* by {@code float} to {@code double}, is <em>not</em>546* equivalent to converting a string directly to547* {@code double}. For example, the {@code float}548* literal {@code 0.1f} is equal to the {@code double}549* value {@code 0.10000000149011612}; the {@code float}550* literal {@code 0.1f} represents a different numerical551* value than the {@code double} literal552* {@code 0.1}. (The numerical value 0.1 cannot be exactly553* represented in a binary floating-point number.)554*555* <p>To avoid calling this method on an invalid string and having556* a {@code NumberFormatException} be thrown, the regular557* expression below can be used to screen the input string:558*559* <pre>{@code560* final String Digits = "(\\p{Digit}+)";561* final String HexDigits = "(\\p{XDigit}+)";562* // an exponent is 'e' or 'E' followed by an optionally563* // signed decimal integer.564* final String Exp = "[eE][+-]?"+Digits;565* final String fpRegex =566* ("[\\x00-\\x20]*"+ // Optional leading "whitespace"567* "[+-]?(" + // Optional sign character568* "NaN|" + // "NaN" string569* "Infinity|" + // "Infinity" string570*571* // A decimal floating-point string representing a finite positive572* // number without a leading sign has at most five basic pieces:573* // Digits . Digits ExponentPart FloatTypeSuffix574* //575* // Since this method allows integer-only strings as input576* // in addition to strings of floating-point literals, the577* // two sub-patterns below are simplifications of the grammar578* // productions from section 3.10.2 of579* // The Java Language Specification.580*581* // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt582* "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+583*584* // . Digits ExponentPart_opt FloatTypeSuffix_opt585* "(\\.("+Digits+")("+Exp+")?)|"+586*587* // Hexadecimal strings588* "((" +589* // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt590* "(0[xX]" + HexDigits + "(\\.)?)|" +591*592* // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt593* "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +594*595* ")[pP][+-]?" + Digits + "))" +596* "[fFdD]?))" +597* "[\\x00-\\x20]*");// Optional trailing "whitespace"598*599* if (Pattern.matches(fpRegex, myString))600* Double.valueOf(myString); // Will not throw NumberFormatException601* else {602* // Perform suitable alternative action603* }604* }</pre>605*606* @param s the string to be parsed.607* @return a {@code Double} object holding the value608* represented by the {@code String} argument.609* @throws NumberFormatException if the string does not contain a610* parsable number.611*/612public static Double valueOf(String s) throws NumberFormatException {613return new Double(parseDouble(s));614}615616/**617* Returns a {@code Double} instance representing the specified618* {@code double} value.619* If a new {@code Double} instance is not required, this method620* should generally be used in preference to the constructor621* {@link #Double(double)}, as this method is likely to yield622* significantly better space and time performance by caching623* frequently requested values.624*625* @param d a double value.626* @return a {@code Double} instance representing {@code d}.627* @since 1.5628*/629@IntrinsicCandidate630public static Double valueOf(double d) {631return new Double(d);632}633634/**635* Returns a new {@code double} initialized to the value636* represented by the specified {@code String}, as performed637* by the {@code valueOf} method of class638* {@code Double}.639*640* @param s the string to be parsed.641* @return the {@code double} value represented by the string642* argument.643* @throws NullPointerException if the string is null644* @throws NumberFormatException if the string does not contain645* a parsable {@code double}.646* @see java.lang.Double#valueOf(String)647* @since 1.2648*/649public static double parseDouble(String s) throws NumberFormatException {650return FloatingDecimal.parseDouble(s);651}652653/**654* Returns {@code true} if the specified number is a655* Not-a-Number (NaN) value, {@code false} otherwise.656*657* @param v the value to be tested.658* @return {@code true} if the value of the argument is NaN;659* {@code false} otherwise.660*/661public static boolean isNaN(double v) {662return (v != v);663}664665/**666* Returns {@code true} if the specified number is infinitely667* large in magnitude, {@code false} otherwise.668*669* @param v the value to be tested.670* @return {@code true} if the value of the argument is positive671* infinity or negative infinity; {@code false} otherwise.672*/673public static boolean isInfinite(double v) {674return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY);675}676677/**678* Returns {@code true} if the argument is a finite floating-point679* value; returns {@code false} otherwise (for NaN and infinity680* arguments).681*682* @param d the {@code double} value to be tested683* @return {@code true} if the argument is a finite684* floating-point value, {@code false} otherwise.685* @since 1.8686*/687public static boolean isFinite(double d) {688return Math.abs(d) <= Double.MAX_VALUE;689}690691/**692* The value of the Double.693*694* @serial695*/696private final double value;697698/**699* Constructs a newly allocated {@code Double} object that700* represents the primitive {@code double} argument.701*702* @param value the value to be represented by the {@code Double}.703*704* @deprecated705* It is rarely appropriate to use this constructor. The static factory706* {@link #valueOf(double)} is generally a better choice, as it is707* likely to yield significantly better space and time performance.708*/709@Deprecated(since="9", forRemoval = true)710public Double(double value) {711this.value = value;712}713714/**715* Constructs a newly allocated {@code Double} object that716* represents the floating-point value of type {@code double}717* represented by the string. The string is converted to a718* {@code double} value as if by the {@code valueOf} method.719*720* @param s a string to be converted to a {@code Double}.721* @throws NumberFormatException if the string does not contain a722* parsable number.723*724* @deprecated725* It is rarely appropriate to use this constructor.726* Use {@link #parseDouble(String)} to convert a string to a727* {@code double} primitive, or use {@link #valueOf(String)}728* to convert a string to a {@code Double} object.729*/730@Deprecated(since="9", forRemoval = true)731public Double(String s) throws NumberFormatException {732value = parseDouble(s);733}734735/**736* Returns {@code true} if this {@code Double} value is737* a Not-a-Number (NaN), {@code false} otherwise.738*739* @return {@code true} if the value represented by this object is740* NaN; {@code false} otherwise.741*/742public boolean isNaN() {743return isNaN(value);744}745746/**747* Returns {@code true} if this {@code Double} value is748* infinitely large in magnitude, {@code false} otherwise.749*750* @return {@code true} if the value represented by this object is751* positive infinity or negative infinity;752* {@code false} otherwise.753*/754public boolean isInfinite() {755return isInfinite(value);756}757758/**759* Returns a string representation of this {@code Double} object.760* The primitive {@code double} value represented by this761* object is converted to a string exactly as if by the method762* {@code toString} of one argument.763*764* @return a {@code String} representation of this object.765* @see java.lang.Double#toString(double)766*/767public String toString() {768return toString(value);769}770771/**772* Returns the value of this {@code Double} as a {@code byte}773* after a narrowing primitive conversion.774*775* @return the {@code double} value represented by this object776* converted to type {@code byte}777* @jls 5.1.3 Narrowing Primitive Conversion778* @since 1.1779*/780public byte byteValue() {781return (byte)value;782}783784/**785* Returns the value of this {@code Double} as a {@code short}786* after a narrowing primitive conversion.787*788* @return the {@code double} value represented by this object789* converted to type {@code short}790* @jls 5.1.3 Narrowing Primitive Conversion791* @since 1.1792*/793public short shortValue() {794return (short)value;795}796797/**798* Returns the value of this {@code Double} as an {@code int}799* after a narrowing primitive conversion.800* @jls 5.1.3 Narrowing Primitive Conversion801*802* @return the {@code double} value represented by this object803* converted to type {@code int}804*/805public int intValue() {806return (int)value;807}808809/**810* Returns the value of this {@code Double} as a {@code long}811* after a narrowing primitive conversion.812*813* @return the {@code double} value represented by this object814* converted to type {@code long}815* @jls 5.1.3 Narrowing Primitive Conversion816*/817public long longValue() {818return (long)value;819}820821/**822* Returns the value of this {@code Double} as a {@code float}823* after a narrowing primitive conversion.824*825* @return the {@code double} value represented by this object826* converted to type {@code float}827* @jls 5.1.3 Narrowing Primitive Conversion828* @since 1.0829*/830public float floatValue() {831return (float)value;832}833834/**835* Returns the {@code double} value of this {@code Double} object.836*837* @return the {@code double} value represented by this object838*/839@IntrinsicCandidate840public double doubleValue() {841return value;842}843844/**845* Returns a hash code for this {@code Double} object. The846* result is the exclusive OR of the two halves of the847* {@code long} integer bit representation, exactly as848* produced by the method {@link #doubleToLongBits(double)}, of849* the primitive {@code double} value represented by this850* {@code Double} object. That is, the hash code is the value851* of the expression:852*853* <blockquote>854* {@code (int)(v^(v>>>32))}855* </blockquote>856*857* where {@code v} is defined by:858*859* <blockquote>860* {@code long v = Double.doubleToLongBits(this.doubleValue());}861* </blockquote>862*863* @return a {@code hash code} value for this object.864*/865@Override866public int hashCode() {867return Double.hashCode(value);868}869870/**871* Returns a hash code for a {@code double} value; compatible with872* {@code Double.hashCode()}.873*874* @param value the value to hash875* @return a hash code value for a {@code double} value.876* @since 1.8877*/878public static int hashCode(double value) {879long bits = doubleToLongBits(value);880return (int)(bits ^ (bits >>> 32));881}882883/**884* Compares this object against the specified object. The result885* is {@code true} if and only if the argument is not886* {@code null} and is a {@code Double} object that887* represents a {@code double} that has the same value as the888* {@code double} represented by this object. For this889* purpose, two {@code double} values are considered to be890* the same if and only if the method {@link891* #doubleToLongBits(double)} returns the identical892* {@code long} value when applied to each.893*894* @apiNote895* This method is defined in terms of {@link896* #doubleToLongBits(double)} rather than the {@code ==} operator897* on {@code double} values since the {@code ==} operator does898* <em>not</em> define an equivalence relation and to satisfy the899* {@linkplain Object#equals equals contract} an equivalence900* relation must be implemented; see <a901* href="#equivalenceRelation">this discussion</a> for details of902* floating-point equality and equivalence.903*904* @see java.lang.Double#doubleToLongBits(double)905* @jls 15.21.1 Numerical Equality Operators == and !=906*/907public boolean equals(Object obj) {908return (obj instanceof Double)909&& (doubleToLongBits(((Double)obj).value) ==910doubleToLongBits(value));911}912913/**914* Returns a representation of the specified floating-point value915* according to the IEEE 754 floating-point "double916* format" bit layout.917*918* <p>Bit 63 (the bit that is selected by the mask919* {@code 0x8000000000000000L}) represents the sign of the920* floating-point number. Bits921* 62-52 (the bits that are selected by the mask922* {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0923* (the bits that are selected by the mask924* {@code 0x000fffffffffffffL}) represent the significand925* (sometimes called the mantissa) of the floating-point number.926*927* <p>If the argument is positive infinity, the result is928* {@code 0x7ff0000000000000L}.929*930* <p>If the argument is negative infinity, the result is931* {@code 0xfff0000000000000L}.932*933* <p>If the argument is NaN, the result is934* {@code 0x7ff8000000000000L}.935*936* <p>In all cases, the result is a {@code long} integer that, when937* given to the {@link #longBitsToDouble(long)} method, will produce a938* floating-point value the same as the argument to939* {@code doubleToLongBits} (except all NaN values are940* collapsed to a single "canonical" NaN value).941*942* @param value a {@code double} precision floating-point number.943* @return the bits that represent the floating-point number.944*/945@IntrinsicCandidate946public static long doubleToLongBits(double value) {947if (!isNaN(value)) {948return doubleToRawLongBits(value);949}950return 0x7ff8000000000000L;951}952953/**954* Returns a representation of the specified floating-point value955* according to the IEEE 754 floating-point "double956* format" bit layout, preserving Not-a-Number (NaN) values.957*958* <p>Bit 63 (the bit that is selected by the mask959* {@code 0x8000000000000000L}) represents the sign of the960* floating-point number. Bits961* 62-52 (the bits that are selected by the mask962* {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0963* (the bits that are selected by the mask964* {@code 0x000fffffffffffffL}) represent the significand965* (sometimes called the mantissa) of the floating-point number.966*967* <p>If the argument is positive infinity, the result is968* {@code 0x7ff0000000000000L}.969*970* <p>If the argument is negative infinity, the result is971* {@code 0xfff0000000000000L}.972*973* <p>If the argument is NaN, the result is the {@code long}974* integer representing the actual NaN value. Unlike the975* {@code doubleToLongBits} method,976* {@code doubleToRawLongBits} does not collapse all the bit977* patterns encoding a NaN to a single "canonical" NaN978* value.979*980* <p>In all cases, the result is a {@code long} integer that,981* when given to the {@link #longBitsToDouble(long)} method, will982* produce a floating-point value the same as the argument to983* {@code doubleToRawLongBits}.984*985* @param value a {@code double} precision floating-point number.986* @return the bits that represent the floating-point number.987* @since 1.3988*/989@IntrinsicCandidate990public static native long doubleToRawLongBits(double value);991992/**993* Returns the {@code double} value corresponding to a given994* bit representation.995* The argument is considered to be a representation of a996* floating-point value according to the IEEE 754 floating-point997* "double format" bit layout.998*999* <p>If the argument is {@code 0x7ff0000000000000L}, the result1000* is positive infinity.1001*1002* <p>If the argument is {@code 0xfff0000000000000L}, the result1003* is negative infinity.1004*1005* <p>If the argument is any value in the range1006* {@code 0x7ff0000000000001L} through1007* {@code 0x7fffffffffffffffL} or in the range1008* {@code 0xfff0000000000001L} through1009* {@code 0xffffffffffffffffL}, the result is a NaN. No IEEE1010* 754 floating-point operation provided by Java can distinguish1011* between two NaN values of the same type with different bit1012* patterns. Distinct values of NaN are only distinguishable by1013* use of the {@code Double.doubleToRawLongBits} method.1014*1015* <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three1016* values that can be computed from the argument:1017*1018* <blockquote><pre>{@code1019* int s = ((bits >> 63) == 0) ? 1 : -1;1020* int e = (int)((bits >> 52) & 0x7ffL);1021* long m = (e == 0) ?1022* (bits & 0xfffffffffffffL) << 1 :1023* (bits & 0xfffffffffffffL) | 0x10000000000000L;1024* }</pre></blockquote>1025*1026* Then the floating-point result equals the value of the mathematical1027* expression <i>s</i>·<i>m</i>·2<sup><i>e</i>-1075</sup>.1028*1029* <p>Note that this method may not be able to return a1030* {@code double} NaN with exactly same bit pattern as the1031* {@code long} argument. IEEE 754 distinguishes between two1032* kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>. The1033* differences between the two kinds of NaN are generally not1034* visible in Java. Arithmetic operations on signaling NaNs turn1035* them into quiet NaNs with a different, but often similar, bit1036* pattern. However, on some processors merely copying a1037* signaling NaN also performs that conversion. In particular,1038* copying a signaling NaN to return it to the calling method1039* may perform this conversion. So {@code longBitsToDouble}1040* may not be able to return a {@code double} with a1041* signaling NaN bit pattern. Consequently, for some1042* {@code long} values,1043* {@code doubleToRawLongBits(longBitsToDouble(start))} may1044* <i>not</i> equal {@code start}. Moreover, which1045* particular bit patterns represent signaling NaNs is platform1046* dependent; although all NaN bit patterns, quiet or signaling,1047* must be in the NaN range identified above.1048*1049* @param bits any {@code long} integer.1050* @return the {@code double} floating-point value with the same1051* bit pattern.1052*/1053@IntrinsicCandidate1054public static native double longBitsToDouble(long bits);10551056/**1057* Compares two {@code Double} objects numerically.1058*1059* This method imposes a total order on {@code Double} objects1060* with two differences compared to the incomplete order defined by1061* the Java language numerical comparison operators ({@code <, <=,1062* ==, >=, >}) on {@code double} values.1063*1064* <ul><li> A NaN is <em>unordered</em> with respect to other1065* values and unequal to itself under the comparison1066* operators. This method chooses to define {@code1067* Double.NaN} to be equal to itself and greater than all1068* other {@code double} values (including {@code1069* Double.POSITIVE_INFINITY}).1070*1071* <li> Positive zero and negative zero compare equal1072* numerically, but are distinct and distinguishable values.1073* This method chooses to define positive zero ({@code +0.0d}),1074* to be greater than negative zero ({@code -0.0d}).1075* </ul>10761077* This ensures that the <i>natural ordering</i> of {@code Double}1078* objects imposed by this method is <i>consistent with1079* equals</i>; see <a href="#equivalenceRelation">this1080* discussion</a> for details of floating-point comparison and1081* ordering.1082*1083* @param anotherDouble the {@code Double} to be compared.1084* @return the value {@code 0} if {@code anotherDouble} is1085* numerically equal to this {@code Double}; a value1086* less than {@code 0} if this {@code Double}1087* is numerically less than {@code anotherDouble};1088* and a value greater than {@code 0} if this1089* {@code Double} is numerically greater than1090* {@code anotherDouble}.1091*1092* @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}1093* @since 1.21094*/1095public int compareTo(Double anotherDouble) {1096return Double.compare(value, anotherDouble.value);1097}10981099/**1100* Compares the two specified {@code double} values. The sign1101* of the integer value returned is the same as that of the1102* integer that would be returned by the call:1103* <pre>1104* new Double(d1).compareTo(new Double(d2))1105* </pre>1106*1107* @param d1 the first {@code double} to compare1108* @param d2 the second {@code double} to compare1109* @return the value {@code 0} if {@code d1} is1110* numerically equal to {@code d2}; a value less than1111* {@code 0} if {@code d1} is numerically less than1112* {@code d2}; and a value greater than {@code 0}1113* if {@code d1} is numerically greater than1114* {@code d2}.1115* @since 1.41116*/1117public static int compare(double d1, double d2) {1118if (d1 < d2)1119return -1; // Neither val is NaN, thisVal is smaller1120if (d1 > d2)1121return 1; // Neither val is NaN, thisVal is larger11221123// Cannot use doubleToRawLongBits because of possibility of NaNs.1124long thisBits = Double.doubleToLongBits(d1);1125long anotherBits = Double.doubleToLongBits(d2);11261127return (thisBits == anotherBits ? 0 : // Values are equal1128(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)11291)); // (0.0, -0.0) or (NaN, !NaN)1130}11311132/**1133* Adds two {@code double} values together as per the + operator.1134*1135* @param a the first operand1136* @param b the second operand1137* @return the sum of {@code a} and {@code b}1138* @jls 4.2.4 Floating-Point Operations1139* @see java.util.function.BinaryOperator1140* @since 1.81141*/1142public static double sum(double a, double b) {1143return a + b;1144}11451146/**1147* Returns the greater of two {@code double} values1148* as if by calling {@link Math#max(double, double) Math.max}.1149*1150* @param a the first operand1151* @param b the second operand1152* @return the greater of {@code a} and {@code b}1153* @see java.util.function.BinaryOperator1154* @since 1.81155*/1156public static double max(double a, double b) {1157return Math.max(a, b);1158}11591160/**1161* Returns the smaller of two {@code double} values1162* as if by calling {@link Math#min(double, double) Math.min}.1163*1164* @param a the first operand1165* @param b the second operand1166* @return the smaller of {@code a} and {@code b}.1167* @see java.util.function.BinaryOperator1168* @since 1.81169*/1170public static double min(double a, double b) {1171return Math.min(a, b);1172}11731174/**1175* Returns an {@link Optional} containing the nominal descriptor for this1176* instance, which is the instance itself.1177*1178* @return an {@link Optional} describing the {@linkplain Double} instance1179* @since 121180*/1181@Override1182public Optional<Double> describeConstable() {1183return Optional.of(this);1184}11851186/**1187* Resolves this instance as a {@link ConstantDesc}, the result of which is1188* the instance itself.1189*1190* @param lookup ignored1191* @return the {@linkplain Double} instance1192* @since 121193*/1194@Override1195public Double resolveConstantDesc(MethodHandles.Lookup lookup) {1196return this;1197}11981199/** use serialVersionUID from JDK 1.0.2 for interoperability */1200@java.io.Serial1201private static final long serialVersionUID = -9172774392245257468L;1202}120312041205