Float.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. /* Float.java -- object wrapper for float
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.lang;
  33. import gnu.java.lang.CPStringBuilder;
  34. /**
  35. * Instances of class <code>Float</code> represent primitive
  36. * <code>float</code> values.
  37. *
  38. * Additionally, this class provides various helper functions and variables
  39. * related to floats.
  40. *
  41. * @author Paul Fisher
  42. * @author Andrew Haley (aph@cygnus.com)
  43. * @author Eric Blake (ebb9@email.byu.edu)
  44. * @author Tom Tromey (tromey@redhat.com)
  45. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  46. * @since 1.0
  47. * @status partly updated to 1.5
  48. */
  49. public final class Float extends Number implements Comparable<Float>
  50. {
  51. /**
  52. * Compatible with JDK 1.0+.
  53. */
  54. private static final long serialVersionUID = -2671257302660747028L;
  55. /**
  56. * The maximum positive value a <code>double</code> may represent
  57. * is 3.4028235e+38f.
  58. */
  59. public static final float MAX_VALUE = 3.4028235e+38f;
  60. /**
  61. * The minimum positive value a <code>float</code> may represent
  62. * is 1.4e-45.
  63. */
  64. public static final float MIN_VALUE = 1.4e-45f;
  65. /**
  66. * The value of a float representation -1.0/0.0, negative infinity.
  67. */
  68. public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
  69. /**
  70. * The value of a float representation 1.0/0.0, positive infinity.
  71. */
  72. public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
  73. /**
  74. * All IEEE 754 values of NaN have the same value in Java.
  75. */
  76. public static final float NaN = 0.0f / 0.0f;
  77. /**
  78. * The primitive type <code>float</code> is represented by this
  79. * <code>Class</code> object.
  80. * @since 1.1
  81. */
  82. public static final Class<Float> TYPE = (Class<Float>) VMClassLoader.getPrimitiveClass('F');
  83. /**
  84. * The number of bits needed to represent a <code>float</code>.
  85. * @since 1.5
  86. */
  87. public static final int SIZE = 32;
  88. /**
  89. * Cache representation of 0
  90. */
  91. private static final Float ZERO = new Float(0.0f);
  92. /**
  93. * Cache representation of 1
  94. */
  95. private static final Float ONE = new Float(1.0f);
  96. /**
  97. * The immutable value of this Float.
  98. *
  99. * @serial the wrapped float
  100. */
  101. private final float value;
  102. /**
  103. * Create a <code>Float</code> from the primitive <code>float</code>
  104. * specified.
  105. *
  106. * @param value the <code>float</code> argument
  107. */
  108. public Float(float value)
  109. {
  110. this.value = value;
  111. }
  112. /**
  113. * Create a <code>Float</code> from the primitive <code>double</code>
  114. * specified.
  115. *
  116. * @param value the <code>double</code> argument
  117. */
  118. public Float(double value)
  119. {
  120. this.value = (float) value;
  121. }
  122. /**
  123. * Create a <code>Float</code> from the specified <code>String</code>.
  124. * This method calls <code>Float.parseFloat()</code>.
  125. *
  126. * @param s the <code>String</code> to convert
  127. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  128. * <code>float</code>
  129. * @throws NullPointerException if <code>s</code> is null
  130. * @see #parseFloat(String)
  131. */
  132. public Float(String s)
  133. {
  134. value = parseFloat(s);
  135. }
  136. /**
  137. * Convert the <code>float</code> to a <code>String</code>.
  138. * Floating-point string representation is fairly complex: here is a
  139. * rundown of the possible values. "<code>[-]</code>" indicates that a
  140. * negative sign will be printed if the value (or exponent) is negative.
  141. * "<code>&lt;number&gt;</code>" means a string of digits ('0' to '9').
  142. * "<code>&lt;digit&gt;</code>" means a single digit ('0' to '9').<br>
  143. *
  144. * <table border=1>
  145. * <tr><th>Value of Float</th><th>String Representation</th></tr>
  146. * <tr><td>[+-] 0</td> <td><code>[-]0.0</code></td></tr>
  147. * <tr><td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
  148. * <td><code>[-]number.number</code></td></tr>
  149. * <tr><td>Other numeric value</td>
  150. * <td><code>[-]&lt;digit&gt;.&lt;number&gt;
  151. * E[-]&lt;number&gt;</code></td></tr>
  152. * <tr><td>[+-] infinity</td> <td><code>[-]Infinity</code></td></tr>
  153. * <tr><td>NaN</td> <td><code>NaN</code></td></tr>
  154. * </table>
  155. *
  156. * Yes, negative zero <em>is</em> a possible value. Note that there is
  157. * <em>always</em> a <code>.</code> and at least one digit printed after
  158. * it: even if the number is 3, it will be printed as <code>3.0</code>.
  159. * After the ".", all digits will be printed except trailing zeros. The
  160. * result is rounded to the shortest decimal number which will parse back
  161. * to the same float.
  162. *
  163. * <p>To create other output formats, use {@link java.text.NumberFormat}.
  164. *
  165. * @XXX specify where we are not in accord with the spec.
  166. *
  167. * @param f the <code>float</code> to convert
  168. * @return the <code>String</code> representing the <code>float</code>
  169. */
  170. public static String toString(float f)
  171. {
  172. return VMFloat.toString(f);
  173. }
  174. /**
  175. * Convert a float value to a hexadecimal string. This converts as
  176. * follows:
  177. * <ul>
  178. * <li> A NaN value is converted to the string "NaN".
  179. * <li> Positive infinity is converted to the string "Infinity".
  180. * <li> Negative infinity is converted to the string "-Infinity".
  181. * <li> For all other values, the first character of the result is '-'
  182. * if the value is negative. This is followed by '0x1.' if the
  183. * value is normal, and '0x0.' if the value is denormal. This is
  184. * then followed by a (lower-case) hexadecimal representation of the
  185. * mantissa, with leading zeros as required for denormal values.
  186. * The next character is a 'p', and this is followed by a decimal
  187. * representation of the unbiased exponent.
  188. * </ul>
  189. * @param f the float value
  190. * @return the hexadecimal string representation
  191. * @since 1.5
  192. */
  193. public static String toHexString(float f)
  194. {
  195. if (isNaN(f))
  196. return "NaN";
  197. if (isInfinite(f))
  198. return f < 0 ? "-Infinity" : "Infinity";
  199. int bits = floatToIntBits(f);
  200. CPStringBuilder result = new CPStringBuilder();
  201. if (bits < 0)
  202. result.append('-');
  203. result.append("0x");
  204. final int mantissaBits = 23;
  205. final int exponentBits = 8;
  206. int mantMask = (1 << mantissaBits) - 1;
  207. int mantissa = bits & mantMask;
  208. int expMask = (1 << exponentBits) - 1;
  209. int exponent = (bits >>> mantissaBits) & expMask;
  210. result.append(exponent == 0 ? '0' : '1');
  211. result.append('.');
  212. // For Float only, we have to adjust the mantissa.
  213. mantissa <<= 1;
  214. result.append(Integer.toHexString(mantissa));
  215. if (exponent == 0 && mantissa != 0)
  216. {
  217. // Treat denormal specially by inserting '0's to make
  218. // the length come out right. The constants here are
  219. // to account for things like the '0x'.
  220. int offset = 4 + ((bits < 0) ? 1 : 0);
  221. // The silly +3 is here to keep the code the same between
  222. // the Float and Double cases. In Float the value is
  223. // not a multiple of 4.
  224. int desiredLength = offset + (mantissaBits + 3) / 4;
  225. while (result.length() < desiredLength)
  226. result.insert(offset, '0');
  227. }
  228. result.append('p');
  229. if (exponent == 0 && mantissa == 0)
  230. {
  231. // Zero, so do nothing special.
  232. }
  233. else
  234. {
  235. // Apply bias.
  236. boolean denormal = exponent == 0;
  237. exponent -= (1 << (exponentBits - 1)) - 1;
  238. // Handle denormal.
  239. if (denormal)
  240. ++exponent;
  241. }
  242. result.append(Integer.toString(exponent));
  243. return result.toString();
  244. }
  245. /**
  246. * Creates a new <code>Float</code> object using the <code>String</code>.
  247. *
  248. * @param s the <code>String</code> to convert
  249. * @return the new <code>Float</code>
  250. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  251. * <code>float</code>
  252. * @throws NullPointerException if <code>s</code> is null
  253. * @see #parseFloat(String)
  254. */
  255. public static Float valueOf(String s)
  256. {
  257. return valueOf(parseFloat(s));
  258. }
  259. /**
  260. * Returns a <code>Float</code> object wrapping the value.
  261. * In contrast to the <code>Float</code> constructor, this method
  262. * may cache some values. It is used by boxing conversion.
  263. *
  264. * @param val the value to wrap
  265. * @return the <code>Float</code>
  266. * @since 1.5
  267. */
  268. public static Float valueOf(float val)
  269. {
  270. if ((val == 0.0) && (floatToRawIntBits(val) == 0))
  271. return ZERO;
  272. else if (val == 1.0)
  273. return ONE;
  274. else
  275. return new Float(val);
  276. }
  277. /**
  278. * Parse the specified <code>String</code> as a <code>float</code>. The
  279. * extended BNF grammar is as follows:<br>
  280. * <pre>
  281. * <em>DecodableString</em>:
  282. * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
  283. * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
  284. * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
  285. * [ <code>f</code> | <code>F</code> | <code>d</code>
  286. * | <code>D</code>] )
  287. * <em>FloatingPoint</em>:
  288. * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
  289. * [ <em>Exponent</em> ] )
  290. * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
  291. * <em>Exponent</em>:
  292. * ( ( <code>e</code> | <code>E</code> )
  293. * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
  294. * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
  295. * </pre>
  296. *
  297. * <p>NaN and infinity are special cases, to allow parsing of the output
  298. * of toString. Otherwise, the result is determined by calculating
  299. * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
  300. * to the nearest float. Remember that many numbers cannot be precisely
  301. * represented in floating point. In case of overflow, infinity is used,
  302. * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
  303. * this does not accept Unicode digits outside the ASCII range.
  304. *
  305. * <p>If an unexpected character is found in the <code>String</code>, a
  306. * <code>NumberFormatException</code> will be thrown. Leading and trailing
  307. * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
  308. * internal to the actual number are not allowed.
  309. *
  310. * <p>To parse numbers according to another format, consider using
  311. * {@link java.text.NumberFormat}.
  312. *
  313. * @XXX specify where/how we are not in accord with the spec.
  314. *
  315. * @param str the <code>String</code> to convert
  316. * @return the <code>float</code> value of <code>s</code>
  317. * @throws NumberFormatException if <code>str</code> cannot be parsed as a
  318. * <code>float</code>
  319. * @throws NullPointerException if <code>str</code> is null
  320. * @see #MIN_VALUE
  321. * @see #MAX_VALUE
  322. * @see #POSITIVE_INFINITY
  323. * @see #NEGATIVE_INFINITY
  324. * @since 1.2
  325. */
  326. public static float parseFloat(String str)
  327. {
  328. return VMFloat.parseFloat(str);
  329. }
  330. /**
  331. * Return <code>true</code> if the <code>float</code> has the same
  332. * value as <code>NaN</code>, otherwise return <code>false</code>.
  333. *
  334. * @param v the <code>float</code> to compare
  335. * @return whether the argument is <code>NaN</code>
  336. */
  337. public static boolean isNaN(float v)
  338. {
  339. // This works since NaN != NaN is the only reflexive inequality
  340. // comparison which returns true.
  341. return v != v;
  342. }
  343. /**
  344. * Return <code>true</code> if the <code>float</code> has a value
  345. * equal to either <code>NEGATIVE_INFINITY</code> or
  346. * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
  347. *
  348. * @param v the <code>float</code> to compare
  349. * @return whether the argument is (-/+) infinity
  350. */
  351. public static boolean isInfinite(float v)
  352. {
  353. return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
  354. }
  355. /**
  356. * Return <code>true</code> if the value of this <code>Float</code>
  357. * is the same as <code>NaN</code>, otherwise return <code>false</code>.
  358. *
  359. * @return whether this <code>Float</code> is <code>NaN</code>
  360. */
  361. public boolean isNaN()
  362. {
  363. return isNaN(value);
  364. }
  365. /**
  366. * Return <code>true</code> if the value of this <code>Float</code>
  367. * is the same as <code>NEGATIVE_INFINITY</code> or
  368. * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
  369. *
  370. * @return whether this <code>Float</code> is (-/+) infinity
  371. */
  372. public boolean isInfinite()
  373. {
  374. return isInfinite(value);
  375. }
  376. /**
  377. * Convert the <code>float</code> value of this <code>Float</code>
  378. * to a <code>String</code>. This method calls
  379. * <code>Float.toString(float)</code> to do its dirty work.
  380. *
  381. * @return the <code>String</code> representation
  382. * @see #toString(float)
  383. */
  384. public String toString()
  385. {
  386. return toString(value);
  387. }
  388. /**
  389. * Return the value of this <code>Float</code> as a <code>byte</code>.
  390. *
  391. * @return the byte value
  392. * @since 1.1
  393. */
  394. public byte byteValue()
  395. {
  396. return (byte) value;
  397. }
  398. /**
  399. * Return the value of this <code>Float</code> as a <code>short</code>.
  400. *
  401. * @return the short value
  402. * @since 1.1
  403. */
  404. public short shortValue()
  405. {
  406. return (short) value;
  407. }
  408. /**
  409. * Return the value of this <code>Integer</code> as an <code>int</code>.
  410. *
  411. * @return the int value
  412. */
  413. public int intValue()
  414. {
  415. return (int) value;
  416. }
  417. /**
  418. * Return the value of this <code>Integer</code> as a <code>long</code>.
  419. *
  420. * @return the long value
  421. */
  422. public long longValue()
  423. {
  424. return (long) value;
  425. }
  426. /**
  427. * Return the value of this <code>Float</code>.
  428. *
  429. * @return the float value
  430. */
  431. public float floatValue()
  432. {
  433. return value;
  434. }
  435. /**
  436. * Return the value of this <code>Float</code> as a <code>double</code>
  437. *
  438. * @return the double value
  439. */
  440. public double doubleValue()
  441. {
  442. return value;
  443. }
  444. /**
  445. * Return a hashcode representing this Object. <code>Float</code>'s hash
  446. * code is calculated by calling <code>floatToIntBits(floatValue())</code>.
  447. *
  448. * @return this Object's hash code
  449. * @see #floatToIntBits(float)
  450. */
  451. public int hashCode()
  452. {
  453. return floatToIntBits(value);
  454. }
  455. /**
  456. * Returns <code>true</code> if <code>obj</code> is an instance of
  457. * <code>Float</code> and represents the same float value. Unlike comparing
  458. * two floats with <code>==</code>, this treats two instances of
  459. * <code>Float.NaN</code> as equal, but treats <code>0.0</code> and
  460. * <code>-0.0</code> as unequal.
  461. *
  462. * <p>Note that <code>f1.equals(f2)</code> is identical to
  463. * <code>floatToIntBits(f1.floatValue()) ==
  464. * floatToIntBits(f2.floatValue())</code>.
  465. *
  466. * @param obj the object to compare
  467. * @return whether the objects are semantically equal
  468. */
  469. public boolean equals(Object obj)
  470. {
  471. if (obj instanceof Float)
  472. {
  473. float f = ((Float) obj).value;
  474. return (floatToRawIntBits(value) == floatToRawIntBits(f)) ||
  475. (isNaN(value) && isNaN(f));
  476. }
  477. return false;
  478. }
  479. /**
  480. * Convert the float to the IEEE 754 floating-point "single format" bit
  481. * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
  482. * (masked by 0x7f800000) represent the exponent, and bits 22-0
  483. * (masked by 0x007fffff) are the mantissa. This function collapses all
  484. * versions of NaN to 0x7fc00000. The result of this function can be used
  485. * as the argument to <code>Float.intBitsToFloat(int)</code> to obtain the
  486. * original <code>float</code> value.
  487. *
  488. * @param value the <code>float</code> to convert
  489. * @return the bits of the <code>float</code>
  490. * @see #intBitsToFloat(int)
  491. */
  492. public static int floatToIntBits(float value)
  493. {
  494. if (isNaN(value))
  495. return 0x7fc00000;
  496. else
  497. return VMFloat.floatToRawIntBits(value);
  498. }
  499. /**
  500. * Convert the float to the IEEE 754 floating-point "single format" bit
  501. * layout. Bit 31 (the most significant) is the sign bit, bits 30-23
  502. * (masked by 0x7f800000) represent the exponent, and bits 22-0
  503. * (masked by 0x007fffff) are the mantissa. This function leaves NaN alone,
  504. * rather than collapsing to a canonical value. The result of this function
  505. * can be used as the argument to <code>Float.intBitsToFloat(int)</code> to
  506. * obtain the original <code>float</code> value.
  507. *
  508. * @param value the <code>float</code> to convert
  509. * @return the bits of the <code>float</code>
  510. * @see #intBitsToFloat(int)
  511. */
  512. public static int floatToRawIntBits(float value)
  513. {
  514. return VMFloat.floatToRawIntBits(value);
  515. }
  516. /**
  517. * Convert the argument in IEEE 754 floating-point "single format" bit
  518. * layout to the corresponding float. Bit 31 (the most significant) is the
  519. * sign bit, bits 30-23 (masked by 0x7f800000) represent the exponent, and
  520. * bits 22-0 (masked by 0x007fffff) are the mantissa. This function leaves
  521. * NaN alone, so that you can recover the bit pattern with
  522. * <code>Float.floatToRawIntBits(float)</code>.
  523. *
  524. * @param bits the bits to convert
  525. * @return the <code>float</code> represented by the bits
  526. * @see #floatToIntBits(float)
  527. * @see #floatToRawIntBits(float)
  528. */
  529. public static float intBitsToFloat(int bits)
  530. {
  531. return VMFloat.intBitsToFloat(bits);
  532. }
  533. /**
  534. * Compare two Floats numerically by comparing their <code>float</code>
  535. * values. The result is positive if the first is greater, negative if the
  536. * second is greater, and 0 if the two are equal. However, this special
  537. * cases NaN and signed zero as follows: NaN is considered greater than
  538. * all other floats, including <code>POSITIVE_INFINITY</code>, and positive
  539. * zero is considered greater than negative zero.
  540. *
  541. * @param f the Float to compare
  542. * @return the comparison
  543. * @since 1.2
  544. */
  545. public int compareTo(Float f)
  546. {
  547. return compare(value, f.value);
  548. }
  549. /**
  550. * Behaves like <code>new Float(x).compareTo(new Float(y))</code>; in
  551. * other words this compares two floats, special casing NaN and zero,
  552. * without the overhead of objects.
  553. *
  554. * @param x the first float to compare
  555. * @param y the second float to compare
  556. * @return the comparison
  557. * @since 1.4
  558. */
  559. public static int compare(float x, float y)
  560. {
  561. // handle the easy cases:
  562. if (x < y)
  563. return -1;
  564. if (x > y)
  565. return 1;
  566. // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
  567. int ix = floatToRawIntBits(x);
  568. int iy = floatToRawIntBits(y);
  569. if (ix == iy)
  570. return 0;
  571. // handle NaNs:
  572. if (x != x)
  573. return (y != y) ? 0 : 1;
  574. else if (y != y)
  575. return -1;
  576. // handle +/- 0.0
  577. return (ix < iy) ? -1 : 1;
  578. }
  579. }