bug fixes + annotations
[IRC.git] / Robust / src / ClassLibrary / SSJava / Double.java
1 /* Double.java -- object wrapper for double
2    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
3    Free Software Foundation, Inc.
4
5    This file is part of GNU Classpath.
6
7    GNU Classpath is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GNU Classpath is distributed in the hope that it will be useful, but
13    WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GNU Classpath; see the file COPYING.  If not, write to the
19    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20    02110-1301 USA.
21
22    Linking this library statically or dynamically with other modules is
23    making a combined work based on this library.  Thus, the terms and
24    conditions of the GNU General Public License cover the whole
25    combination.
26
27    As a special exception, the copyright holders of this library give you
28    permission to link this library with independent modules to produce an
29    executable, regardless of the license terms of these independent
30    modules, and to copy and distribute the resulting executable under
31    terms of your choice, provided that you also meet, for each linked
32    independent module, the terms and conditions of the license of that
33    module.  An independent module is a module which is not derived from
34    or based on this library.  If you modify this library, you may extend
35    this exception to your version of the library, but you are not
36    obligated to do so.  If you do not wish to do so, delete this
37    exception statement from your version. */
38
39 //package java.lang;
40
41 /**
42  * Instances of class <code>Double</code> represent primitive
43  * <code>double</code> values.
44  * 
45  * Additionally, this class provides various helper functions and variables
46  * related to doubles.
47  * 
48  * @author Paul Fisher
49  * @author Andrew Haley (aph@cygnus.com)
50  * @author Eric Blake (ebb9@email.byu.edu)
51  * @author Tom Tromey (tromey@redhat.com)
52  * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
53  * @since 1.0
54  * @status partly updated to 1.5
55  */
56 @LATTICE("V")
57 @METHODDEFAULT("OUT<THIS,THIS<IN,THISLOC=THIS,RETURNLOC=OUT")
58 public final class Double extends Number // implements Comparable<Double>
59 {
60   /**
61    * Compatible with JDK 1.0+.
62    */
63   /**
64    * The immutable value of this Double.
65    * 
66    * @serial the wrapped double
67    */
68   @LOC("V")
69   private final double value;
70
71   /**
72    * Create a <code>Double</code> from the primitive <code>double</code>
73    * specified.
74    * 
75    * @param value
76    *          the <code>double</code> argument
77    */
78   public Double(double value) {
79     this.value = value;
80   }
81
82   /**
83    * Create a <code>Double</code> from the specified <code>String</code>. This
84    * method calls <code>Double.parseDouble()</code>.
85    * 
86    * @param s
87    *          the <code>String</code> to convert
88    * @throws NumberFormatException
89    *           if <code>s</code> cannot be parsed as a <code>double</code>
90    * @throws NullPointerException
91    *           if <code>s</code> is null
92    * @see #parseDouble(String)
93    */
94   public Double(String s) {
95     value = parseDouble(s);
96   }
97
98   /**
99    * Convert the <code>double</code> to a <code>String</code>. Floating-point
100    * string representation is fairly complex: here is a rundown of the possible
101    * values. "<code>[-]</code>" indicates that a negative sign will be printed
102    * if the value (or exponent) is negative. "<code>&lt;number&gt;</code>" means
103    * a string of digits ('0' to '9'). "<code>&lt;digit&gt;</code>" means a
104    * single digit ('0' to '9').<br>
105    * 
106    * <table border=1>
107    * <tr>
108    * <th>Value of Double</th>
109    * <th>String Representation</th>
110    * </tr>
111    * <tr>
112    * <td>[+-] 0</td>
113    * <td><code>[-]0.0</code></td>
114    * </tr>
115    * <tr>
116    * <td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
117    * <td><code>[-]number.number</code></td>
118    * </tr>
119    * <tr>
120    * <td>Other numeric value</td>
121    * <td><code>[-]&lt;digit&gt;.&lt;number&gt;
122    *          E[-]&lt;number&gt;</code></td>
123    * </tr>
124    * <tr>
125    * <td>[+-] infinity</td>
126    * <td><code>[-]Infinity</code></td>
127    * </tr>
128    * <tr>
129    * <td>NaN</td>
130    * <td><code>NaN</code></td>
131    * </tr>
132    * </table>
133    * 
134    * Yes, negative zero <em>is</em> a possible value. Note that there is
135    * <em>always</em> a <code>.</code> and at least one digit printed after it:
136    * even if the number is 3, it will be printed as <code>3.0</code>. After the
137    * ".", all digits will be printed except trailing zeros. The result is
138    * rounded to the shortest decimal number which will parse back to the same
139    * double.
140    * 
141    * <p>
142    * To create other output formats, use {@link java.text.NumberFormat}.
143    * 
144    * @XXX specify where we are not in accord with the spec.
145    * 
146    * @param d
147    *          the <code>double</code> to convert
148    * @return the <code>String</code> representing the <code>double</code>
149    */
150   public static String toString(@LOC("IN") double d) {
151     return String.valueOf(d);
152   }
153
154   /**
155    * Convert a double value to a hexadecimal string. This converts as follows:
156    * <ul>
157    * <li>A NaN value is converted to the string "NaN".
158    * <li>Positive infinity is converted to the string "Infinity".
159    * <li>Negative infinity is converted to the string "-Infinity".
160    * <li>For all other values, the first character of the result is '-' if the
161    * value is negative. This is followed by '0x1.' if the value is normal, and
162    * '0x0.' if the value is denormal. This is then followed by a (lower-case)
163    * hexadecimal representation of the mantissa, with leading zeros as required
164    * for denormal values. The next character is a 'p', and this is followed by a
165    * decimal representation of the unbiased exponent.
166    * </ul>
167    * 
168    * @param d
169    *          the double value
170    * @return the hexadecimal string representation
171    * @since 1.5
172    */
173   public static String toHexString(double d) {
174     /*
175      * if (isNaN(d)) return "NaN"; if (isInfinite(d)) return d < 0 ? "-Infinity"
176      * : "Infinity";
177      * 
178      * long bits = doubleToLongBits(d); StringBuilder result = new
179      * StringBuilder();
180      * 
181      * if (bits < 0) result.append('-'); result.append("0x");
182      * 
183      * final int mantissaBits = 52; final int exponentBits = 11; long mantMask =
184      * (1L << mantissaBits) - 1; long mantissa = bits & mantMask; long expMask =
185      * (1L << exponentBits) - 1; long exponent = (bits >>> mantissaBits) &
186      * expMask;
187      * 
188      * result.append(exponent == 0 ? '0' : '1'); result.append('.');
189      * result.append(Long.toHexString(mantissa)); if (exponent == 0 && mantissa
190      * != 0) { // Treat denormal specially by inserting '0's to make // the
191      * length come out right. The constants here are // to account for things
192      * like the '0x'. int offset = 4 + ((bits < 0) ? 1 : 0); // The silly +3 is
193      * here to keep the code the same between // the Float and Double cases. In
194      * Float the value is // not a multiple of 4. int desiredLength = offset +
195      * (mantissaBits + 3) / 4; while (result.length() < desiredLength)
196      * result.insert(offset, '0'); } result.append('p'); if (exponent == 0 &&
197      * mantissa == 0) { // Zero, so do nothing special. } else { // Apply bias.
198      * boolean denormal = exponent == 0; exponent -= (1 << (exponentBits - 1)) -
199      * 1; // Handle denormal. if (denormal) ++exponent; }
200      * 
201      * result.append(Long.toString(exponent)); return result.toString();
202      */
203     return "0x0";
204   }
205
206   /**
207    * Returns a <code>Double</code> object wrapping the value. In contrast to the
208    * <code>Double</code> constructor, this method may cache some values. It is
209    * used by boxing conversion.
210    * 
211    * @param val
212    *          the value to wrap
213    * @return the <code>Double</code>
214    * @since 1.5
215    */
216   public static Double valueOf(double val) {
217     // We don't actually cache, but we could.
218     return new Double(val);
219   }
220
221   /**
222    * Create a new <code>Double</code> object using the <code>String</code>.
223    * 
224    * @param s
225    *          the <code>String</code> to convert
226    * @return the new <code>Double</code>
227    * @throws NumberFormatException
228    *           if <code>s</code> cannot be parsed as a <code>double</code>
229    * @throws NullPointerException
230    *           if <code>s</code> is null.
231    * @see #parseDouble(String)
232    */
233   public static Double valueOf(String s) {
234     return new Double(parseDouble(s));
235   }
236
237   /**
238    * Parse the specified <code>String</code> as a <code>double</code>. The
239    * extended BNF grammar is as follows:<br>
240    * 
241    * <pre>
242    * <em>DecodableString</em>:
243    *      ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
244    *    | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
245    *    | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
246    *              [ <code>f</code> | <code>F</code> | <code>d</code>
247    *                | <code>D</code>] )
248    * <em>FloatingPoint</em>:
249    *      ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
250    *              [ <em>Exponent</em> ] )
251    *    | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
252    * <em>Exponent</em>:
253    *      ( ( <code>e</code> | <code>E</code> )
254    *              [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
255    * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
256    * </pre>
257    * 
258    * <p>
259    * NaN and infinity are special cases, to allow parsing of the output of
260    * toString. Otherwise, the result is determined by calculating
261    * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding to
262    * the nearest double. Remember that many numbers cannot be precisely
263    * represented in floating point. In case of overflow, infinity is used, and
264    * in case of underflow, signed zero is used. Unlike Integer.parseInt, this
265    * does not accept Unicode digits outside the ASCII range.
266    * 
267    * <p>
268    * If an unexpected character is found in the <code>String</code>, a
269    * <code>NumberFormatException</code> will be thrown. Leading and trailing
270    * 'whitespace' is ignored via <code>String.trim()</code>, but spaces internal
271    * to the actual number are not allowed.
272    * 
273    * <p>
274    * To parse numbers according to another format, consider using
275    * {@link java.text.NumberFormat}.
276    * 
277    * @XXX specify where/how we are not in accord with the spec.
278    * 
279    * @param str
280    *          the <code>String</code> to convert
281    * @return the <code>double</code> value of <code>s</code>
282    * @throws NumberFormatException
283    *           if <code>s</code> cannot be parsed as a <code>double</code>
284    * @throws NullPointerException
285    *           if <code>s</code> is null
286    * @see #MIN_VALUE
287    * @see #MAX_VALUE
288    * @see #POSITIVE_INFINITY
289    * @see #NEGATIVE_INFINITY
290    * @since 1.2
291    */
292   public static double parseDouble(String str) {
293     return nativeparsedouble(str);
294   }
295
296   public static native double nativeparsedouble(String str);
297
298   public static native double nativeparsedouble(int start, int length, byte[] str);
299
300   /**
301    * Return <code>true</code> if the <code>double</code> has the same value as
302    * <code>NaN</code>, otherwise return <code>false</code>.
303    * 
304    * @param v
305    *          the <code>double</code> to compare
306    * @return whether the argument is <code>NaN</code>.
307    */
308   public static boolean isNaN(@LOC("IN") double v) {
309     // This works since NaN != NaN is the only reflexive inequality
310     // comparison which returns true.
311     return v != v;
312   }
313
314   /**
315    * Return <code>true</code> if the <code>double</code> has a value equal to
316    * either <code>NEGATIVE_INFINITY</code> or <code>POSITIVE_INFINITY</code>,
317    * otherwise return <code>false</code>.
318    * 
319    * @param v
320    *          the <code>double</code> to compare
321    * @return whether the argument is (-/+) infinity.
322    */
323   public static boolean isInfinite(double v) {
324     return false;
325   }
326
327   /**
328    * Return <code>true</code> if the value of this <code>Double</code> is the
329    * same as <code>NaN</code>, otherwise return <code>false</code>.
330    * 
331    * @return whether this <code>Double</code> is <code>NaN</code>
332    */
333   public boolean isNaN() {
334     return isNaN(value);
335   }
336
337   /**
338    * Return <code>true</code> if the value of this <code>Double</code> is the
339    * same as <code>NEGATIVE_INFINITY</code> or <code>POSITIVE_INFINITY</code>,
340    * otherwise return <code>false</code>.
341    * 
342    * @return whether this <code>Double</code> is (-/+) infinity
343    */
344   public boolean isInfinite() {
345     return isInfinite(value);
346   }
347
348   /**
349    * Convert the <code>double</code> value of this <code>Double</code> to a
350    * <code>String</code>. This method calls <code>Double.toString(double)</code>
351    * to do its dirty work.
352    * 
353    * @return the <code>String</code> representation
354    * @see #toString(double)
355    */
356   public String toString() {
357     return toString(value);
358   }
359
360   /**
361    * Return the value of this <code>Double</code> as a <code>byte</code>.
362    * 
363    * @return the byte value
364    * @since 1.1
365    */
366   public byte byteValue() {
367     return (byte) value;
368   }
369
370   /**
371    * Return the value of this <code>Double</code> as a <code>short</code>.
372    * 
373    * @return the short value
374    * @since 1.1
375    */
376   public short shortValue() {
377     return (short) value;
378   }
379
380   /**
381    * Return the value of this <code>Double</code> as an <code>int</code>.
382    * 
383    * @return the int value
384    */
385   public int intValue() {
386     return (int) value;
387   }
388
389   /**
390    * Return the value of this <code>Double</code> as a <code>long</code>.
391    * 
392    * @return the long value
393    */
394   public long longValue() {
395     return (long) value;
396   }
397
398   /**
399    * Return the value of this <code>Double</code> as a <code>float</code>.
400    * 
401    * @return the float value
402    */
403   public float floatValue() {
404     return (float) value;
405   }
406
407   /**
408    * Return the value of this <code>Double</code>.
409    * 
410    * @return the double value
411    */
412   public double doubleValue() {
413     return value;
414   }
415
416   /**
417    * Return a hashcode representing this Object. <code>Double</code>'s hash code
418    * is calculated by:<br>
419    * <code>long v = Double.doubleToLongBits(doubleValue());<br>
420    *    int hash = (int)(v^(v&gt;&gt;32))</code>.
421    * 
422    * @return this Object's hash code
423    * @see #doubleToLongBits(double)
424    */
425   public int hashCode() {
426     @LOC("OUT") long v = doubleToLongBits(value);
427     return (int) (v ^ (v >>> 32));
428   }
429
430   /**
431    * Returns <code>true</code> if <code>obj</code> is an instance of
432    * <code>Double</code> and represents the same double value. Unlike comparing
433    * two doubles with <code>==</code>, this treats two instances of
434    * <code>Double.NaN</code> as equal, but treats <code>0.0</code> and
435    * <code>-0.0</code> as unequal.
436    * 
437    * <p>
438    * Note that <code>d1.equals(d2)</code> is identical to
439    * <code>doubleToLongBits(d1.doubleValue()) ==
440    *    doubleToLongBits(d2.doubleValue())</code>.
441    * 
442    * @param obj
443    *          the object to compare
444    * @return whether the objects are semantically equal
445    */
446   public boolean equals(Object obj) {
447     if (!(obj instanceof Double))
448       return false;
449
450     double d = ((Double) obj).value;
451
452     // Avoid call to native method. However, some implementations, like gcj,
453     // are better off using floatToIntBits(value) == floatToIntBits(f).
454     // Check common case first, then check NaN and 0.
455     if (value == d)
456       return (value != 0) || (1 / value == 1 / d);
457     return isNaN(value) && isNaN(d);
458   }
459
460   /**
461    * Convert the double to the IEEE 754 floating-point "double format" bit
462    * layout. Bit 63 (the most significant) is the sign bit, bits 62-52 (masked
463    * by 0x7ff0000000000000L) represent the exponent, and bits 51-0 (masked by
464    * 0x000fffffffffffffL) are the mantissa. This function collapses all versions
465    * of NaN to 0x7ff8000000000000L. The result of this function can be used as
466    * the argument to <code>Double.longBitsToDouble(long)</code> to obtain the
467    * original <code>double</code> value.
468    * 
469    * @param value
470    *          the <code>double</code> to convert
471    * @return the bits of the <code>double</code>
472    * @see #longBitsToDouble(long)
473    */
474   public static long doubleToLongBits(@LOC("IN") double value) {
475     if (isNaN(value))
476       return 0x7ff8000000000000L;
477     else
478       return /* VMDouble. */doubleToRawLongBits(value);
479   }
480
481   /**
482    * Convert the double to the IEEE 754 floating-point "double format" bit
483    * layout. Bit 63 (the most significant) is the sign bit, bits 62-52 (masked
484    * by 0x7ff0000000000000L) represent the exponent, and bits 51-0 (masked by
485    * 0x000fffffffffffffL) are the mantissa. This function leaves NaN alone,
486    * rather than collapsing to a canonical value. The result of this function
487    * can be used as the argument to <code>Double.longBitsToDouble(long)</code>
488    * to obtain the original <code>double</code> value.
489    * 
490    * @param value
491    *          the <code>double</code> to convert
492    * @return the bits of the <code>double</code>
493    * @see #longBitsToDouble(long)
494    */
495   /*
496    * public static long doubleToRawLongBits(double value) { return
497    * VMDouble.doubleToRawLongBits(value); }
498    */
499   public static native long doubleToRawLongBits(double value);
500
501   /**
502    * Convert the argument in IEEE 754 floating-point "double format" bit layout
503    * to the corresponding float. Bit 63 (the most significant) is the sign bit,
504    * bits 62-52 (masked by 0x7ff0000000000000L) represent the exponent, and bits
505    * 51-0 (masked by 0x000fffffffffffffL) are the mantissa. This function leaves
506    * NaN alone, so that you can recover the bit pattern with
507    * <code>Double.doubleToRawLongBits(double)</code>.
508    * 
509    * @param bits
510    *          the bits to convert
511    * @return the <code>double</code> represented by the bits
512    * @see #doubleToLongBits(double)
513    * @see #doubleToRawLongBits(double)
514    */
515   /*
516    * public static double longBitsToDouble(long bits) { return
517    * VMDouble.longBitsToDouble(bits); }
518    */
519   public static native double longBitsToDouble(long bits);
520
521   /**
522    * Compare two Doubles numerically by comparing their <code>double</code>
523    * values. The result is positive if the first is greater, negative if the
524    * second is greater, and 0 if the two are equal. However, this special cases
525    * NaN and signed zero as follows: NaN is considered greater than all other
526    * doubles, including <code>POSITIVE_INFINITY</code>, and positive zero is
527    * considered greater than negative zero.
528    * 
529    * @param d
530    *          the Double to compare
531    * @return the comparison
532    * @since 1.2
533    */
534   public int compareTo(Double d) {
535     return compare(value, d.value);
536   }
537
538   /**
539    * Behaves like <code>new Double(x).compareTo(new Double(y))</code>; in other
540    * words this compares two doubles, special casing NaN and zero, without the
541    * overhead of objects.
542    * 
543    * @param x
544    *          the first double to compare
545    * @param y
546    *          the second double to compare
547    * @return the comparison
548    * @since 1.4
549    */
550   public static int compare(double x, double y) {
551     // handle the easy cases:
552     if (x < y)
553       return -1;
554     if (x > y)
555       return 1;
556
557     // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
558     long lx = doubleToRawLongBits(x);
559     long ly = doubleToRawLongBits(y);
560     if (lx == ly)
561       return 0;
562
563     // handle NaNs:
564     if (x != x)
565       return (y != y) ? 0 : 1;
566     else if (y != y)
567       return -1;
568
569     // handle +/- 0.0
570     return (lx < ly) ? -1 : 1;
571   }
572 }