Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/lang/Double.java
41152 views
1
/*
2
* Copyright (c) 1994, 2021, 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.vm.annotation.IntrinsicCandidate;
36
37
/**
38
* The {@code Double} class wraps a value of the primitive type
39
* {@code double} in an object. An object of type
40
* {@code Double} contains a single field whose type is
41
* {@code double}.
42
*
43
* <p>In addition, this class provides several methods for converting a
44
* {@code double} to a {@code String} and a
45
* {@code String} to a {@code double}, as well as other
46
* constants and methods useful when dealing with a
47
* {@code double}.
48
*
49
* <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
50
* class; programmers should treat instances that are
51
* {@linkplain #equals(Object) equal} as interchangeable and should not
52
* use instances for synchronization, or unpredictable behavior may
53
* occur. For example, in a future release, synchronization may fail.
54
*
55
* <h2><a id=equivalenceRelation>Floating-point Equality, Equivalence,
56
* and Comparison</a></h2>
57
*
58
* IEEE 754 floating-point values include finite nonzero values,
59
* signed zeros ({@code +0.0} and {@code -0.0}), signed infinities
60
* {@linkplain Double#POSITIVE_INFINITY positive infinity} and
61
* {@linkplain Double#NEGATIVE_INFINITY negative infinity}), and
62
* {@linkplain Double#NaN NaN} (not-a-number).
63
*
64
* <p>An <em>equivalence relation</em> on a set of values is a boolean
65
* relation on pairs of values that is reflexive, symmetric, and
66
* transitive. For more discussion of equivalence relations and object
67
* equality, see the {@link Object#equals Object.equals}
68
* specification. An equivalence relation partitions the values it
69
* operates over into sets called <i>equivalence classes</i>. All the
70
* members of the equivalence class are equal to each other under the
71
* relation. An equivalence class may contain only a single member. At
72
* least for some purposes, all the members of an equivalence class
73
* are substitutable for each other. In particular, in a numeric
74
* expression equivalent values can be <em>substituted</em> for one
75
* another without changing the result of the expression, meaning
76
* changing the equivalence class of the result of the expression.
77
*
78
* <p>Notably, the built-in {@code ==} operation on floating-point
79
* values is <em>not</em> an equivalence relation. Despite not
80
* defining an equivalence relation, the semantics of the IEEE 754
81
* {@code ==} operator were deliberately designed to meet other needs
82
* of numerical computation. There are two exceptions where the
83
* properties of an equivalence relation are not satisfied by {@code
84
* ==} on floating-point values:
85
*
86
* <ul>
87
*
88
* <li>If {@code v1} and {@code v2} are both NaN, then {@code v1
89
* == v2} has the value {@code false}. Therefore, for two NaN
90
* arguments the <em>reflexive</em> property of an equivalence
91
* relation is <em>not</em> satisfied by the {@code ==} operator.
92
*
93
* <li>If {@code v1} represents {@code +0.0} while {@code v2}
94
* represents {@code -0.0}, or vice versa, then {@code v1 == v2} has
95
* the value {@code true} even though {@code +0.0} and {@code -0.0}
96
* are distinguishable under various floating-point operations. For
97
* example, {@code 1.0/+0.0} evaluates to positive infinity while
98
* {@code 1.0/-0.0} evaluates to <em>negative</em> infinity and
99
* positive infinity and negative infinity are neither equal to each
100
* other nor equivalent to each other. Thus, while a signed zero input
101
* most commonly determines the sign of a zero result, because of
102
* dividing by zero, {@code +0.0} and {@code -0.0} may not be
103
* substituted for each other in general. The sign of a zero input
104
* also has a non-substitutable effect on the result of some math
105
* library methods.
106
*
107
* </ul>
108
*
109
* <p>For ordered comparisons using the built-in comparison operators
110
* ({@code <}, {@code <=}, etc.), NaN values have another anomalous
111
* situation: a NaN is neither less than, nor greater than, nor equal
112
* to any value, including itself. This means the <i>trichotomy of
113
* comparison</i> does <em>not</em> hold.
114
*
115
* <p>To provide the appropriate semantics for {@code equals} and
116
* {@code compareTo} methods, those methods cannot simply be wrappers
117
* around {@code ==} or ordered comparison operations. Instead, {@link
118
* Double#equals equals} defines NaN arguments to be equal to each
119
* other and defines {@code +0.0} to <em>not</em> be equal to {@code
120
* -0.0}, restoring reflexivity. For comparisons, {@link
121
* Double#compareTo compareTo} defines a total order where {@code
122
* -0.0} is less than {@code +0.0} and where a NaN is equal to itself
123
* and considered greater than positive infinity.
124
*
125
* <p>The operational semantics of {@code equals} and {@code
126
* compareTo} are expressed in terms of {@linkplain #doubleToLongBits
127
* bit-wise converting} the floating-point values to integral values.
128
*
129
* <p>The <em>natural ordering</em> implemented by {@link #compareTo
130
* compareTo} is {@linkplain Comparable consistent with equals}. That
131
* is, two objects are reported as equal by {@code equals} if and only
132
* if {@code compareTo} on those objects returns zero.
133
*
134
* <p>The adjusted behaviors defined for {@code equals} and {@code
135
* compareTo} allow instances of wrapper classes to work properly with
136
* conventional data structures. For example, defining NaN
137
* values to be {@code equals} to one another allows NaN to be used as
138
* an element of a {@link java.util.HashSet HashSet} or as the key of
139
* a {@link java.util.HashMap HashMap}. Similarly, defining {@code
140
* compareTo} as a total ordering, including {@code +0.0}, {@code
141
* -0.0}, and NaN, allows instances of wrapper classes to be used as
142
* elements of a {@link java.util.SortedSet SortedSet} or as keys of a
143
* {@link java.util.SortedMap SortedMap}.
144
*
145
* @jls 4.2.3 Floating-Point Types, Formats, and Values
146
* @jls 4.2.4. Floating-Point Operations
147
* @jls 15.21.1 Numerical Equality Operators == and !=
148
* @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
149
*
150
* @author Lee Boynton
151
* @author Arthur van Hoff
152
* @author Joseph D. Darcy
153
* @since 1.0
154
*/
155
@jdk.internal.ValueBased
156
public final class Double extends Number
157
implements Comparable<Double>, Constable, ConstantDesc {
158
/**
159
* A constant holding the positive infinity of type
160
* {@code double}. It is equal to the value returned by
161
* {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
162
*/
163
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
164
165
/**
166
* A constant holding the negative infinity of type
167
* {@code double}. It is equal to the value returned by
168
* {@code Double.longBitsToDouble(0xfff0000000000000L)}.
169
*/
170
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
171
172
/**
173
* A constant holding a Not-a-Number (NaN) value of type
174
* {@code double}. It is equivalent to the value returned by
175
* {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
176
*/
177
public static final double NaN = 0.0d / 0.0;
178
179
/**
180
* A constant holding the largest positive finite value of type
181
* {@code double},
182
* (2-2<sup>-52</sup>)&middot;2<sup>1023</sup>. It is equal to
183
* the hexadecimal floating-point literal
184
* {@code 0x1.fffffffffffffP+1023} and also equal to
185
* {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
186
*/
187
public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308
188
189
/**
190
* A constant holding the smallest positive normal value of type
191
* {@code double}, 2<sup>-1022</sup>. It is equal to the
192
* hexadecimal floating-point literal {@code 0x1.0p-1022} and also
193
* equal to {@code Double.longBitsToDouble(0x0010000000000000L)}.
194
*
195
* @since 1.6
196
*/
197
public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308
198
199
/**
200
* A constant holding the smallest positive nonzero value of type
201
* {@code double}, 2<sup>-1074</sup>. It is equal to the
202
* hexadecimal floating-point literal
203
* {@code 0x0.0000000000001P-1022} and also equal to
204
* {@code Double.longBitsToDouble(0x1L)}.
205
*/
206
public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324
207
208
/**
209
* Maximum exponent a finite {@code double} variable may have.
210
* It is equal to the value returned by
211
* {@code Math.getExponent(Double.MAX_VALUE)}.
212
*
213
* @since 1.6
214
*/
215
public static final int MAX_EXPONENT = 1023;
216
217
/**
218
* Minimum exponent a normalized {@code double} variable may
219
* have. It is equal to the value returned by
220
* {@code Math.getExponent(Double.MIN_NORMAL)}.
221
*
222
* @since 1.6
223
*/
224
public static final int MIN_EXPONENT = -1022;
225
226
/**
227
* The number of bits used to represent a {@code double} value.
228
*
229
* @since 1.5
230
*/
231
public static final int SIZE = 64;
232
233
/**
234
* The number of bytes used to represent a {@code double} value.
235
*
236
* @since 1.8
237
*/
238
public static final int BYTES = SIZE / Byte.SIZE;
239
240
/**
241
* The {@code Class} instance representing the primitive type
242
* {@code double}.
243
*
244
* @since 1.1
245
*/
246
@SuppressWarnings("unchecked")
247
public static final Class<Double> TYPE = (Class<Double>) Class.getPrimitiveClass("double");
248
249
/**
250
* Returns a string representation of the {@code double}
251
* argument. All characters mentioned below are ASCII characters.
252
* <ul>
253
* <li>If the argument is NaN, the result is the string
254
* "{@code NaN}".
255
* <li>Otherwise, the result is a string that represents the sign and
256
* magnitude (absolute value) of the argument. If the sign is negative,
257
* the first character of the result is '{@code -}'
258
* ({@code '\u005Cu002D'}); if the sign is positive, no sign character
259
* appears in the result. As for the magnitude <i>m</i>:
260
* <ul>
261
* <li>If <i>m</i> is infinity, it is represented by the characters
262
* {@code "Infinity"}; thus, positive infinity produces the result
263
* {@code "Infinity"} and negative infinity produces the result
264
* {@code "-Infinity"}.
265
*
266
* <li>If <i>m</i> is zero, it is represented by the characters
267
* {@code "0.0"}; thus, negative zero produces the result
268
* {@code "-0.0"} and positive zero produces the result
269
* {@code "0.0"}.
270
*
271
* <li>If <i>m</i> is greater than or equal to 10<sup>-3</sup> but less
272
* than 10<sup>7</sup>, then it is represented as the integer part of
273
* <i>m</i>, in decimal form with no leading zeroes, followed by
274
* '{@code .}' ({@code '\u005Cu002E'}), followed by one or
275
* more decimal digits representing the fractional part of <i>m</i>.
276
*
277
* <li>If <i>m</i> is less than 10<sup>-3</sup> or greater than or
278
* equal to 10<sup>7</sup>, then it is represented in so-called
279
* "computerized scientific notation." Let <i>n</i> be the unique
280
* integer such that 10<sup><i>n</i></sup> &le; <i>m</i> {@literal <}
281
* 10<sup><i>n</i>+1</sup>; then let <i>a</i> be the
282
* mathematically exact quotient of <i>m</i> and
283
* 10<sup><i>n</i></sup> so that 1 &le; <i>a</i> {@literal <} 10. The
284
* magnitude is then represented as the integer part of <i>a</i>,
285
* as a single decimal digit, followed by '{@code .}'
286
* ({@code '\u005Cu002E'}), followed by decimal digits
287
* representing the fractional part of <i>a</i>, followed by the
288
* letter '{@code E}' ({@code '\u005Cu0045'}), followed
289
* by a representation of <i>n</i> as a decimal integer, as
290
* produced by the method {@link Integer#toString(int)}.
291
* </ul>
292
* </ul>
293
* How many digits must be printed for the fractional part of
294
* <i>m</i> or <i>a</i>? There must be at least one digit to represent
295
* the fractional part, and beyond that as many, but only as many, more
296
* digits as are needed to uniquely distinguish the argument value from
297
* adjacent values of type {@code double}. That is, suppose that
298
* <i>x</i> is the exact mathematical value represented by the decimal
299
* representation produced by this method for a finite nonzero argument
300
* <i>d</i>. Then <i>d</i> must be the {@code double} value nearest
301
* to <i>x</i>; or if two {@code double} values are equally close
302
* to <i>x</i>, then <i>d</i> must be one of them and the least
303
* significant bit of the significand of <i>d</i> must be {@code 0}.
304
*
305
* <p>To create localized string representations of a floating-point
306
* value, use subclasses of {@link java.text.NumberFormat}.
307
*
308
* @param d the {@code double} to be converted.
309
* @return a string representation of the argument.
310
*/
311
public static String toString(double d) {
312
return FloatingDecimal.toJavaFormatString(d);
313
}
314
315
/**
316
* Returns a hexadecimal string representation of the
317
* {@code double} argument. All characters mentioned below
318
* are ASCII characters.
319
*
320
* <ul>
321
* <li>If the argument is NaN, the result is the string
322
* "{@code NaN}".
323
* <li>Otherwise, the result is a string that represents the sign
324
* and magnitude of the argument. If the sign is negative, the
325
* first character of the result is '{@code -}'
326
* ({@code '\u005Cu002D'}); if the sign is positive, no sign
327
* character appears in the result. As for the magnitude <i>m</i>:
328
*
329
* <ul>
330
* <li>If <i>m</i> is infinity, it is represented by the string
331
* {@code "Infinity"}; thus, positive infinity produces the
332
* result {@code "Infinity"} and negative infinity produces
333
* the result {@code "-Infinity"}.
334
*
335
* <li>If <i>m</i> is zero, it is represented by the string
336
* {@code "0x0.0p0"}; thus, negative zero produces the result
337
* {@code "-0x0.0p0"} and positive zero produces the result
338
* {@code "0x0.0p0"}.
339
*
340
* <li>If <i>m</i> is a {@code double} value with a
341
* normalized representation, substrings are used to represent the
342
* significand and exponent fields. The significand is
343
* represented by the characters {@code "0x1."}
344
* followed by a lowercase hexadecimal representation of the rest
345
* of the significand as a fraction. Trailing zeros in the
346
* hexadecimal representation are removed unless all the digits
347
* are zero, in which case a single zero is used. Next, the
348
* exponent is represented by {@code "p"} followed
349
* by a decimal string of the unbiased exponent as if produced by
350
* a call to {@link Integer#toString(int) Integer.toString} on the
351
* exponent value.
352
*
353
* <li>If <i>m</i> is a {@code double} value with a subnormal
354
* representation, the significand is represented by the
355
* characters {@code "0x0."} followed by a
356
* hexadecimal representation of the rest of the significand as a
357
* fraction. Trailing zeros in the hexadecimal representation are
358
* removed. Next, the exponent is represented by
359
* {@code "p-1022"}. Note that there must be at
360
* least one nonzero digit in a subnormal significand.
361
*
362
* </ul>
363
*
364
* </ul>
365
*
366
* <table class="striped">
367
* <caption>Examples</caption>
368
* <thead>
369
* <tr><th scope="col">Floating-point Value</th><th scope="col">Hexadecimal String</th>
370
* </thead>
371
* <tbody style="text-align:right">
372
* <tr><th scope="row">{@code 1.0}</th> <td>{@code 0x1.0p0}</td>
373
* <tr><th scope="row">{@code -1.0}</th> <td>{@code -0x1.0p0}</td>
374
* <tr><th scope="row">{@code 2.0}</th> <td>{@code 0x1.0p1}</td>
375
* <tr><th scope="row">{@code 3.0}</th> <td>{@code 0x1.8p1}</td>
376
* <tr><th scope="row">{@code 0.5}</th> <td>{@code 0x1.0p-1}</td>
377
* <tr><th scope="row">{@code 0.25}</th> <td>{@code 0x1.0p-2}</td>
378
* <tr><th scope="row">{@code Double.MAX_VALUE}</th>
379
* <td>{@code 0x1.fffffffffffffp1023}</td>
380
* <tr><th scope="row">{@code Minimum Normal Value}</th>
381
* <td>{@code 0x1.0p-1022}</td>
382
* <tr><th scope="row">{@code Maximum Subnormal Value}</th>
383
* <td>{@code 0x0.fffffffffffffp-1022}</td>
384
* <tr><th scope="row">{@code Double.MIN_VALUE}</th>
385
* <td>{@code 0x0.0000000000001p-1022}</td>
386
* </tbody>
387
* </table>
388
* @param d the {@code double} to be converted.
389
* @return a hex string representation of the argument.
390
* @since 1.5
391
* @author Joseph D. Darcy
392
*/
393
public static String toHexString(double d) {
394
/*
395
* Modeled after the "a" conversion specifier in C99, section
396
* 7.19.6.1; however, the output of this method is more
397
* tightly specified.
398
*/
399
if (!isFinite(d) )
400
// For infinity and NaN, use the decimal output.
401
return Double.toString(d);
402
else {
403
// Initialized to maximum size of output.
404
StringBuilder answer = new StringBuilder(24);
405
406
if (Math.copySign(1.0, d) == -1.0) // value is negative,
407
answer.append("-"); // so append sign info
408
409
answer.append("0x");
410
411
d = Math.abs(d);
412
413
if(d == 0.0) {
414
answer.append("0.0p0");
415
} else {
416
boolean subnormal = (d < Double.MIN_NORMAL);
417
418
// Isolate significand bits and OR in a high-order bit
419
// so that the string representation has a known
420
// length.
421
long signifBits = (Double.doubleToLongBits(d)
422
& DoubleConsts.SIGNIF_BIT_MASK) |
423
0x1000000000000000L;
424
425
// Subnormal values have a 0 implicit bit; normal
426
// values have a 1 implicit bit.
427
answer.append(subnormal ? "0." : "1.");
428
429
// Isolate the low-order 13 digits of the hex
430
// representation. If all the digits are zero,
431
// replace with a single 0; otherwise, remove all
432
// trailing zeros.
433
String signif = Long.toHexString(signifBits).substring(3,16);
434
answer.append(signif.equals("0000000000000") ? // 13 zeros
435
"0":
436
signif.replaceFirst("0{1,12}$", ""));
437
438
answer.append('p');
439
// If the value is subnormal, use the E_min exponent
440
// value for double; otherwise, extract and report d's
441
// exponent (the representation of a subnormal uses
442
// E_min -1).
443
answer.append(subnormal ?
444
Double.MIN_EXPONENT:
445
Math.getExponent(d));
446
}
447
return answer.toString();
448
}
449
}
450
451
/**
452
* Returns a {@code Double} object holding the
453
* {@code double} value represented by the argument string
454
* {@code s}.
455
*
456
* <p>If {@code s} is {@code null}, then a
457
* {@code NullPointerException} is thrown.
458
*
459
* <p>Leading and trailing whitespace characters in {@code s}
460
* are ignored. Whitespace is removed as if by the {@link
461
* String#trim} method; that is, both ASCII space and control
462
* characters are removed. The rest of {@code s} should
463
* constitute a <i>FloatValue</i> as described by the lexical
464
* syntax rules:
465
*
466
* <blockquote>
467
* <dl>
468
* <dt><i>FloatValue:</i>
469
* <dd><i>Sign<sub>opt</sub></i> {@code NaN}
470
* <dd><i>Sign<sub>opt</sub></i> {@code Infinity}
471
* <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i>
472
* <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i>
473
* <dd><i>SignedInteger</i>
474
* </dl>
475
*
476
* <dl>
477
* <dt><i>HexFloatingPointLiteral</i>:
478
* <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i>
479
* </dl>
480
*
481
* <dl>
482
* <dt><i>HexSignificand:</i>
483
* <dd><i>HexNumeral</i>
484
* <dd><i>HexNumeral</i> {@code .}
485
* <dd>{@code 0x} <i>HexDigits<sub>opt</sub>
486
* </i>{@code .}<i> HexDigits</i>
487
* <dd>{@code 0X}<i> HexDigits<sub>opt</sub>
488
* </i>{@code .} <i>HexDigits</i>
489
* </dl>
490
*
491
* <dl>
492
* <dt><i>BinaryExponent:</i>
493
* <dd><i>BinaryExponentIndicator SignedInteger</i>
494
* </dl>
495
*
496
* <dl>
497
* <dt><i>BinaryExponentIndicator:</i>
498
* <dd>{@code p}
499
* <dd>{@code P}
500
* </dl>
501
*
502
* </blockquote>
503
*
504
* where <i>Sign</i>, <i>FloatingPointLiteral</i>,
505
* <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and
506
* <i>FloatTypeSuffix</i> are as defined in the lexical structure
507
* sections of
508
* <cite>The Java Language Specification</cite>,
509
* except that underscores are not accepted between digits.
510
* If {@code s} does not have the form of
511
* a <i>FloatValue</i>, then a {@code NumberFormatException}
512
* is thrown. Otherwise, {@code s} is regarded as
513
* representing an exact decimal value in the usual
514
* "computerized scientific notation" or as an exact
515
* hexadecimal value; this exact numerical value is then
516
* conceptually converted to an "infinitely precise"
517
* binary value that is then rounded to type {@code double}
518
* by the usual round-to-nearest rule of IEEE 754 floating-point
519
* arithmetic, which includes preserving the sign of a zero
520
* value.
521
*
522
* Note that the round-to-nearest rule also implies overflow and
523
* underflow behaviour; if the exact value of {@code s} is large
524
* enough in magnitude (greater than or equal to ({@link
525
* #MAX_VALUE} + {@link Math#ulp(double) ulp(MAX_VALUE)}/2),
526
* rounding to {@code double} will result in an infinity and if the
527
* exact value of {@code s} is small enough in magnitude (less
528
* than or equal to {@link #MIN_VALUE}/2), rounding to float will
529
* result in a zero.
530
*
531
* Finally, after rounding a {@code Double} object representing
532
* this {@code double} value is returned.
533
*
534
* <p> To interpret localized string representations of a
535
* floating-point value, use subclasses of {@link
536
* java.text.NumberFormat}.
537
*
538
* <p>Note that trailing format specifiers, specifiers that
539
* determine the type of a floating-point literal
540
* ({@code 1.0f} is a {@code float} value;
541
* {@code 1.0d} is a {@code double} value), do
542
* <em>not</em> influence the results of this method. In other
543
* words, the numerical value of the input string is converted
544
* directly to the target floating-point type. The two-step
545
* sequence of conversions, string to {@code float} followed
546
* by {@code float} to {@code double}, is <em>not</em>
547
* equivalent to converting a string directly to
548
* {@code double}. For example, the {@code float}
549
* literal {@code 0.1f} is equal to the {@code double}
550
* value {@code 0.10000000149011612}; the {@code float}
551
* literal {@code 0.1f} represents a different numerical
552
* value than the {@code double} literal
553
* {@code 0.1}. (The numerical value 0.1 cannot be exactly
554
* represented in a binary floating-point number.)
555
*
556
* <p>To avoid calling this method on an invalid string and having
557
* a {@code NumberFormatException} be thrown, the regular
558
* expression below can be used to screen the input string:
559
*
560
* <pre>{@code
561
* final String Digits = "(\\p{Digit}+)";
562
* final String HexDigits = "(\\p{XDigit}+)";
563
* // an exponent is 'e' or 'E' followed by an optionally
564
* // signed decimal integer.
565
* final String Exp = "[eE][+-]?"+Digits;
566
* final String fpRegex =
567
* ("[\\x00-\\x20]*"+ // Optional leading "whitespace"
568
* "[+-]?(" + // Optional sign character
569
* "NaN|" + // "NaN" string
570
* "Infinity|" + // "Infinity" string
571
*
572
* // A decimal floating-point string representing a finite positive
573
* // number without a leading sign has at most five basic pieces:
574
* // Digits . Digits ExponentPart FloatTypeSuffix
575
* //
576
* // Since this method allows integer-only strings as input
577
* // in addition to strings of floating-point literals, the
578
* // two sub-patterns below are simplifications of the grammar
579
* // productions from section 3.10.2 of
580
* // The Java Language Specification.
581
*
582
* // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
583
* "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
584
*
585
* // . Digits ExponentPart_opt FloatTypeSuffix_opt
586
* "(\\.("+Digits+")("+Exp+")?)|"+
587
*
588
* // Hexadecimal strings
589
* "((" +
590
* // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
591
* "(0[xX]" + HexDigits + "(\\.)?)|" +
592
*
593
* // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
594
* "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
595
*
596
* ")[pP][+-]?" + Digits + "))" +
597
* "[fFdD]?))" +
598
* "[\\x00-\\x20]*");// Optional trailing "whitespace"
599
*
600
* if (Pattern.matches(fpRegex, myString))
601
* Double.valueOf(myString); // Will not throw NumberFormatException
602
* else {
603
* // Perform suitable alternative action
604
* }
605
* }</pre>
606
*
607
* @param s the string to be parsed.
608
* @return a {@code Double} object holding the value
609
* represented by the {@code String} argument.
610
* @throws NumberFormatException if the string does not contain a
611
* parsable number.
612
*/
613
public static Double valueOf(String s) throws NumberFormatException {
614
return new Double(parseDouble(s));
615
}
616
617
/**
618
* Returns a {@code Double} instance representing the specified
619
* {@code double} value.
620
* If a new {@code Double} instance is not required, this method
621
* should generally be used in preference to the constructor
622
* {@link #Double(double)}, as this method is likely to yield
623
* significantly better space and time performance by caching
624
* frequently requested values.
625
*
626
* @param d a double value.
627
* @return a {@code Double} instance representing {@code d}.
628
* @since 1.5
629
*/
630
@IntrinsicCandidate
631
public static Double valueOf(double d) {
632
return new Double(d);
633
}
634
635
/**
636
* Returns a new {@code double} initialized to the value
637
* represented by the specified {@code String}, as performed
638
* by the {@code valueOf} method of class
639
* {@code Double}.
640
*
641
* @param s the string to be parsed.
642
* @return the {@code double} value represented by the string
643
* argument.
644
* @throws NullPointerException if the string is null
645
* @throws NumberFormatException if the string does not contain
646
* a parsable {@code double}.
647
* @see java.lang.Double#valueOf(String)
648
* @since 1.2
649
*/
650
public static double parseDouble(String s) throws NumberFormatException {
651
return FloatingDecimal.parseDouble(s);
652
}
653
654
/**
655
* Returns {@code true} if the specified number is a
656
* Not-a-Number (NaN) value, {@code false} otherwise.
657
*
658
* @param v the value to be tested.
659
* @return {@code true} if the value of the argument is NaN;
660
* {@code false} otherwise.
661
*/
662
public static boolean isNaN(double v) {
663
return (v != v);
664
}
665
666
/**
667
* Returns {@code true} if the specified number is infinitely
668
* large in magnitude, {@code false} otherwise.
669
*
670
* @param v the value to be tested.
671
* @return {@code true} if the value of the argument is positive
672
* infinity or negative infinity; {@code false} otherwise.
673
*/
674
public static boolean isInfinite(double v) {
675
return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY);
676
}
677
678
/**
679
* Returns {@code true} if the argument is a finite floating-point
680
* value; returns {@code false} otherwise (for NaN and infinity
681
* arguments).
682
*
683
* @param d the {@code double} value to be tested
684
* @return {@code true} if the argument is a finite
685
* floating-point value, {@code false} otherwise.
686
* @since 1.8
687
*/
688
public static boolean isFinite(double d) {
689
return Math.abs(d) <= Double.MAX_VALUE;
690
}
691
692
/**
693
* The value of the Double.
694
*
695
* @serial
696
*/
697
private final double value;
698
699
/**
700
* Constructs a newly allocated {@code Double} object that
701
* represents the primitive {@code double} argument.
702
*
703
* @param value the value to be represented by the {@code Double}.
704
*
705
* @deprecated
706
* It is rarely appropriate to use this constructor. The static factory
707
* {@link #valueOf(double)} is generally a better choice, as it is
708
* likely to yield significantly better space and time performance.
709
*/
710
@Deprecated(since="9", forRemoval = true)
711
public Double(double value) {
712
this.value = value;
713
}
714
715
/**
716
* Constructs a newly allocated {@code Double} object that
717
* represents the floating-point value of type {@code double}
718
* represented by the string. The string is converted to a
719
* {@code double} value as if by the {@code valueOf} method.
720
*
721
* @param s a string to be converted to a {@code Double}.
722
* @throws NumberFormatException if the string does not contain a
723
* parsable number.
724
*
725
* @deprecated
726
* It is rarely appropriate to use this constructor.
727
* Use {@link #parseDouble(String)} to convert a string to a
728
* {@code double} primitive, or use {@link #valueOf(String)}
729
* to convert a string to a {@code Double} object.
730
*/
731
@Deprecated(since="9", forRemoval = true)
732
public Double(String s) throws NumberFormatException {
733
value = parseDouble(s);
734
}
735
736
/**
737
* Returns {@code true} if this {@code Double} value is
738
* a Not-a-Number (NaN), {@code false} otherwise.
739
*
740
* @return {@code true} if the value represented by this object is
741
* NaN; {@code false} otherwise.
742
*/
743
public boolean isNaN() {
744
return isNaN(value);
745
}
746
747
/**
748
* Returns {@code true} if this {@code Double} value is
749
* infinitely large in magnitude, {@code false} otherwise.
750
*
751
* @return {@code true} if the value represented by this object is
752
* positive infinity or negative infinity;
753
* {@code false} otherwise.
754
*/
755
public boolean isInfinite() {
756
return isInfinite(value);
757
}
758
759
/**
760
* Returns a string representation of this {@code Double} object.
761
* The primitive {@code double} value represented by this
762
* object is converted to a string exactly as if by the method
763
* {@code toString} of one argument.
764
*
765
* @return a {@code String} representation of this object.
766
* @see java.lang.Double#toString(double)
767
*/
768
public String toString() {
769
return toString(value);
770
}
771
772
/**
773
* Returns the value of this {@code Double} as a {@code byte}
774
* after a narrowing primitive conversion.
775
*
776
* @return the {@code double} value represented by this object
777
* converted to type {@code byte}
778
* @jls 5.1.3 Narrowing Primitive Conversion
779
* @since 1.1
780
*/
781
public byte byteValue() {
782
return (byte)value;
783
}
784
785
/**
786
* Returns the value of this {@code Double} as a {@code short}
787
* after a narrowing primitive conversion.
788
*
789
* @return the {@code double} value represented by this object
790
* converted to type {@code short}
791
* @jls 5.1.3 Narrowing Primitive Conversion
792
* @since 1.1
793
*/
794
public short shortValue() {
795
return (short)value;
796
}
797
798
/**
799
* Returns the value of this {@code Double} as an {@code int}
800
* after a narrowing primitive conversion.
801
* @jls 5.1.3 Narrowing Primitive Conversion
802
*
803
* @return the {@code double} value represented by this object
804
* converted to type {@code int}
805
*/
806
public int intValue() {
807
return (int)value;
808
}
809
810
/**
811
* Returns the value of this {@code Double} as a {@code long}
812
* after a narrowing primitive conversion.
813
*
814
* @return the {@code double} value represented by this object
815
* converted to type {@code long}
816
* @jls 5.1.3 Narrowing Primitive Conversion
817
*/
818
public long longValue() {
819
return (long)value;
820
}
821
822
/**
823
* Returns the value of this {@code Double} as a {@code float}
824
* after a narrowing primitive conversion.
825
*
826
* @return the {@code double} value represented by this object
827
* converted to type {@code float}
828
* @jls 5.1.3 Narrowing Primitive Conversion
829
* @since 1.0
830
*/
831
public float floatValue() {
832
return (float)value;
833
}
834
835
/**
836
* Returns the {@code double} value of this {@code Double} object.
837
*
838
* @return the {@code double} value represented by this object
839
*/
840
@IntrinsicCandidate
841
public double doubleValue() {
842
return value;
843
}
844
845
/**
846
* Returns a hash code for this {@code Double} object. The
847
* result is the exclusive OR of the two halves of the
848
* {@code long} integer bit representation, exactly as
849
* produced by the method {@link #doubleToLongBits(double)}, of
850
* the primitive {@code double} value represented by this
851
* {@code Double} object. That is, the hash code is the value
852
* of the expression:
853
*
854
* <blockquote>
855
* {@code (int)(v^(v>>>32))}
856
* </blockquote>
857
*
858
* where {@code v} is defined by:
859
*
860
* <blockquote>
861
* {@code long v = Double.doubleToLongBits(this.doubleValue());}
862
* </blockquote>
863
*
864
* @return a {@code hash code} value for this object.
865
*/
866
@Override
867
public int hashCode() {
868
return Double.hashCode(value);
869
}
870
871
/**
872
* Returns a hash code for a {@code double} value; compatible with
873
* {@code Double.hashCode()}.
874
*
875
* @param value the value to hash
876
* @return a hash code value for a {@code double} value.
877
* @since 1.8
878
*/
879
public static int hashCode(double value) {
880
long bits = doubleToLongBits(value);
881
return (int)(bits ^ (bits >>> 32));
882
}
883
884
/**
885
* Compares this object against the specified object. The result
886
* is {@code true} if and only if the argument is not
887
* {@code null} and is a {@code Double} object that
888
* represents a {@code double} that has the same value as the
889
* {@code double} represented by this object. For this
890
* purpose, two {@code double} values are considered to be
891
* the same if and only if the method {@link
892
* #doubleToLongBits(double)} returns the identical
893
* {@code long} value when applied to each.
894
*
895
* @apiNote
896
* This method is defined in terms of {@link
897
* #doubleToLongBits(double)} rather than the {@code ==} operator
898
* on {@code double} values since the {@code ==} operator does
899
* <em>not</em> define an equivalence relation and to satisfy the
900
* {@linkplain Object#equals equals contract} an equivalence
901
* relation must be implemented; see <a
902
* href="#equivalenceRelation">this discussion</a> for details of
903
* floating-point equality and equivalence.
904
*
905
* @see java.lang.Double#doubleToLongBits(double)
906
* @jls 15.21.1 Numerical Equality Operators == and !=
907
*/
908
public boolean equals(Object obj) {
909
return (obj instanceof Double)
910
&& (doubleToLongBits(((Double)obj).value) ==
911
doubleToLongBits(value));
912
}
913
914
/**
915
* Returns a representation of the specified floating-point value
916
* according to the IEEE 754 floating-point "double
917
* format" bit layout.
918
*
919
* <p>Bit 63 (the bit that is selected by the mask
920
* {@code 0x8000000000000000L}) represents the sign of the
921
* floating-point number. Bits
922
* 62-52 (the bits that are selected by the mask
923
* {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
924
* (the bits that are selected by the mask
925
* {@code 0x000fffffffffffffL}) represent the significand
926
* (sometimes called the mantissa) of the floating-point number.
927
*
928
* <p>If the argument is positive infinity, the result is
929
* {@code 0x7ff0000000000000L}.
930
*
931
* <p>If the argument is negative infinity, the result is
932
* {@code 0xfff0000000000000L}.
933
*
934
* <p>If the argument is NaN, the result is
935
* {@code 0x7ff8000000000000L}.
936
*
937
* <p>In all cases, the result is a {@code long} integer that, when
938
* given to the {@link #longBitsToDouble(long)} method, will produce a
939
* floating-point value the same as the argument to
940
* {@code doubleToLongBits} (except all NaN values are
941
* collapsed to a single "canonical" NaN value).
942
*
943
* @param value a {@code double} precision floating-point number.
944
* @return the bits that represent the floating-point number.
945
*/
946
@IntrinsicCandidate
947
public static long doubleToLongBits(double value) {
948
if (!isNaN(value)) {
949
return doubleToRawLongBits(value);
950
}
951
return 0x7ff8000000000000L;
952
}
953
954
/**
955
* Returns a representation of the specified floating-point value
956
* according to the IEEE 754 floating-point "double
957
* format" bit layout, preserving Not-a-Number (NaN) values.
958
*
959
* <p>Bit 63 (the bit that is selected by the mask
960
* {@code 0x8000000000000000L}) represents the sign of the
961
* floating-point number. Bits
962
* 62-52 (the bits that are selected by the mask
963
* {@code 0x7ff0000000000000L}) represent the exponent. Bits 51-0
964
* (the bits that are selected by the mask
965
* {@code 0x000fffffffffffffL}) represent the significand
966
* (sometimes called the mantissa) of the floating-point number.
967
*
968
* <p>If the argument is positive infinity, the result is
969
* {@code 0x7ff0000000000000L}.
970
*
971
* <p>If the argument is negative infinity, the result is
972
* {@code 0xfff0000000000000L}.
973
*
974
* <p>If the argument is NaN, the result is the {@code long}
975
* integer representing the actual NaN value. Unlike the
976
* {@code doubleToLongBits} method,
977
* {@code doubleToRawLongBits} does not collapse all the bit
978
* patterns encoding a NaN to a single "canonical" NaN
979
* value.
980
*
981
* <p>In all cases, the result is a {@code long} integer that,
982
* when given to the {@link #longBitsToDouble(long)} method, will
983
* produce a floating-point value the same as the argument to
984
* {@code doubleToRawLongBits}.
985
*
986
* @param value a {@code double} precision floating-point number.
987
* @return the bits that represent the floating-point number.
988
* @since 1.3
989
*/
990
@IntrinsicCandidate
991
public static native long doubleToRawLongBits(double value);
992
993
/**
994
* Returns the {@code double} value corresponding to a given
995
* bit representation.
996
* The argument is considered to be a representation of a
997
* floating-point value according to the IEEE 754 floating-point
998
* "double format" bit layout.
999
*
1000
* <p>If the argument is {@code 0x7ff0000000000000L}, the result
1001
* is positive infinity.
1002
*
1003
* <p>If the argument is {@code 0xfff0000000000000L}, the result
1004
* is negative infinity.
1005
*
1006
* <p>If the argument is any value in the range
1007
* {@code 0x7ff0000000000001L} through
1008
* {@code 0x7fffffffffffffffL} or in the range
1009
* {@code 0xfff0000000000001L} through
1010
* {@code 0xffffffffffffffffL}, the result is a NaN. No IEEE
1011
* 754 floating-point operation provided by Java can distinguish
1012
* between two NaN values of the same type with different bit
1013
* patterns. Distinct values of NaN are only distinguishable by
1014
* use of the {@code Double.doubleToRawLongBits} method.
1015
*
1016
* <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three
1017
* values that can be computed from the argument:
1018
*
1019
* <blockquote><pre>{@code
1020
* int s = ((bits >> 63) == 0) ? 1 : -1;
1021
* int e = (int)((bits >> 52) & 0x7ffL);
1022
* long m = (e == 0) ?
1023
* (bits & 0xfffffffffffffL) << 1 :
1024
* (bits & 0xfffffffffffffL) | 0x10000000000000L;
1025
* }</pre></blockquote>
1026
*
1027
* Then the floating-point result equals the value of the mathematical
1028
* expression <i>s</i>&middot;<i>m</i>&middot;2<sup><i>e</i>-1075</sup>.
1029
*
1030
* <p>Note that this method may not be able to return a
1031
* {@code double} NaN with exactly same bit pattern as the
1032
* {@code long} argument. IEEE 754 distinguishes between two
1033
* kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>. The
1034
* differences between the two kinds of NaN are generally not
1035
* visible in Java. Arithmetic operations on signaling NaNs turn
1036
* them into quiet NaNs with a different, but often similar, bit
1037
* pattern. However, on some processors merely copying a
1038
* signaling NaN also performs that conversion. In particular,
1039
* copying a signaling NaN to return it to the calling method
1040
* may perform this conversion. So {@code longBitsToDouble}
1041
* may not be able to return a {@code double} with a
1042
* signaling NaN bit pattern. Consequently, for some
1043
* {@code long} values,
1044
* {@code doubleToRawLongBits(longBitsToDouble(start))} may
1045
* <i>not</i> equal {@code start}. Moreover, which
1046
* particular bit patterns represent signaling NaNs is platform
1047
* dependent; although all NaN bit patterns, quiet or signaling,
1048
* must be in the NaN range identified above.
1049
*
1050
* @param bits any {@code long} integer.
1051
* @return the {@code double} floating-point value with the same
1052
* bit pattern.
1053
*/
1054
@IntrinsicCandidate
1055
public static native double longBitsToDouble(long bits);
1056
1057
/**
1058
* Compares two {@code Double} objects numerically.
1059
*
1060
* This method imposes a total order on {@code Double} objects
1061
* with two differences compared to the incomplete order defined by
1062
* the Java language numerical comparison operators ({@code <, <=,
1063
* ==, >=, >}) on {@code double} values.
1064
*
1065
* <ul><li> A NaN is <em>unordered</em> with respect to other
1066
* values and unequal to itself under the comparison
1067
* operators. This method chooses to define {@code
1068
* Double.NaN} to be equal to itself and greater than all
1069
* other {@code double} values (including {@code
1070
* Double.POSITIVE_INFINITY}).
1071
*
1072
* <li> Positive zero and negative zero compare equal
1073
* numerically, but are distinct and distinguishable values.
1074
* This method chooses to define positive zero ({@code +0.0d}),
1075
* to be greater than negative zero ({@code -0.0d}).
1076
* </ul>
1077
1078
* This ensures that the <i>natural ordering</i> of {@code Double}
1079
* objects imposed by this method is <i>consistent with
1080
* equals</i>; see <a href="#equivalenceRelation">this
1081
* discussion</a> for details of floating-point comparison and
1082
* ordering.
1083
*
1084
* @param anotherDouble the {@code Double} to be compared.
1085
* @return the value {@code 0} if {@code anotherDouble} is
1086
* numerically equal to this {@code Double}; a value
1087
* less than {@code 0} if this {@code Double}
1088
* is numerically less than {@code anotherDouble};
1089
* and a value greater than {@code 0} if this
1090
* {@code Double} is numerically greater than
1091
* {@code anotherDouble}.
1092
*
1093
* @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
1094
* @since 1.2
1095
*/
1096
public int compareTo(Double anotherDouble) {
1097
return Double.compare(value, anotherDouble.value);
1098
}
1099
1100
/**
1101
* Compares the two specified {@code double} values. The sign
1102
* of the integer value returned is the same as that of the
1103
* integer that would be returned by the call:
1104
* <pre>
1105
* new Double(d1).compareTo(new Double(d2))
1106
* </pre>
1107
*
1108
* @param d1 the first {@code double} to compare
1109
* @param d2 the second {@code double} to compare
1110
* @return the value {@code 0} if {@code d1} is
1111
* numerically equal to {@code d2}; a value less than
1112
* {@code 0} if {@code d1} is numerically less than
1113
* {@code d2}; and a value greater than {@code 0}
1114
* if {@code d1} is numerically greater than
1115
* {@code d2}.
1116
* @since 1.4
1117
*/
1118
public static int compare(double d1, double d2) {
1119
if (d1 < d2)
1120
return -1; // Neither val is NaN, thisVal is smaller
1121
if (d1 > d2)
1122
return 1; // Neither val is NaN, thisVal is larger
1123
1124
// Cannot use doubleToRawLongBits because of possibility of NaNs.
1125
long thisBits = Double.doubleToLongBits(d1);
1126
long anotherBits = Double.doubleToLongBits(d2);
1127
1128
return (thisBits == anotherBits ? 0 : // Values are equal
1129
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1130
1)); // (0.0, -0.0) or (NaN, !NaN)
1131
}
1132
1133
/**
1134
* Adds two {@code double} values together as per the + operator.
1135
*
1136
* @param a the first operand
1137
* @param b the second operand
1138
* @return the sum of {@code a} and {@code b}
1139
* @jls 4.2.4 Floating-Point Operations
1140
* @see java.util.function.BinaryOperator
1141
* @since 1.8
1142
*/
1143
public static double sum(double a, double b) {
1144
return a + b;
1145
}
1146
1147
/**
1148
* Returns the greater of two {@code double} values
1149
* as if by calling {@link Math#max(double, double) Math.max}.
1150
*
1151
* @param a the first operand
1152
* @param b the second operand
1153
* @return the greater of {@code a} and {@code b}
1154
* @see java.util.function.BinaryOperator
1155
* @since 1.8
1156
*/
1157
public static double max(double a, double b) {
1158
return Math.max(a, b);
1159
}
1160
1161
/**
1162
* Returns the smaller of two {@code double} values
1163
* as if by calling {@link Math#min(double, double) Math.min}.
1164
*
1165
* @param a the first operand
1166
* @param b the second operand
1167
* @return the smaller of {@code a} and {@code b}.
1168
* @see java.util.function.BinaryOperator
1169
* @since 1.8
1170
*/
1171
public static double min(double a, double b) {
1172
return Math.min(a, b);
1173
}
1174
1175
/**
1176
* Returns an {@link Optional} containing the nominal descriptor for this
1177
* instance, which is the instance itself.
1178
*
1179
* @return an {@link Optional} describing the {@linkplain Double} instance
1180
* @since 12
1181
*/
1182
@Override
1183
public Optional<Double> describeConstable() {
1184
return Optional.of(this);
1185
}
1186
1187
/**
1188
* Resolves this instance as a {@link ConstantDesc}, the result of which is
1189
* the instance itself.
1190
*
1191
* @param lookup ignored
1192
* @return the {@linkplain Double} instance
1193
* @since 12
1194
*/
1195
@Override
1196
public Double resolveConstantDesc(MethodHandles.Lookup lookup) {
1197
return this;
1198
}
1199
1200
/** use serialVersionUID from JDK 1.0.2 for interoperability */
1201
@java.io.Serial
1202
private static final long serialVersionUID = -9172774392245257468L;
1203
}
1204
1205