Source for java.lang.Float

   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:    * Convert a float value to a hexadecimal string.  This converts as
 187:    * follows:
 188:    * <ul>
 189:    * <li> A NaN value is converted to the string "NaN".
 190:    * <li> Positive infinity is converted to the string "Infinity".
 191:    * <li> Negative infinity is converted to the string "-Infinity".
 192:    * <li> For all other values, the first character of the result is '-'
 193:    * if the value is negative.  This is followed by '0x1.' if the
 194:    * value is normal, and '0x0.' if the value is denormal.  This is
 195:    * then followed by a (lower-case) hexadecimal representation of the
 196:    * mantissa, with leading zeros as required for denormal values.
 197:    * The next character is a 'p', and this is followed by a decimal
 198:    * representation of the unbiased exponent.
 199:    * </ul>
 200:    * @param f the float value
 201:    * @return the hexadecimal string representation
 202:    * @since 1.5
 203:    */
 204:   public static String toHexString(float f)
 205:   {
 206:     if (isNaN(f))
 207:       return "NaN";
 208:     if (isInfinite(f))
 209:       return f < 0 ? "-Infinity" : "Infinity";
 210: 
 211:     int bits = floatToIntBits(f);
 212:     StringBuilder result = new StringBuilder();
 213:     
 214:     if (bits < 0)
 215:       result.append('-');
 216:     result.append("0x");
 217: 
 218:     final int mantissaBits = 23;
 219:     final int exponentBits = 8;
 220:     int mantMask = (1 << mantissaBits) - 1;
 221:     int mantissa = bits & mantMask;
 222:     int expMask = (1 << exponentBits) - 1;
 223:     int exponent = (bits >>> mantissaBits) & expMask;
 224: 
 225:     result.append(exponent == 0 ? '0' : '1');
 226:     result.append('.');
 227:     // For Float only, we have to adjust the mantissa.
 228:     mantissa <<= 1;
 229:     result.append(Integer.toHexString(mantissa));
 230:     if (exponent == 0 && mantissa != 0)
 231:       {
 232:         // Treat denormal specially by inserting '0's to make
 233:         // the length come out right.  The constants here are
 234:         // to account for things like the '0x'.
 235:         int offset = 4 + ((bits < 0) ? 1 : 0);
 236:         // The silly +3 is here to keep the code the same between
 237:         // the Float and Double cases.  In Float the value is
 238:         // not a multiple of 4.
 239:         int desiredLength = offset + (mantissaBits + 3) / 4;
 240:         while (result.length() < desiredLength)
 241:           result.insert(offset, '0');
 242:       }
 243:     result.append('p');
 244:     if (exponent == 0 && mantissa == 0)
 245:       {
 246:         // Zero, so do nothing special.
 247:       }
 248:     else
 249:       {
 250:         // Apply bias.
 251:         boolean denormal = exponent == 0;
 252:         exponent -= (1 << (exponentBits - 1)) - 1;
 253:         // Handle denormal.
 254:         if (denormal)
 255:           ++exponent;
 256:       }
 257: 
 258:     result.append(Integer.toString(exponent));
 259:     return result.toString();
 260:   }
 261: 
 262:   /**
 263:    * Creates a new <code>Float</code> object using the <code>String</code>.
 264:    *
 265:    * @param s the <code>String</code> to convert
 266:    * @return the new <code>Float</code>
 267:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 268:    *         <code>float</code>
 269:    * @throws NullPointerException if <code>s</code> is null
 270:    * @see #parseFloat(String)
 271:    */
 272:   public static Float valueOf(String s)
 273:   {
 274:     return new Float(parseFloat(s));
 275:   }
 276: 
 277:   /**
 278:    * Returns a <code>Float</code> object wrapping the value.
 279:    * In contrast to the <code>Float</code> constructor, this method
 280:    * may cache some values.  It is used by boxing conversion.
 281:    *
 282:    * @param val the value to wrap
 283:    * @return the <code>Float</code>
 284:    * 
 285:    * @since 1.5
 286:    */
 287:   public static Float valueOf(float val)
 288:   {
 289:     // We don't actually cache, but we could.
 290:     return new Float(val);
 291:   }
 292: 
 293:   /**
 294:    * Parse the specified <code>String</code> as a <code>float</code>. The
 295:    * extended BNF grammar is as follows:<br>
 296:    * <pre>
 297:    * <em>DecodableString</em>:
 298:    *      ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
 299:    *    | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
 300:    *    | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
 301:    *              [ <code>f</code> | <code>F</code> | <code>d</code>
 302:    *                | <code>D</code>] )
 303:    * <em>FloatingPoint</em>:
 304:    *      ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
 305:    *              [ <em>Exponent</em> ] )
 306:    *    | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
 307:    * <em>Exponent</em>:
 308:    *      ( ( <code>e</code> | <code>E</code> )
 309:    *              [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
 310:    * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
 311:    * </pre>
 312:    *
 313:    * <p>NaN and infinity are special cases, to allow parsing of the output
 314:    * of toString.  Otherwise, the result is determined by calculating
 315:    * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
 316:    * to the nearest float. Remember that many numbers cannot be precisely
 317:    * represented in floating point. In case of overflow, infinity is used,
 318:    * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
 319:    * this does not accept Unicode digits outside the ASCII range.
 320:    *
 321:    * <p>If an unexpected character is found in the <code>String</code>, a
 322:    * <code>NumberFormatException</code> will be thrown.  Leading and trailing
 323:    * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
 324:    * internal to the actual number are not allowed.
 325:    *
 326:    * <p>To parse numbers according to another format, consider using
 327:    * {@link java.text.NumberFormat}.
 328:    *
 329:    * @XXX specify where/how we are not in accord with the spec.
 330:    *
 331:    * @param str the <code>String</code> to convert
 332:    * @return the <code>float</code> value of <code>s</code>
 333:    * @throws NumberFormatException if <code>s</code> cannot be parsed as a
 334:    *         <code>float</code>
 335:    * @throws NullPointerException if <code>s</code> is null
 336:    * @see #MIN_VALUE
 337:    * @see #MAX_VALUE
 338:    * @see #POSITIVE_INFINITY
 339:    * @see #NEGATIVE_INFINITY
 340:    * @since 1.2
 341:    */
 342:   public static float parseFloat(String str)
 343:   {
 344:     // XXX Rounding parseDouble() causes some errors greater than 1 ulp from
 345:     // the infinitely precise decimal.
 346:     return (float) Double.parseDouble(str);
 347:   }
 348: 
 349:   /**
 350:    * Return <code>true</code> if the <code>float</code> has the same
 351:    * value as <code>NaN</code>, otherwise return <code>false</code>.
 352:    *
 353:    * @param v the <code>float</code> to compare
 354:    * @return whether the argument is <code>NaN</code>
 355:    */
 356:   public static boolean isNaN(float v)
 357:   {
 358:     // This works since NaN != NaN is the only reflexive inequality
 359:     // comparison which returns true.
 360:     return v != v;
 361:   }
 362: 
 363:   /**
 364:    * Return <code>true</code> if the <code>float</code> has a value
 365:    * equal to either <code>NEGATIVE_INFINITY</code> or
 366:    * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
 367:    *
 368:    * @param v the <code>float</code> to compare
 369:    * @return whether the argument is (-/+) infinity
 370:    */
 371:   public static boolean isInfinite(float v)
 372:   {
 373:     return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
 374:   }
 375: 
 376:   /**
 377:    * Return <code>true</code> if the value of this <code>Float</code>
 378:    * is the same as <code>NaN</code>, otherwise return <code>false</code>.
 379:    *
 380:    * @return whether this <code>Float</code> is <code>NaN</code>
 381:    */
 382:   public boolean isNaN()
 383:   {
 384:     return isNaN(value);
 385:   }
 386: 
 387:   /**
 388:    * Return <code>true</code> if the value of this <code>Float</code>
 389:    * is the same as <code>NEGATIVE_INFINITY</code> or
 390:    * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
 391:    *
 392:    * @return whether this <code>Float</code> is (-/+) infinity
 393:    */
 394:   public boolean isInfinite()
 395:   {
 396:     return isInfinite(value);
 397:   }
 398: 
 399:   /**
 400:    * Convert the <code>float</code> value of this <code>Float</code>
 401:    * to a <code>String</code>.  This method calls
 402:    * <code>Float.toString(float)</code> to do its dirty work.
 403:    *
 404:    * @return the <code>String</code> representation
 405:    * @see #toString(float)
 406:    */
 407:   public String toString()
 408:   {
 409:     return toString(value);
 410:   }
 411: 
 412:   /**
 413:    * Return the value of this <code>Float</code> as a <code>byte</code>.
 414:    *
 415:    * @return the byte value
 416:    * @since 1.1
 417:    */
 418:   public byte byteValue()
 419:   {
 420:     return (byte) value;
 421:   }
 422: 
 423:   /**
 424:    * Return the value of this <code>Float</code> as a <code>short</code>.
 425:    *
 426:    * @return the short value
 427:    * @since 1.1
 428:    */
 429:   public short shortValue()
 430:   {
 431:     return (short) value;
 432:   }
 433: 
 434:   /**
 435:    * Return the value of this <code>Integer</code> as an <code>int</code>.
 436:    *
 437:    * @return the int value
 438:    */
 439:   public int intValue()
 440:   {
 441:     return (int) value;
 442:   }
 443: 
 444:   /**
 445:    * Return the value of this <code>Integer</code> as a <code>long</code>.
 446:    *
 447:    * @return the long value
 448:    */
 449:   public long longValue()
 450:   {
 451:     return (long) value;
 452:   }
 453: 
 454:   /**
 455:    * Return the value of this <code>Float</code>.
 456:    *
 457:    * @return the float value
 458:    */
 459:   public float floatValue()
 460:   {
 461:     return value;
 462:   }
 463: 
 464:   /**
 465:    * Return the value of this <code>Float</code> as a <code>double</code>
 466:    *
 467:    * @return the double value
 468:    */
 469:   public double doubleValue()
 470:   {
 471:     return value;
 472:   }
 473: 
 474:   /**
 475:    * Return a hashcode representing this Object. <code>Float</code>'s hash
 476:    * code is calculated by calling <code>floatToIntBits(floatValue())</code>.
 477:    *
 478:    * @return this Object's hash code
 479:    * @see #floatToIntBits(float)
 480:    */
 481:   public int hashCode()
 482:   {
 483:     return floatToIntBits(value);
 484:   }
 485: 
 486:   /**
 487:    * Returns <code>true</code> if <code>obj</code> is an instance of
 488:    * <code>Float</code> and represents the same float value. Unlike comparing
 489:    * two floats with <code>==</code>, this treats two instances of
 490:    * <code>Float.NaN</code> as equal, but treats <code>0.0</code> and
 491:    * <code>-0.0</code> as unequal.
 492:    *
 493:    * <p>Note that <code>f1.equals(f2)</code> is identical to
 494:    * <code>floatToIntBits(f1.floatValue()) ==
 495:    *    floatToIntBits(f2.floatValue())</code>.
 496:    *
 497:    * @param obj the object to compare
 498:    * @return whether the objects are semantically equal
 499:    */
 500:   public boolean equals(Object obj)
 501:   {
 502:     if (! (obj instanceof Float))
 503:       return false;
 504: 
 505:     float f = ((Float) obj).value;
 506: 
 507:     // Avoid call to native method. However, some implementations, like gcj,
 508:     // are better off using floatToIntBits(value) == floatToIntBits(f).
 509:     // Check common case first, then check NaN and 0.
 510:     if (value == f)
 511:       return (value != 0) || (1 / value == 1 / f);
 512:     return isNaN(value) && isNaN(f);
 513:   }
 514: 
 515:   /**
 516:    * Convert the float to the IEEE 754 floating-point "single format" bit
 517:    * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
 518:    * (masked by 0x7f800000) represent the exponent, and bits 22-0
 519:    * (masked by 0x007fffff) are the mantissa. This function collapses all
 520:    * versions of NaN to 0x7fc00000. The result of this function can be used
 521:    * as the argument to <code>Float.intBitsToFloat(int)</code> to obtain the
 522:    * original <code>float</code> value.
 523:    *
 524:    * @param value the <code>float</code> to convert
 525:    * @return the bits of the <code>float</code>
 526:    * @see #intBitsToFloat(int)
 527:    */
 528:   public static int floatToIntBits(float value)
 529:   {
 530:     return VMFloat.floatToIntBits(value);
 531:   }
 532: 
 533:   /**
 534:    * Convert the float to the IEEE 754 floating-point "single format" bit
 535:    * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
 536:    * (masked by 0x7f800000) represent the exponent, and bits 22-0
 537:    * (masked by 0x007fffff) are the mantissa. This function leaves NaN alone,
 538:    * rather than collapsing to a canonical value. The result of this function
 539:    * can be used as the argument to <code>Float.intBitsToFloat(int)</code> to
 540:    * obtain the original <code>float</code> value.
 541:    *
 542:    * @param value the <code>float</code> to convert
 543:    * @return the bits of the <code>float</code>
 544:    * @see #intBitsToFloat(int)
 545:    */
 546:   public static int floatToRawIntBits(float value)
 547:   {
 548:     return VMFloat.floatToRawIntBits(value);
 549:   }
 550: 
 551:   /**
 552:    * Convert the argument in IEEE 754 floating-point "single format" bit
 553:    * layout to the corresponding float. Bit 31 (the most significant) is the
 554:    * sign bit, bits 30-23 (masked by 0x7f800000) represent the exponent, and
 555:    * bits 22-0 (masked by 0x007fffff) are the mantissa. This function leaves
 556:    * NaN alone, so that you can recover the bit pattern with
 557:    * <code>Float.floatToRawIntBits(float)</code>.
 558:    *
 559:    * @param bits the bits to convert
 560:    * @return the <code>float</code> represented by the bits
 561:    * @see #floatToIntBits(float)
 562:    * @see #floatToRawIntBits(float)
 563:    */
 564:   public static float intBitsToFloat(int bits)
 565:   {
 566:     return VMFloat.intBitsToFloat(bits);
 567:   }
 568: 
 569:   /**
 570:    * Compare two Floats numerically by comparing their <code>float</code>
 571:    * values. The result is positive if the first is greater, negative if the
 572:    * second is greater, and 0 if the two are equal. However, this special
 573:    * cases NaN and signed zero as follows: NaN is considered greater than
 574:    * all other floats, including <code>POSITIVE_INFINITY</code>, and positive
 575:    * zero is considered greater than negative zero.
 576:    *
 577:    * @param f the Float to compare
 578:    * @return the comparison
 579:    * @since 1.2
 580:    */
 581:   public int compareTo(Float f)
 582:   {
 583:     return compare(value, f.value);
 584:   }
 585: 
 586:   /**
 587:    * Behaves like <code>compareTo(Float)</code> unless the Object
 588:    * is not an <code>Float</code>.
 589:    *
 590:    * @param o the object to compare
 591:    * @return the comparison
 592:    * @throws ClassCastException if the argument is not a <code>Float</code>
 593:    * @see #compareTo(Float)
 594:    * @see Comparable
 595:    * @since 1.2
 596:    */
 597:   public int compareTo(Object o)
 598:   {
 599:     return compare(value, ((Float) o).value);
 600:   }
 601: 
 602:   /**
 603:    * Behaves like <code>new Float(x).compareTo(new Float(y))</code>; in
 604:    * other words this compares two floats, special casing NaN and zero,
 605:    * without the overhead of objects.
 606:    *
 607:    * @param x the first float to compare
 608:    * @param y the second float to compare
 609:    * @return the comparison
 610:    * @since 1.4
 611:    */
 612:   public static int compare(float x, float y)
 613:   {
 614:     if (isNaN(x))
 615:       return isNaN(y) ? 0 : 1;
 616:     if (isNaN(y))
 617:       return -1;
 618:     // recall that 0.0 == -0.0, so we convert to infinities and try again
 619:     if (x == 0 && y == 0)
 620:       return (int) (1 / x - 1 / y);
 621:     if (x == y)
 622:       return 0;
 623: 
 624:     return x > y ? 1 : -1;
 625:   }
 626: }