Source for java.lang.Float

   1: /* Float.java -- object wrapper for float
   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: 
  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:  * @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 Float extends Number implements Comparable<Float>
  58: {
  59:   /**
  60:    * Compatible with JDK 1.0+.
  61:    */
  62:   private static final long serialVersionUID = -2671257302660747028L;
  63: 
  64:   /**
  65:    * The maximum positive value a <code>double</code> may represent
  66:    * is 3.4028235e+38f.
  67:    */
  68:   public static final float MAX_VALUE = 3.4028235e+38f;
  69: 
  70:   /**
  71:    * The minimum positive value a <code>float</code> may represent
  72:    * is 1.4e-45.
  73:    */
  74:   public static final float MIN_VALUE = 1.4e-45f;
  75: 
  76:   /**
  77:    * The value of a float representation -1.0/0.0, negative infinity.
  78:    */
  79:   public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
  80: 
  81:   /**
  82:    * The value of a float representation 1.0/0.0, positive infinity.
  83:    */
  84:   public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
  85: 
  86:   /**
  87:    * All IEEE 754 values of NaN have the same value in Java.
  88:    */
  89:   public static final float NaN = 0.0f / 0.0f;
  90: 
  91:   /**
  92:    * The primitive type <code>float</code> is represented by this
  93:    * <code>Class</code> object.
  94:    * @since 1.1
  95:    */
  96:   public static final Class<Float> TYPE = (Class<Float>) VMClassLoader.getPrimitiveClass('F');
  97: 
  98:   /**
  99:    * 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>&lt;number&gt;</code>" means a string of digits ('0' to '9').
 154:    * "<code>&lt;digit&gt;</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>[-]&lt;digit&gt;.&lt;number&gt;
 163:    *          E[-]&lt;number&gt;</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 VMDouble.toString(f, true);
 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>s</code> cannot be parsed as a
 335:    *         <code>float</code>
 336:    * @throws NullPointerException if <code>s</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:     // XXX Rounding parseDouble() causes some errors greater than 1 ulp from
 346:     // the infinitely precise decimal.
 347:     return (float) Double.parseDouble(str);
 348:   }
 349: 
 350:   /**
 351:    * Return <code>true</code> if the <code>float</code> has the same
 352:    * value as <code>NaN</code>, otherwise return <code>false</code>.
 353:    *
 354:    * @param v the <code>float</code> to compare
 355:    * @return whether the argument is <code>NaN</code>
 356:    */
 357:   public static boolean isNaN(float v)
 358:   {
 359:     // This works since NaN != NaN is the only reflexive inequality
 360:     // comparison which returns true.
 361:     return v != v;
 362:   }
 363: 
 364:   /**
 365:    * Return <code>true</code> if the <code>float</code> has a value
 366:    * equal to either <code>NEGATIVE_INFINITY</code> or
 367:    * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
 368:    *
 369:    * @param v the <code>float</code> to compare
 370:    * @return whether the argument is (-/+) infinity
 371:    */
 372:   public static boolean isInfinite(float v)
 373:   {
 374:     return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
 375:   }
 376: 
 377:   /**
 378:    * Return <code>true</code> if the value of this <code>Float</code>
 379:    * is the same as <code>NaN</code>, otherwise return <code>false</code>.
 380:    *
 381:    * @return whether this <code>Float</code> is <code>NaN</code>
 382:    */
 383:   public boolean isNaN()
 384:   {
 385:     return isNaN(value);
 386:   }
 387: 
 388:   /**
 389:    * Return <code>true</code> if the value of this <code>Float</code>
 390:    * is the same as <code>NEGATIVE_INFINITY</code> or
 391:    * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
 392:    *
 393:    * @return whether this <code>Float</code> is (-/+) infinity
 394:    */
 395:   public boolean isInfinite()
 396:   {
 397:     return isInfinite(value);
 398:   }
 399: 
 400:   /**
 401:    * Convert the <code>float</code> value of this <code>Float</code>
 402:    * to a <code>String</code>.  This method calls
 403:    * <code>Float.toString(float)</code> to do its dirty work.
 404:    *
 405:    * @return the <code>String</code> representation
 406:    * @see #toString(float)
 407:    */
 408:   public String toString()
 409:   {
 410:     return toString(value);
 411:   }
 412: 
 413:   /**
 414:    * Return the value of this <code>Float</code> as a <code>byte</code>.
 415:    *
 416:    * @return the byte value
 417:    * @since 1.1
 418:    */
 419:   public byte byteValue()
 420:   {
 421:     return (byte) value;
 422:   }
 423: 
 424:   /**
 425:    * Return the value of this <code>Float</code> as a <code>short</code>.
 426:    *
 427:    * @return the short value
 428:    * @since 1.1
 429:    */
 430:   public short shortValue()
 431:   {
 432:     return (short) value;
 433:   }
 434: 
 435:   /**
 436:    * Return the value of this <code>Integer</code> as an <code>int</code>.
 437:    *
 438:    * @return the int value
 439:    */
 440:   public int intValue()
 441:   {
 442:     return (int) value;
 443:   }
 444: 
 445:   /**
 446:    * Return the value of this <code>Integer</code> as a <code>long</code>.
 447:    *
 448:    * @return the long value
 449:    */
 450:   public long longValue()
 451:   {
 452:     return (long) value;
 453:   }
 454: 
 455:   /**
 456:    * Return the value of this <code>Float</code>.
 457:    *
 458:    * @return the float value
 459:    */
 460:   public float floatValue()
 461:   {
 462:     return value;
 463:   }
 464: 
 465:   /**
 466:    * Return the value of this <code>Float</code> as a <code>double</code>
 467:    *
 468:    * @return the double value
 469:    */
 470:   public double doubleValue()
 471:   {
 472:     return value;
 473:   }
 474: 
 475:   /**
 476:    * Return a hashcode representing this Object. <code>Float</code>'s hash
 477:    * code is calculated by calling <code>floatToIntBits(floatValue())</code>.
 478:    *
 479:    * @return this Object's hash code
 480:    * @see #floatToIntBits(float)
 481:    */
 482:   public int hashCode()
 483:   {
 484:     return floatToIntBits(value);
 485:   }
 486: 
 487:   /**
 488:    * Returns <code>true</code> if <code>obj</code> is an instance of
 489:    * <code>Float</code> and represents the same float value. Unlike comparing
 490:    * two floats with <code>==</code>, this treats two instances of
 491:    * <code>Float.NaN</code> as equal, but treats <code>0.0</code> and
 492:    * <code>-0.0</code> as unequal.
 493:    *
 494:    * <p>Note that <code>f1.equals(f2)</code> is identical to
 495:    * <code>floatToIntBits(f1.floatValue()) ==
 496:    *    floatToIntBits(f2.floatValue())</code>.
 497:    *
 498:    * @param obj the object to compare
 499:    * @return whether the objects are semantically equal
 500:    */
 501:   public boolean equals(Object obj)
 502:   {
 503:     if (! (obj instanceof Float))
 504:       return false;
 505: 
 506:     float f = ((Float) obj).value;
 507: 
 508:     // Avoid call to native method. However, some implementations, like gcj,
 509:     // are better off using floatToIntBits(value) == floatToIntBits(f).
 510:     // Check common case first, then check NaN and 0.
 511:     if (value == f)
 512:       return (value != 0) || (1 / value == 1 / f);
 513:     return isNaN(value) && isNaN(f);
 514:   }
 515: 
 516:   /**
 517:    * Convert the float to the IEEE 754 floating-point "single format" bit
 518:    * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
 519:    * (masked by 0x7f800000) represent the exponent, and bits 22-0
 520:    * (masked by 0x007fffff) are the mantissa. This function collapses all
 521:    * versions of NaN to 0x7fc00000. The result of this function can be used
 522:    * as the argument to <code>Float.intBitsToFloat(int)</code> to obtain the
 523:    * original <code>float</code> value.
 524:    *
 525:    * @param value the <code>float</code> to convert
 526:    * @return the bits of the <code>float</code>
 527:    * @see #intBitsToFloat(int)
 528:    */
 529:   public static int floatToIntBits(float value)
 530:   {
 531:     return VMFloat.floatToIntBits(value);
 532:   }
 533: 
 534:   /**
 535:    * Convert the float to the IEEE 754 floating-point "single format" bit
 536:    * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
 537:    * (masked by 0x7f800000) represent the exponent, and bits 22-0
 538:    * (masked by 0x007fffff) are the mantissa. This function leaves NaN alone,
 539:    * rather than collapsing to a canonical value. The result of this function
 540:    * can be used as the argument to <code>Float.intBitsToFloat(int)</code> to
 541:    * obtain the original <code>float</code> value.
 542:    *
 543:    * @param value the <code>float</code> to convert
 544:    * @return the bits of the <code>float</code>
 545:    * @see #intBitsToFloat(int)
 546:    */
 547:   public static int floatToRawIntBits(float value)
 548:   {
 549:     return VMFloat.floatToRawIntBits(value);
 550:   }
 551: 
 552:   /**
 553:    * Convert the argument in IEEE 754 floating-point "single format" bit
 554:    * layout to the corresponding float. Bit 31 (the most significant) is the
 555:    * sign bit, bits 30-23 (masked by 0x7f800000) represent the exponent, and
 556:    * bits 22-0 (masked by 0x007fffff) are the mantissa. This function leaves
 557:    * NaN alone, so that you can recover the bit pattern with
 558:    * <code>Float.floatToRawIntBits(float)</code>.
 559:    *
 560:    * @param bits the bits to convert
 561:    * @return the <code>float</code> represented by the bits
 562:    * @see #floatToIntBits(float)
 563:    * @see #floatToRawIntBits(float)
 564:    */
 565:   public static float intBitsToFloat(int bits)
 566:   {
 567:     return VMFloat.intBitsToFloat(bits);
 568:   }
 569: 
 570:   /**
 571:    * Compare two Floats numerically by comparing their <code>float</code>
 572:    * values. The result is positive if the first is greater, negative if the
 573:    * second is greater, and 0 if the two are equal. However, this special
 574:    * cases NaN and signed zero as follows: NaN is considered greater than
 575:    * all other floats, including <code>POSITIVE_INFINITY</code>, and positive
 576:    * zero is considered greater than negative zero.
 577:    *
 578:    * @param f the Float to compare
 579:    * @return the comparison
 580:    * @since 1.2
 581:    */
 582:   public int compareTo(Float f)
 583:   {
 584:     return compare(value, f.value);
 585:   }
 586: 
 587:   /**
 588:    * Behaves like <code>new Float(x).compareTo(new Float(y))</code>; in
 589:    * other words this compares two floats, special casing NaN and zero,
 590:    * without the overhead of objects.
 591:    *
 592:    * @param x the first float to compare
 593:    * @param y the second float to compare
 594:    * @return the comparison
 595:    * @since 1.4
 596:    */
 597:   public static int compare(float x, float y)
 598:   {
 599:     if (isNaN(x))
 600:       return isNaN(y) ? 0 : 1;
 601:     if (isNaN(y))
 602:       return -1;
 603:     // recall that 0.0 == -0.0, so we convert to infinities and try again
 604:     if (x == 0 && y == 0)
 605:       return (int) (1 / x - 1 / y);
 606:     if (x == y)
 607:       return 0;
 608: 
 609:     return x > y ? 1 : -1;
 610:   }
 611: }