OSDN Git Service

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