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