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