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