001 /* Double.java -- object wrapper for double
002 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
003 Free Software Foundation, Inc.
004
005 This file is part of GNU Classpath.
006
007 GNU Classpath is free software; you can redistribute it and/or modify
008 it under the terms of the GNU General Public License as published by
009 the Free Software Foundation; either version 2, or (at your option)
010 any later version.
011
012 GNU Classpath is distributed in the hope that it will be useful, but
013 WITHOUT ANY WARRANTY; without even the implied warranty of
014 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 General Public License for more details.
016
017 You should have received a copy of the GNU General Public License
018 along with GNU Classpath; see the file COPYING. If not, write to the
019 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
020 02110-1301 USA.
021
022 Linking this library statically or dynamically with other modules is
023 making a combined work based on this library. Thus, the terms and
024 conditions of the GNU General Public License cover the whole
025 combination.
026
027 As a special exception, the copyright holders of this library give you
028 permission to link this library with independent modules to produce an
029 executable, regardless of the license terms of these independent
030 modules, and to copy and distribute the resulting executable under
031 terms of your choice, provided that you also meet, for each linked
032 independent module, the terms and conditions of the license of that
033 module. An independent module is a module which is not derived from
034 or based on this library. If you modify this library, you may extend
035 this exception to your version of the library, but you are not
036 obligated to do so. If you do not wish to do so, delete this
037 exception statement from your version. */
038
039 package java.lang;
040
041 import gnu.java.lang.CPStringBuilder;
042
043 /**
044 * Instances of class <code>Double</code> represent primitive
045 * <code>double</code> values.
046 *
047 * Additionally, this class provides various helper functions and variables
048 * related to doubles.
049 *
050 * @author Paul Fisher
051 * @author Andrew Haley (aph@cygnus.com)
052 * @author Eric Blake (ebb9@email.byu.edu)
053 * @author Tom Tromey (tromey@redhat.com)
054 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
055 * @since 1.0
056 * @status partly updated to 1.5
057 */
058 public final class Double extends Number implements Comparable<Double>
059 {
060 /**
061 * Compatible with JDK 1.0+.
062 */
063 private static final long serialVersionUID = -9172774392245257468L;
064
065 /**
066 * The maximum positive value a <code>double</code> may represent
067 * is 1.7976931348623157e+308.
068 */
069 public static final double MAX_VALUE = 1.7976931348623157e+308;
070
071 /**
072 * The minimum positive value a <code>double</code> may represent
073 * is 5e-324.
074 */
075 public static final double MIN_VALUE = 5e-324;
076
077 /**
078 * The value of a double representation -1.0/0.0, negative
079 * infinity.
080 */
081 public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
082
083 /**
084 * The value of a double representing 1.0/0.0, positive infinity.
085 */
086 public static final double POSITIVE_INFINITY = 1.0 / 0.0;
087
088 /**
089 * All IEEE 754 values of NaN have the same value in Java.
090 */
091 public static final double NaN = 0.0 / 0.0;
092
093 /**
094 * The number of bits needed to represent a <code>double</code>.
095 * @since 1.5
096 */
097 public static final int SIZE = 64;
098
099 /**
100 * The primitive type <code>double</code> is represented by this
101 * <code>Class</code> object.
102 * @since 1.1
103 */
104 public static final Class<Double> TYPE = (Class<Double>) VMClassLoader.getPrimitiveClass('D');
105
106 /**
107 * Cache representation of 0
108 */
109 private static final Double ZERO = new Double(0.0d);
110
111 /**
112 * Cache representation of 1
113 */
114 private static final Double ONE = new Double(1.0d);
115
116 /**
117 * The immutable value of this Double.
118 *
119 * @serial the wrapped double
120 */
121 private final double value;
122
123 /**
124 * Create a <code>Double</code> from the primitive <code>double</code>
125 * specified.
126 *
127 * @param value the <code>double</code> argument
128 */
129 public Double(double value)
130 {
131 this.value = value;
132 }
133
134 /**
135 * Create a <code>Double</code> from the specified <code>String</code>.
136 * This method calls <code>Double.parseDouble()</code>.
137 *
138 * @param s the <code>String</code> to convert
139 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
140 * <code>double</code>
141 * @throws NullPointerException if <code>s</code> is null
142 * @see #parseDouble(String)
143 */
144 public Double(String s)
145 {
146 value = parseDouble(s);
147 }
148
149 /**
150 * Convert the <code>double</code> to a <code>String</code>.
151 * Floating-point string representation is fairly complex: here is a
152 * rundown of the possible values. "<code>[-]</code>" indicates that a
153 * negative sign will be printed if the value (or exponent) is negative.
154 * "<code><number></code>" means a string of digits ('0' to '9').
155 * "<code><digit></code>" means a single digit ('0' to '9').<br>
156 *
157 * <table border=1>
158 * <tr><th>Value of Double</th><th>String Representation</th></tr>
159 * <tr><td>[+-] 0</td> <td><code>[-]0.0</code></td></tr>
160 * <tr><td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
161 * <td><code>[-]number.number</code></td></tr>
162 * <tr><td>Other numeric value</td>
163 * <td><code>[-]<digit>.<number>
164 * E[-]<number></code></td></tr>
165 * <tr><td>[+-] infinity</td> <td><code>[-]Infinity</code></td></tr>
166 * <tr><td>NaN</td> <td><code>NaN</code></td></tr>
167 * </table>
168 *
169 * Yes, negative zero <em>is</em> a possible value. Note that there is
170 * <em>always</em> a <code>.</code> and at least one digit printed after
171 * it: even if the number is 3, it will be printed as <code>3.0</code>.
172 * After the ".", all digits will be printed except trailing zeros. The
173 * result is rounded to the shortest decimal number which will parse back
174 * to the same double.
175 *
176 * <p>To create other output formats, use {@link java.text.NumberFormat}.
177 *
178 * @XXX specify where we are not in accord with the spec.
179 *
180 * @param d the <code>double</code> to convert
181 * @return the <code>String</code> representing the <code>double</code>
182 */
183 public static String toString(double d)
184 {
185 return VMDouble.toString(d, false);
186 }
187
188 /**
189 * Convert a double value to a hexadecimal string. This converts as
190 * follows:
191 * <ul>
192 * <li> A NaN value is converted to the string "NaN".
193 * <li> Positive infinity is converted to the string "Infinity".
194 * <li> Negative infinity is converted to the string "-Infinity".
195 * <li> For all other values, the first character of the result is '-'
196 * if the value is negative. This is followed by '0x1.' if the
197 * value is normal, and '0x0.' if the value is denormal. This is
198 * then followed by a (lower-case) hexadecimal representation of the
199 * mantissa, with leading zeros as required for denormal values.
200 * The next character is a 'p', and this is followed by a decimal
201 * representation of the unbiased exponent.
202 * </ul>
203 * @param d the double value
204 * @return the hexadecimal string representation
205 * @since 1.5
206 */
207 public static String toHexString(double d)
208 {
209 if (isNaN(d))
210 return "NaN";
211 if (isInfinite(d))
212 return d < 0 ? "-Infinity" : "Infinity";
213
214 long bits = doubleToLongBits(d);
215 CPStringBuilder result = new CPStringBuilder();
216
217 if (bits < 0)
218 result.append('-');
219 result.append("0x");
220
221 final int mantissaBits = 52;
222 final int exponentBits = 11;
223 long mantMask = (1L << mantissaBits) - 1;
224 long mantissa = bits & mantMask;
225 long expMask = (1L << exponentBits) - 1;
226 long exponent = (bits >>> mantissaBits) & expMask;
227
228 result.append(exponent == 0 ? '0' : '1');
229 result.append('.');
230 result.append(Long.toHexString(mantissa));
231 if (exponent == 0 && mantissa != 0)
232 {
233 // Treat denormal specially by inserting '0's to make
234 // the length come out right. The constants here are
235 // to account for things like the '0x'.
236 int offset = 4 + ((bits < 0) ? 1 : 0);
237 // The silly +3 is here to keep the code the same between
238 // the Float and Double cases. In Float the value is
239 // not a multiple of 4.
240 int desiredLength = offset + (mantissaBits + 3) / 4;
241 while (result.length() < desiredLength)
242 result.insert(offset, '0');
243 }
244 result.append('p');
245 if (exponent == 0 && mantissa == 0)
246 {
247 // Zero, so do nothing special.
248 }
249 else
250 {
251 // Apply bias.
252 boolean denormal = exponent == 0;
253 exponent -= (1 << (exponentBits - 1)) - 1;
254 // Handle denormal.
255 if (denormal)
256 ++exponent;
257 }
258
259 result.append(Long.toString(exponent));
260 return result.toString();
261 }
262
263 /**
264 * Returns a <code>Double</code> object wrapping the value.
265 * In contrast to the <code>Double</code> constructor, this method
266 * may cache some values. It is used by boxing conversion.
267 *
268 * @param val the value to wrap
269 * @return the <code>Double</code>
270 * @since 1.5
271 */
272 public static Double valueOf(double val)
273 {
274 if ((val == 0.0) && (doubleToRawLongBits(val) == 0L))
275 return ZERO;
276 else if (val == 1.0)
277 return ONE;
278 else
279 return new Double(val);
280 }
281
282 /**
283 * Create a new <code>Double</code> object using the <code>String</code>.
284 *
285 * @param s the <code>String</code> to convert
286 * @return the new <code>Double</code>
287 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
288 * <code>double</code>
289 * @throws NullPointerException if <code>s</code> is null.
290 * @see #parseDouble(String)
291 */
292 public static Double valueOf(String s)
293 {
294 return valueOf(parseDouble(s));
295 }
296
297 /**
298 * Parse the specified <code>String</code> as a <code>double</code>. The
299 * extended BNF grammar is as follows:<br>
300 * <pre>
301 * <em>DecodableString</em>:
302 * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
303 * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
304 * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
305 * [ <code>f</code> | <code>F</code> | <code>d</code>
306 * | <code>D</code>] )
307 * <em>FloatingPoint</em>:
308 * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
309 * [ <em>Exponent</em> ] )
310 * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
311 * <em>Exponent</em>:
312 * ( ( <code>e</code> | <code>E</code> )
313 * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
314 * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
315 * </pre>
316 *
317 * <p>NaN and infinity are special cases, to allow parsing of the output
318 * of toString. Otherwise, the result is determined by calculating
319 * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
320 * to the nearest double. Remember that many numbers cannot be precisely
321 * represented in floating point. In case of overflow, infinity is used,
322 * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
323 * this does not accept Unicode digits outside the ASCII range.
324 *
325 * <p>If an unexpected character is found in the <code>String</code>, a
326 * <code>NumberFormatException</code> will be thrown. Leading and trailing
327 * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
328 * internal to the actual number are not allowed.
329 *
330 * <p>To parse numbers according to another format, consider using
331 * {@link java.text.NumberFormat}.
332 *
333 * @XXX specify where/how we are not in accord with the spec.
334 *
335 * @param str the <code>String</code> to convert
336 * @return the <code>double</code> value of <code>s</code>
337 * @throws NumberFormatException if <code>s</code> cannot be parsed as a
338 * <code>double</code>
339 * @throws NullPointerException if <code>s</code> is null
340 * @see #MIN_VALUE
341 * @see #MAX_VALUE
342 * @see #POSITIVE_INFINITY
343 * @see #NEGATIVE_INFINITY
344 * @since 1.2
345 */
346 public static double parseDouble(String str)
347 {
348 return VMDouble.parseDouble(str);
349 }
350
351 /**
352 * Return <code>true</code> if the <code>double</code> has the same
353 * value as <code>NaN</code>, otherwise return <code>false</code>.
354 *
355 * @param v the <code>double</code> to compare
356 * @return whether the argument is <code>NaN</code>.
357 */
358 public static boolean isNaN(double v)
359 {
360 // This works since NaN != NaN is the only reflexive inequality
361 // comparison which returns true.
362 return v != v;
363 }
364
365 /**
366 * Return <code>true</code> if the <code>double</code> has a value
367 * equal to either <code>NEGATIVE_INFINITY</code> or
368 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
369 *
370 * @param v the <code>double</code> to compare
371 * @return whether the argument is (-/+) infinity.
372 */
373 public static boolean isInfinite(double v)
374 {
375 return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
376 }
377
378 /**
379 * Return <code>true</code> if the value of this <code>Double</code>
380 * is the same as <code>NaN</code>, otherwise return <code>false</code>.
381 *
382 * @return whether this <code>Double</code> is <code>NaN</code>
383 */
384 public boolean isNaN()
385 {
386 return isNaN(value);
387 }
388
389 /**
390 * Return <code>true</code> if the value of this <code>Double</code>
391 * is the same as <code>NEGATIVE_INFINITY</code> or
392 * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
393 *
394 * @return whether this <code>Double</code> is (-/+) infinity
395 */
396 public boolean isInfinite()
397 {
398 return isInfinite(value);
399 }
400
401 /**
402 * Convert the <code>double</code> value of this <code>Double</code>
403 * to a <code>String</code>. This method calls
404 * <code>Double.toString(double)</code> to do its dirty work.
405 *
406 * @return the <code>String</code> representation
407 * @see #toString(double)
408 */
409 public String toString()
410 {
411 return toString(value);
412 }
413
414 /**
415 * Return the value of this <code>Double</code> as a <code>byte</code>.
416 *
417 * @return the byte value
418 * @since 1.1
419 */
420 public byte byteValue()
421 {
422 return (byte) value;
423 }
424
425 /**
426 * Return the value of this <code>Double</code> as a <code>short</code>.
427 *
428 * @return the short value
429 * @since 1.1
430 */
431 public short shortValue()
432 {
433 return (short) value;
434 }
435
436 /**
437 * Return the value of this <code>Double</code> as an <code>int</code>.
438 *
439 * @return the int value
440 */
441 public int intValue()
442 {
443 return (int) value;
444 }
445
446 /**
447 * Return the value of this <code>Double</code> as a <code>long</code>.
448 *
449 * @return the long value
450 */
451 public long longValue()
452 {
453 return (long) value;
454 }
455
456 /**
457 * Return the value of this <code>Double</code> as a <code>float</code>.
458 *
459 * @return the float value
460 */
461 public float floatValue()
462 {
463 return (float) value;
464 }
465
466 /**
467 * Return the value of this <code>Double</code>.
468 *
469 * @return the double value
470 */
471 public double doubleValue()
472 {
473 return value;
474 }
475
476 /**
477 * Return a hashcode representing this Object. <code>Double</code>'s hash
478 * code is calculated by:<br>
479 * <code>long v = Double.doubleToLongBits(doubleValue());<br>
480 * int hash = (int)(v^(v>>32))</code>.
481 *
482 * @return this Object's hash code
483 * @see #doubleToLongBits(double)
484 */
485 public int hashCode()
486 {
487 long v = doubleToLongBits(value);
488 return (int) (v ^ (v >>> 32));
489 }
490
491 /**
492 * Returns <code>true</code> if <code>obj</code> is an instance of
493 * <code>Double</code> and represents the same double value. Unlike comparing
494 * two doubles with <code>==</code>, this treats two instances of
495 * <code>Double.NaN</code> as equal, but treats <code>0.0</code> and
496 * <code>-0.0</code> as unequal.
497 *
498 * <p>Note that <code>d1.equals(d2)</code> is identical to
499 * <code>doubleToLongBits(d1.doubleValue()) ==
500 * doubleToLongBits(d2.doubleValue())</code>.
501 *
502 * @param obj the object to compare
503 * @return whether the objects are semantically equal
504 */
505 public boolean equals(Object obj)
506 {
507 if (obj instanceof Double)
508 {
509 double d = ((Double) obj).value;
510 return (doubleToRawLongBits(value) == doubleToRawLongBits(d)) ||
511 (isNaN(value) && isNaN(d));
512 }
513 return false;
514 }
515
516 /**
517 * Convert the double to the IEEE 754 floating-point "double format" bit
518 * layout. Bit 63 (the most significant) is the sign bit, bits 62-52
519 * (masked by 0x7ff0000000000000L) represent the exponent, and bits 51-0
520 * (masked by 0x000fffffffffffffL) are the mantissa. This function
521 * collapses all versions of NaN to 0x7ff8000000000000L. The result of this
522 * function can be used as the argument to
523 * <code>Double.longBitsToDouble(long)</code> to obtain the original
524 * <code>double</code> value.
525 *
526 * @param value the <code>double</code> to convert
527 * @return the bits of the <code>double</code>
528 * @see #longBitsToDouble(long)
529 */
530 public static long doubleToLongBits(double value)
531 {
532 if (isNaN(value))
533 return 0x7ff8000000000000L;
534 else
535 return VMDouble.doubleToRawLongBits(value);
536 }
537
538 /**
539 * Convert the double to the IEEE 754 floating-point "double format" bit
540 * layout. Bit 63 (the most significant) is the sign bit, bits 62-52
541 * (masked by 0x7ff0000000000000L) represent the exponent, and bits 51-0
542 * (masked by 0x000fffffffffffffL) are the mantissa. This function
543 * leaves NaN alone, rather than collapsing to a canonical value. The
544 * result of this function can be used as the argument to
545 * <code>Double.longBitsToDouble(long)</code> to obtain the original
546 * <code>double</code> value.
547 *
548 * @param value the <code>double</code> to convert
549 * @return the bits of the <code>double</code>
550 * @see #longBitsToDouble(long)
551 */
552 public static long doubleToRawLongBits(double value)
553 {
554 return VMDouble.doubleToRawLongBits(value);
555 }
556
557 /**
558 * Convert the argument in IEEE 754 floating-point "double format" bit
559 * layout to the corresponding float. Bit 63 (the most significant) is the
560 * sign bit, bits 62-52 (masked by 0x7ff0000000000000L) represent the
561 * exponent, and bits 51-0 (masked by 0x000fffffffffffffL) are the mantissa.
562 * This function leaves NaN alone, so that you can recover the bit pattern
563 * with <code>Double.doubleToRawLongBits(double)</code>.
564 *
565 * @param bits the bits to convert
566 * @return the <code>double</code> represented by the bits
567 * @see #doubleToLongBits(double)
568 * @see #doubleToRawLongBits(double)
569 */
570 public static double longBitsToDouble(long bits)
571 {
572 return VMDouble.longBitsToDouble(bits);
573 }
574
575 /**
576 * Compare two Doubles numerically by comparing their <code>double</code>
577 * values. The result is positive if the first is greater, negative if the
578 * second is greater, and 0 if the two are equal. However, this special
579 * cases NaN and signed zero as follows: NaN is considered greater than
580 * all other doubles, including <code>POSITIVE_INFINITY</code>, and positive
581 * zero is considered greater than negative zero.
582 *
583 * @param d the Double to compare
584 * @return the comparison
585 * @since 1.2
586 */
587 public int compareTo(Double d)
588 {
589 return compare(value, d.value);
590 }
591
592 /**
593 * Behaves like <code>new Double(x).compareTo(new Double(y))</code>; in
594 * other words this compares two doubles, special casing NaN and zero,
595 * without the overhead of objects.
596 *
597 * @param x the first double to compare
598 * @param y the second double to compare
599 * @return the comparison
600 * @since 1.4
601 */
602 public static int compare(double x, double y)
603 {
604 // handle the easy cases:
605 if (x < y)
606 return -1;
607 if (x > y)
608 return 1;
609
610 // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
611 long lx = doubleToRawLongBits(x);
612 long ly = doubleToRawLongBits(y);
613 if (lx == ly)
614 return 0;
615
616 // handle NaNs:
617 if (x != x)
618 return (y != y) ? 0 : 1;
619 else if (y != y)
620 return -1;
621
622 // handle +/- 0.0
623 return (lx < ly) ? -1 : 1;
624 }
625 }