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