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