1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package java.lang;
19
20/**
21 * The wrapper for the primitive type {@code double}.
22 *
23 * @see java.lang.Number
24 * @since 1.0
25 */
26public final class Double extends Number implements Comparable<Double> {
27    static final int EXPONENT_BIAS = 1023;
28
29    static final int EXPONENT_BITS = 12;
30    static final int MANTISSA_BITS = 52;
31    static final int NON_MANTISSA_BITS = 12;
32
33    static final long SIGN_MASK     = 0x8000000000000000L;
34    static final long EXPONENT_MASK = 0x7ff0000000000000L;
35    static final long MANTISSA_MASK = 0x000fffffffffffffL;
36
37    private static final long serialVersionUID = -9172774392245257468L;
38
39    /**
40     * The value which the receiver represents.
41     */
42    private final double value;
43
44    /**
45     * Constant for the maximum {@code double} value, (2 - 2<sup>-52</sup>) *
46     * 2<sup>1023</sup>.
47     */
48    public static final double MAX_VALUE = 1.79769313486231570e+308;
49
50    /**
51     * Constant for the minimum {@code double} value, 2<sup>-1074</sup>.
52     */
53    public static final double MIN_VALUE = 5e-324;
54
55    /* 4.94065645841246544e-324 gets rounded to 9.88131e-324 */
56
57    /**
58     * Constant for the Not-a-Number (NaN) value of the {@code double} type.
59     */
60    public static final double NaN = 0.0 / 0.0;
61
62    /**
63     * Constant for the positive infinity value of the {@code double} type.
64     */
65    public static final double POSITIVE_INFINITY = 1.0 / 0.0;
66
67    /**
68     * Constant for the negative infinity value of the {@code double} type.
69     */
70    public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
71
72    /**
73     * Constant for the smallest positive normal value of the {@code double} type.
74     *
75     * @since 1.6
76     */
77    public static final double MIN_NORMAL = 2.2250738585072014E-308;
78
79    /**
80     * Maximum base-2 exponent that a finite value of the {@code double} type may have.
81     * Equal to {@code Math.getExponent(Double.MAX_VALUE)}.
82     *
83     * @since 1.6
84     */
85    public static final int MAX_EXPONENT = 1023;
86
87    /**
88     * Minimum base-2 exponent that a normal value of the {@code double} type may have.
89     * Equal to {@code Math.getExponent(Double.MIN_NORMAL)}.
90     *
91     * @since 1.6
92     */
93    public static final int MIN_EXPONENT = -1022;
94
95    /**
96     * The {@link Class} object that represents the primitive type {@code
97     * double}.
98     *
99     * @since 1.1
100     */
101    @SuppressWarnings("unchecked")
102    public static final Class<Double> TYPE
103            = (Class<Double>) double[].class.getComponentType();
104    // Note: Double.TYPE can't be set to "double.class", since *that* is
105    // defined to be "java.lang.Double.TYPE";
106
107    /**
108     * Constant for the number of bits needed to represent a {@code double} in
109     * two's complement form.
110     *
111     * @since 1.5
112     */
113    public static final int SIZE = 64;
114
115    /**
116     * Constructs a new {@code Double} with the specified primitive double
117     * value.
118     *
119     * @param value
120     *            the primitive double value to store in the new instance.
121     */
122    public Double(double value) {
123        this.value = value;
124    }
125
126    /**
127     * Constructs a new {@code Double} from the specified string.
128     *
129     * @param string
130     *            the string representation of a double value.
131     * @throws NumberFormatException
132     *             if {@code string} cannot be parsed as a double value.
133     * @see #parseDouble(String)
134     */
135    public Double(String string) throws NumberFormatException {
136        this(parseDouble(string));
137    }
138
139    /**
140     * Compares this object to the specified double object to determine their
141     * relative order. There are two special cases:
142     * <ul>
143     * <li>{@code Double.NaN} is equal to {@code Double.NaN} and it is greater
144     * than any other double value, including {@code Double.POSITIVE_INFINITY};</li>
145     * <li>+0.0d is greater than -0.0d</li>
146     * </ul>
147     *
148     * @param object
149     *            the double object to compare this object to.
150     * @return a negative value if the value of this double is less than the
151     *         value of {@code object}; 0 if the value of this double and the
152     *         value of {@code object} are equal; a positive value if the value
153     *         of this double is greater than the value of {@code object}.
154     * @throws NullPointerException
155     *             if {@code object} is {@code null}.
156     * @see java.lang.Comparable
157     * @since 1.2
158     */
159    public int compareTo(Double object) {
160        return compare(value, object.value);
161    }
162
163    @Override
164    public byte byteValue() {
165        return (byte) value;
166    }
167
168    /**
169     * Returns an integer corresponding to the bits of the given
170     * <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a> double precision
171     * {@code value}. All <em>Not-a-Number (NaN)</em> values are converted to a single NaN
172     * representation ({@code 0x7ff8000000000000L}) (compare to {@link #doubleToRawLongBits}).
173     */
174    public static native long doubleToLongBits(double value);
175
176    /**
177     * Returns an integer corresponding to the bits of the given
178     * <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a> double precision
179     * {@code value}. <em>Not-a-Number (NaN)</em> values are preserved (compare
180     * to {@link #doubleToLongBits}).
181     */
182    public static native long doubleToRawLongBits(double value);
183
184    /**
185     * Gets the primitive value of this double.
186     *
187     * @return this object's primitive value.
188     */
189    @Override
190    public double doubleValue() {
191        return value;
192    }
193
194    /**
195     * Tests this double for equality with {@code object}.
196     * To be equal, {@code object} must be an instance of {@code Double} and
197     * {@code doubleToLongBits} must give the same value for both objects.
198     *
199     * <p>Note that, unlike {@code ==}, {@code -0.0} and {@code +0.0} compare
200     * unequal, and {@code NaN}s compare equal by this method.
201     *
202     * @param object
203     *            the object to compare this double with.
204     * @return {@code true} if the specified object is equal to this
205     *         {@code Double}; {@code false} otherwise.
206     */
207    @Override
208    public boolean equals(Object object) {
209        return (object instanceof Double) &&
210                (doubleToLongBits(this.value) == doubleToLongBits(((Double) object).value));
211    }
212
213    @Override
214    public float floatValue() {
215        return (float) value;
216    }
217
218    @Override
219    public int hashCode() {
220        long v = doubleToLongBits(value);
221        return (int) (v ^ (v >>> 32));
222    }
223
224    @Override
225    public int intValue() {
226        return (int) value;
227    }
228
229    /**
230     * Indicates whether this object represents an infinite value.
231     *
232     * @return {@code true} if the value of this double is positive or negative
233     *         infinity; {@code false} otherwise.
234     */
235    public boolean isInfinite() {
236        return isInfinite(value);
237    }
238
239    /**
240     * Indicates whether the specified double represents an infinite value.
241     *
242     * @param d
243     *            the double to check.
244     * @return {@code true} if the value of {@code d} is positive or negative
245     *         infinity; {@code false} otherwise.
246     */
247    public static boolean isInfinite(double d) {
248        return (d == POSITIVE_INFINITY) || (d == NEGATIVE_INFINITY);
249    }
250
251    /**
252     * Indicates whether this object is a <em>Not-a-Number (NaN)</em> value.
253     *
254     * @return {@code true} if this double is <em>Not-a-Number</em>;
255     *         {@code false} if it is a (potentially infinite) double number.
256     */
257    public boolean isNaN() {
258        return isNaN(value);
259    }
260
261    /**
262     * Indicates whether the specified double is a <em>Not-a-Number (NaN)</em>
263     * value.
264     *
265     * @param d
266     *            the double value to check.
267     * @return {@code true} if {@code d} is <em>Not-a-Number</em>;
268     *         {@code false} if it is a (potentially infinite) double number.
269     */
270    public static boolean isNaN(double d) {
271        return d != d;
272    }
273
274    /**
275     * Returns the <a href="http://en.wikipedia.org/wiki/IEEE_754-1985">IEEE 754</a>
276     * double precision float corresponding to the given {@code bits}.
277     */
278    public static native double longBitsToDouble(long bits);
279
280    @Override
281    public long longValue() {
282        return (long) value;
283    }
284
285    /**
286     * Parses the specified string as a double value.
287     *
288     * @param string
289     *            the string representation of a double value.
290     * @return the primitive double value represented by {@code string}.
291     * @throws NumberFormatException
292     *             if {@code string} cannot be parsed as a double value.
293     */
294    public static double parseDouble(String string) throws NumberFormatException {
295        return StringToReal.parseDouble(string);
296    }
297
298    @Override
299    public short shortValue() {
300        return (short) value;
301    }
302
303    @Override
304    public String toString() {
305        return Double.toString(value);
306    }
307
308    /**
309     * Returns a string containing a concise, human-readable description of the
310     * specified double value.
311     *
312     * @param d
313     *             the double to convert to a string.
314     * @return a printable representation of {@code d}.
315     */
316    public static String toString(double d) {
317        return RealToString.getInstance().doubleToString(d);
318    }
319
320    /**
321     * Parses the specified string as a double value.
322     *
323     * @param string
324     *            the string representation of a double value.
325     * @return a {@code Double} instance containing the double value represented
326     *         by {@code string}.
327     * @throws NumberFormatException
328     *             if {@code string} cannot be parsed as a double value.
329     * @see #parseDouble(String)
330     */
331    public static Double valueOf(String string) throws NumberFormatException {
332        return parseDouble(string);
333    }
334
335    /**
336     * Compares the two specified double values. There are two special cases:
337     * <ul>
338     * <li>{@code Double.NaN} is equal to {@code Double.NaN} and it is greater
339     * than any other double value, including {@code Double.POSITIVE_INFINITY};</li>
340     * <li>+0.0d is greater than -0.0d</li>
341     * </ul>
342     *
343     * @param double1
344     *            the first value to compare.
345     * @param double2
346     *            the second value to compare.
347     * @return a negative value if {@code double1} is less than {@code double2};
348     *         0 if {@code double1} and {@code double2} are equal; a positive
349     *         value if {@code double1} is greater than {@code double2}.
350     */
351    public static int compare(double double1, double double2) {
352        // Non-zero, non-NaN checking.
353        if (double1 > double2) {
354            return 1;
355        }
356        if (double2 > double1) {
357            return -1;
358        }
359        if (double1 == double2 && 0.0d != double1) {
360            return 0;
361        }
362
363        // NaNs are equal to other NaNs and larger than any other double
364        if (isNaN(double1)) {
365            if (isNaN(double2)) {
366                return 0;
367            }
368            return 1;
369        } else if (isNaN(double2)) {
370            return -1;
371        }
372
373        // Deal with +0.0 and -0.0
374        long d1 = doubleToRawLongBits(double1);
375        long d2 = doubleToRawLongBits(double2);
376        // The below expression is equivalent to:
377        // (d1 == d2) ? 0 : (d1 < d2) ? -1 : 1
378        return (int) ((d1 >> 63) - (d2 >> 63));
379    }
380
381    /**
382     * Returns a {@code Double} instance for the specified double value.
383     *
384     * @param d
385     *            the double value to store in the instance.
386     * @return a {@code Double} instance containing {@code d}.
387     * @since 1.5
388     */
389    public static Double valueOf(double d) {
390        return new Double(d);
391    }
392
393    /**
394     * Converts the specified double into its hexadecimal string representation.
395     *
396     * @param d
397     *            the double to convert.
398     * @return the hexadecimal string representation of {@code d}.
399     * @since 1.5
400     */
401    public static String toHexString(double d) {
402        /*
403         * Reference: http://en.wikipedia.org/wiki/IEEE_754-1985
404         */
405        if (d != d) {
406            return "NaN";
407        }
408        if (d == POSITIVE_INFINITY) {
409            return "Infinity";
410        }
411        if (d == NEGATIVE_INFINITY) {
412            return "-Infinity";
413        }
414
415        long bitValue = doubleToLongBits(d);
416
417        boolean negative = (bitValue & 0x8000000000000000L) != 0;
418        // mask exponent bits and shift down
419        long exponent = (bitValue & 0x7FF0000000000000L) >>> 52;
420        // mask significand bits and shift up
421        long significand = bitValue & 0x000FFFFFFFFFFFFFL;
422
423        if (exponent == 0 && significand == 0) {
424            return (negative ? "-0x0.0p0" : "0x0.0p0");
425        }
426
427        StringBuilder hexString = new StringBuilder(10);
428        if (negative) {
429            hexString.append("-0x");
430        } else {
431            hexString.append("0x");
432        }
433
434        if (exponent == 0) { // denormal (subnormal) value
435            hexString.append("0.");
436            // significand is 52-bits, so there can be 13 hex digits
437            int fractionDigits = 13;
438            // remove trailing hex zeros, so Integer.toHexString() won't print
439            // them
440            while ((significand != 0) && ((significand & 0xF) == 0)) {
441                significand >>>= 4;
442                fractionDigits--;
443            }
444            // this assumes Integer.toHexString() returns lowercase characters
445            String hexSignificand = Long.toHexString(significand);
446
447            // if there are digits left, then insert some '0' chars first
448            if (significand != 0 && fractionDigits > hexSignificand.length()) {
449                int digitDiff = fractionDigits - hexSignificand.length();
450                while (digitDiff-- != 0) {
451                    hexString.append('0');
452                }
453            }
454            hexString.append(hexSignificand);
455            hexString.append("p-1022");
456        } else { // normal value
457            hexString.append("1.");
458            // significand is 52-bits, so there can be 13 hex digits
459            int fractionDigits = 13;
460            // remove trailing hex zeros, so Integer.toHexString() won't print
461            // them
462            while ((significand != 0) && ((significand & 0xF) == 0)) {
463                significand >>>= 4;
464                fractionDigits--;
465            }
466            // this assumes Integer.toHexString() returns lowercase characters
467            String hexSignificand = Long.toHexString(significand);
468
469            // if there are digits left, then insert some '0' chars first
470            if (significand != 0 && fractionDigits > hexSignificand.length()) {
471                int digitDiff = fractionDigits - hexSignificand.length();
472                while (digitDiff-- != 0) {
473                    hexString.append('0');
474                }
475            }
476
477            hexString.append(hexSignificand);
478            hexString.append('p');
479            // remove exponent's 'bias' and convert to a string
480            hexString.append(Long.toString(exponent - 1023));
481        }
482        return hexString.toString();
483    }
484}
485