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