1 /* 2 * Copyright (c) 1994, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang; 27 28 import java.lang.invoke.MethodHandles; 29 import java.lang.constant.Constable; 30 import java.lang.constant.ConstantDesc; 31 import java.util.Optional; 32 33 import jdk.internal.math.FloatConsts; 34 import jdk.internal.math.FloatingDecimal; 35 import jdk.internal.math.FloatToDecimal; 36 import jdk.internal.vm.annotation.IntrinsicCandidate; 37 38 /** 39 * The {@code Float} class wraps a value of primitive type 40 * {@code float} in an object. An object of type 41 * {@code Float} contains a single field whose type is 42 * {@code float}. 43 * 44 * <p>In addition, this class provides several methods for converting a 45 * {@code float} to a {@code String} and a 46 * {@code String} to a {@code float}, as well as other 47 * constants and methods useful when dealing with a 48 * {@code float}. 49 * 50 * <!-- Android-removed: paragraph on ValueBased 51 * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> 52 * class; programmers should treat instances that are 53 * {@linkplain #equals(Object) equal} as interchangeable and should not 54 * use instances for synchronization, or unpredictable behavior may 55 * occur. For example, in a future release, synchronization may fail. 56 * --> 57 * 58 * <h2><a id=equivalenceRelation>Floating-point Equality, Equivalence, 59 * and Comparison</a></h2> 60 * 61 * The class {@code java.lang.Double} has a <a 62 * href="Double.html#equivalenceRelation">discussion of equality, 63 * equivalence, and comparison of floating-point values</a> that is 64 * equally applicable to {@code float} values. 65 * 66 * @see <a href="https://standards.ieee.org/ieee/754/6210/"> 67 * <cite>IEEE Standard for Floating-Point Arithmetic</cite></a> 68 * 69 * @author Lee Boynton 70 * @author Arthur van Hoff 71 * @author Joseph D. Darcy 72 * @since 1.0 73 */ 74 @jdk.internal.ValueBased 75 public final class Float extends Number 76 implements Comparable<Float>, Constable, ConstantDesc { 77 /** 78 * A constant holding the positive infinity of type 79 * {@code float}. It is equal to the value returned by 80 * {@code Float.intBitsToFloat(0x7f800000)}. 81 */ 82 public static final float POSITIVE_INFINITY = 1.0f / 0.0f; 83 84 /** 85 * A constant holding the negative infinity of type 86 * {@code float}. It is equal to the value returned by 87 * {@code Float.intBitsToFloat(0xff800000)}. 88 */ 89 public static final float NEGATIVE_INFINITY = -1.0f / 0.0f; 90 91 /** 92 * A constant holding a Not-a-Number (NaN) value of type 93 * {@code float}. It is equivalent to the value returned by 94 * {@code Float.intBitsToFloat(0x7fc00000)}. 95 */ 96 public static final float NaN = 0.0f / 0.0f; 97 98 /** 99 * A constant holding the largest positive finite value of type 100 * {@code float}, (2-2<sup>-23</sup>)·2<sup>127</sup>. 101 * It is equal to the hexadecimal floating-point literal 102 * {@code 0x1.fffffeP+127f} and also equal to 103 * {@code Float.intBitsToFloat(0x7f7fffff)}. 104 */ 105 public static final float MAX_VALUE = 0x1.fffffeP+127f; // 3.4028235e+38f 106 107 /** 108 * A constant holding the smallest positive normal value of type 109 * {@code float}, 2<sup>-126</sup>. It is equal to the 110 * hexadecimal floating-point literal {@code 0x1.0p-126f} and also 111 * equal to {@code Float.intBitsToFloat(0x00800000)}. 112 * 113 * @since 1.6 114 */ 115 public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f 116 117 /** 118 * A constant holding the smallest positive nonzero value of type 119 * {@code float}, 2<sup>-149</sup>. It is equal to the 120 * hexadecimal floating-point literal {@code 0x0.000002P-126f} 121 * and also equal to {@code Float.intBitsToFloat(0x1)}. 122 */ 123 public static final float MIN_VALUE = 0x0.000002P-126f; // 1.4e-45f 124 125 /** 126 * The number of bits used to represent a {@code float} value. 127 * 128 * @since 1.5 129 */ 130 public static final int SIZE = 32; 131 132 /** 133 * The number of bits in the significand of a {@code float} value. 134 * This is the parameter N in section {@jls 4.2.3} of 135 * <cite>The Java Language Specification</cite>. 136 * 137 * @since 19 138 */ 139 public static final int PRECISION = 24; 140 141 /** 142 * Maximum exponent a finite {@code float} variable may have. It 143 * is equal to the value returned by {@code 144 * Math.getExponent(Float.MAX_VALUE)}. 145 * 146 * @since 1.6 147 */ 148 public static final int MAX_EXPONENT = (1 << (SIZE - PRECISION - 1)) - 1; // 127 149 150 /** 151 * Minimum exponent a normalized {@code float} variable may have. 152 * It is equal to the value returned by {@code 153 * Math.getExponent(Float.MIN_NORMAL)}. 154 * 155 * @since 1.6 156 */ 157 public static final int MIN_EXPONENT = 1 - MAX_EXPONENT; // -126 158 159 /** 160 * The number of bytes used to represent a {@code float} value. 161 * 162 * @since 1.8 163 */ 164 public static final int BYTES = SIZE / Byte.SIZE; 165 166 /** 167 * The {@code Class} instance representing the primitive type 168 * {@code float}. 169 * 170 * @since 1.1 171 */ 172 @SuppressWarnings("unchecked") 173 public static final Class<Float> TYPE = (Class<Float>) Class.getPrimitiveClass("float"); 174 175 /** 176 * Returns a string representation of the {@code float} 177 * argument. All characters mentioned below are ASCII characters. 178 * <ul> 179 * <li>If the argument is NaN, the result is the string 180 * "{@code NaN}". 181 * <li>Otherwise, the result is a string that represents the sign and 182 * magnitude (absolute value) of the argument. If the sign is 183 * negative, the first character of the result is 184 * '{@code -}' ({@code '\u005Cu002D'}); if the sign is 185 * positive, no sign character appears in the result. As for 186 * the magnitude <i>m</i>: 187 * <ul> 188 * <li>If <i>m</i> is infinity, it is represented by the characters 189 * {@code "Infinity"}; thus, positive infinity produces 190 * the result {@code "Infinity"} and negative infinity 191 * produces the result {@code "-Infinity"}. 192 * <li>If <i>m</i> is zero, it is represented by the characters 193 * {@code "0.0"}; thus, negative zero produces the result 194 * {@code "-0.0"} and positive zero produces the result 195 * {@code "0.0"}. 196 * 197 * <li> Otherwise <i>m</i> is positive and finite. 198 * It is converted to a string in two stages: 199 * <ul> 200 * <li> <em>Selection of a decimal</em>: 201 * A well-defined decimal <i>d</i><sub><i>m</i></sub> 202 * is selected to represent <i>m</i>. 203 * This decimal is (almost always) the <em>shortest</em> one that 204 * rounds to <i>m</i> according to the round to nearest 205 * rounding policy of IEEE 754 floating-point arithmetic. 206 * <li> <em>Formatting as a string</em>: 207 * The decimal <i>d</i><sub><i>m</i></sub> is formatted as a string, 208 * either in plain or in computerized scientific notation, 209 * depending on its value. 210 * </ul> 211 * </ul> 212 * </ul> 213 * 214 * <p>A <em>decimal</em> is a number of the form 215 * <i>s</i>×10<sup><i>i</i></sup> 216 * for some (unique) integers <i>s</i> > 0 and <i>i</i> such that 217 * <i>s</i> is not a multiple of 10. 218 * These integers are the <em>significand</em> and 219 * the <em>exponent</em>, respectively, of the decimal. 220 * The <em>length</em> of the decimal is the (unique) 221 * positive integer <i>n</i> meeting 222 * 10<sup><i>n</i>-1</sup> ≤ <i>s</i> < 10<sup><i>n</i></sup>. 223 * 224 * <p>The decimal <i>d</i><sub><i>m</i></sub> for a finite positive <i>m</i> 225 * is defined as follows: 226 * <ul> 227 * <li>Let <i>R</i> be the set of all decimals that round to <i>m</i> 228 * according to the usual <em>round to nearest</em> rounding policy of 229 * IEEE 754 floating-point arithmetic. 230 * <li>Let <i>p</i> be the minimal length over all decimals in <i>R</i>. 231 * <li>When <i>p</i> ≥ 2, let <i>T</i> be the set of all decimals 232 * in <i>R</i> with length <i>p</i>. 233 * Otherwise, let <i>T</i> be the set of all decimals 234 * in <i>R</i> with length 1 or 2. 235 * <li>Define <i>d</i><sub><i>m</i></sub> as the decimal in <i>T</i> 236 * that is closest to <i>m</i>. 237 * Or if there are two such decimals in <i>T</i>, 238 * select the one with the even significand. 239 * </ul> 240 * 241 * <p>The (uniquely) selected decimal <i>d</i><sub><i>m</i></sub> 242 * is then formatted. 243 * Let <i>s</i>, <i>i</i> and <i>n</i> be the significand, exponent and 244 * length of <i>d</i><sub><i>m</i></sub>, respectively. 245 * Further, let <i>e</i> = <i>n</i> + <i>i</i> - 1 and let 246 * <i>s</i><sub>1</sub>…<i>s</i><sub><i>n</i></sub> 247 * be the usual decimal expansion of <i>s</i>. 248 * Note that <i>s</i><sub>1</sub> ≠ 0 249 * and <i>s</i><sub><i>n</i></sub> ≠ 0. 250 * Below, the decimal point {@code '.'} is {@code '\u005Cu002E'} 251 * and the exponent indicator {@code 'E'} is {@code '\u005Cu0045'}. 252 * <ul> 253 * <li>Case -3 ≤ <i>e</i> < 0: 254 * <i>d</i><sub><i>m</i></sub> is formatted as 255 * <code>0.0</code>…<code>0</code><!-- 256 * --><i>s</i><sub>1</sub>…<i>s</i><sub><i>n</i></sub>, 257 * where there are exactly -(<i>n</i> + <i>i</i>) zeroes between 258 * the decimal point and <i>s</i><sub>1</sub>. 259 * For example, 123 × 10<sup>-4</sup> is formatted as 260 * {@code 0.0123}. 261 * <li>Case 0 ≤ <i>e</i> < 7: 262 * <ul> 263 * <li>Subcase <i>i</i> ≥ 0: 264 * <i>d</i><sub><i>m</i></sub> is formatted as 265 * <i>s</i><sub>1</sub>…<i>s</i><sub><i>n</i></sub><!-- 266 * --><code>0</code>…<code>0.0</code>, 267 * where there are exactly <i>i</i> zeroes 268 * between <i>s</i><sub><i>n</i></sub> and the decimal point. 269 * For example, 123 × 10<sup>2</sup> is formatted as 270 * {@code 12300.0}. 271 * <li>Subcase <i>i</i> < 0: 272 * <i>d</i><sub><i>m</i></sub> is formatted as 273 * <i>s</i><sub>1</sub>…<!-- 274 * --><i>s</i><sub><i>n</i>+<i>i</i></sub><code>.</code><!-- 275 * --><i>s</i><sub><i>n</i>+<i>i</i>+1</sub>…<!-- 276 * --><i>s</i><sub><i>n</i></sub>, 277 * where there are exactly -<i>i</i> digits to the right of 278 * the decimal point. 279 * For example, 123 × 10<sup>-1</sup> is formatted as 280 * {@code 12.3}. 281 * </ul> 282 * <li>Case <i>e</i> < -3 or <i>e</i> ≥ 7: 283 * computerized scientific notation is used to format 284 * <i>d</i><sub><i>m</i></sub>. 285 * Here <i>e</i> is formatted as by {@link Integer#toString(int)}. 286 * <ul> 287 * <li>Subcase <i>n</i> = 1: 288 * <i>d</i><sub><i>m</i></sub> is formatted as 289 * <i>s</i><sub>1</sub><code>.0E</code><i>e</i>. 290 * For example, 1 × 10<sup>23</sup> is formatted as 291 * {@code 1.0E23}. 292 * <li>Subcase <i>n</i> > 1: 293 * <i>d</i><sub><i>m</i></sub> is formatted as 294 * <i>s</i><sub>1</sub><code>.</code><i>s</i><sub>2</sub><!-- 295 * -->…<i>s</i><sub><i>n</i></sub><code>E</code><i>e</i>. 296 * For example, 123 × 10<sup>-21</sup> is formatted as 297 * {@code 1.23E-19}. 298 * </ul> 299 * </ul> 300 * 301 * <p>To create localized string representations of a floating-point 302 * value, use subclasses of {@link java.text.NumberFormat}. 303 * 304 * @param f the {@code float} to be converted. 305 * @return a string representation of the argument. 306 */ toString(float f)307 public static String toString(float f) { 308 return FloatToDecimal.toString(f); 309 } 310 311 /** 312 * Returns a hexadecimal string representation of the 313 * {@code float} argument. All characters mentioned below are 314 * ASCII characters. 315 * 316 * <ul> 317 * <li>If the argument is NaN, the result is the string 318 * "{@code NaN}". 319 * <li>Otherwise, the result is a string that represents the sign and 320 * magnitude (absolute value) of the argument. If the sign is negative, 321 * the first character of the result is '{@code -}' 322 * ({@code '\u005Cu002D'}); if the sign is positive, no sign character 323 * appears in the result. As for the magnitude <i>m</i>: 324 * 325 * <ul> 326 * <li>If <i>m</i> is infinity, it is represented by the string 327 * {@code "Infinity"}; thus, positive infinity produces the 328 * result {@code "Infinity"} and negative infinity produces 329 * the result {@code "-Infinity"}. 330 * 331 * <li>If <i>m</i> is zero, it is represented by the string 332 * {@code "0x0.0p0"}; thus, negative zero produces the result 333 * {@code "-0x0.0p0"} and positive zero produces the result 334 * {@code "0x0.0p0"}. 335 * 336 * <li>If <i>m</i> is a {@code float} value with a 337 * normalized representation, substrings are used to represent the 338 * significand and exponent fields. The significand is 339 * represented by the characters {@code "0x1."} 340 * followed by a lowercase hexadecimal representation of the rest 341 * of the significand as a fraction. Trailing zeros in the 342 * hexadecimal representation are removed unless all the digits 343 * are zero, in which case a single zero is used. Next, the 344 * exponent is represented by {@code "p"} followed 345 * by a decimal string of the unbiased exponent as if produced by 346 * a call to {@link Integer#toString(int) Integer.toString} on the 347 * exponent value. 348 * 349 * <li>If <i>m</i> is a {@code float} value with a subnormal 350 * representation, the significand is represented by the 351 * characters {@code "0x0."} followed by a 352 * hexadecimal representation of the rest of the significand as a 353 * fraction. Trailing zeros in the hexadecimal representation are 354 * removed. Next, the exponent is represented by 355 * {@code "p-126"}. Note that there must be at 356 * least one nonzero digit in a subnormal significand. 357 * 358 * </ul> 359 * 360 * </ul> 361 * 362 * <table class="striped"> 363 * <caption>Examples</caption> 364 * <thead> 365 * <tr><th scope="col">Floating-point Value</th><th scope="col">Hexadecimal String</th> 366 * </thead> 367 * <tbody> 368 * <tr><th scope="row">{@code 1.0}</th> <td>{@code 0x1.0p0}</td> 369 * <tr><th scope="row">{@code -1.0}</th> <td>{@code -0x1.0p0}</td> 370 * <tr><th scope="row">{@code 2.0}</th> <td>{@code 0x1.0p1}</td> 371 * <tr><th scope="row">{@code 3.0}</th> <td>{@code 0x1.8p1}</td> 372 * <tr><th scope="row">{@code 0.5}</th> <td>{@code 0x1.0p-1}</td> 373 * <tr><th scope="row">{@code 0.25}</th> <td>{@code 0x1.0p-2}</td> 374 * <tr><th scope="row">{@code Float.MAX_VALUE}</th> 375 * <td>{@code 0x1.fffffep127}</td> 376 * <tr><th scope="row">{@code Minimum Normal Value}</th> 377 * <td>{@code 0x1.0p-126}</td> 378 * <tr><th scope="row">{@code Maximum Subnormal Value}</th> 379 * <td>{@code 0x0.fffffep-126}</td> 380 * <tr><th scope="row">{@code Float.MIN_VALUE}</th> 381 * <td>{@code 0x0.000002p-126}</td> 382 * </tbody> 383 * </table> 384 * @param f the {@code float} to be converted. 385 * @return a hex string representation of the argument. 386 * @since 1.5 387 * @author Joseph D. Darcy 388 */ toHexString(float f)389 public static String toHexString(float f) { 390 if (Math.abs(f) < Float.MIN_NORMAL 391 && f != 0.0f ) {// float subnormal 392 // Adjust exponent to create subnormal double, then 393 // replace subnormal double exponent with subnormal float 394 // exponent 395 String s = Double.toHexString(Math.scalb((double)f, 396 /* -1022+126 */ 397 Double.MIN_EXPONENT- 398 Float.MIN_EXPONENT)); 399 return s.replaceFirst("p-1022$", "p-126"); 400 } 401 else // double string will be the same as float string 402 return Double.toHexString(f); 403 } 404 405 /** 406 * Returns a {@code Float} object holding the 407 * {@code float} value represented by the argument string 408 * {@code s}. 409 * 410 * <p>If {@code s} is {@code null}, then a 411 * {@code NullPointerException} is thrown. 412 * 413 * <p>Leading and trailing whitespace characters in {@code s} 414 * are ignored. Whitespace is removed as if by the {@link 415 * String#trim} method; that is, both ASCII space and control 416 * characters are removed. The rest of {@code s} should 417 * constitute a <i>FloatValue</i> as described by the lexical 418 * syntax rules: 419 * 420 * <blockquote> 421 * <dl> 422 * <dt><i>FloatValue:</i> 423 * <dd><i>Sign<sub>opt</sub></i> {@code NaN} 424 * <dd><i>Sign<sub>opt</sub></i> {@code Infinity} 425 * <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i> 426 * <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i> 427 * <dd><i>SignedInteger</i> 428 * </dl> 429 * 430 * <dl> 431 * <dt><i>HexFloatingPointLiteral</i>: 432 * <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i> 433 * </dl> 434 * 435 * <dl> 436 * <dt><i>HexSignificand:</i> 437 * <dd><i>HexNumeral</i> 438 * <dd><i>HexNumeral</i> {@code .} 439 * <dd>{@code 0x} <i>HexDigits<sub>opt</sub> 440 * </i>{@code .}<i> HexDigits</i> 441 * <dd>{@code 0X}<i> HexDigits<sub>opt</sub> 442 * </i>{@code .} <i>HexDigits</i> 443 * </dl> 444 * 445 * <dl> 446 * <dt><i>BinaryExponent:</i> 447 * <dd><i>BinaryExponentIndicator SignedInteger</i> 448 * </dl> 449 * 450 * <dl> 451 * <dt><i>BinaryExponentIndicator:</i> 452 * <dd>{@code p} 453 * <dd>{@code P} 454 * </dl> 455 * 456 * </blockquote> 457 * 458 * where <i>Sign</i>, <i>FloatingPointLiteral</i>, 459 * <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and 460 * <i>FloatTypeSuffix</i> are as defined in the lexical structure 461 * sections of 462 * <cite>The Java Language Specification</cite>, 463 * except that underscores are not accepted between digits. 464 * If {@code s} does not have the form of 465 * a <i>FloatValue</i>, then a {@code NumberFormatException} 466 * is thrown. Otherwise, {@code s} is regarded as 467 * representing an exact decimal value in the usual 468 * "computerized scientific notation" or as an exact 469 * hexadecimal value; this exact numerical value is then 470 * conceptually converted to an "infinitely precise" 471 * binary value that is then rounded to type {@code float} 472 * by the usual round-to-nearest rule of IEEE 754 floating-point 473 * arithmetic, which includes preserving the sign of a zero 474 * value. 475 * 476 * Note that the round-to-nearest rule also implies overflow and 477 * underflow behaviour; if the exact value of {@code s} is large 478 * enough in magnitude (greater than or equal to ({@link 479 * #MAX_VALUE} + {@link Math#ulp(float) ulp(MAX_VALUE)}/2), 480 * rounding to {@code float} will result in an infinity and if the 481 * exact value of {@code s} is small enough in magnitude (less 482 * than or equal to {@link #MIN_VALUE}/2), rounding to float will 483 * result in a zero. 484 * 485 * Finally, after rounding a {@code Float} object representing 486 * this {@code float} value is returned. 487 * 488 * <p>To interpret localized string representations of a 489 * floating-point value, use subclasses of {@link 490 * java.text.NumberFormat}. 491 * 492 * <p>Note that trailing format specifiers, specifiers that 493 * determine the type of a floating-point literal 494 * ({@code 1.0f} is a {@code float} value; 495 * {@code 1.0d} is a {@code double} value), do 496 * <em>not</em> influence the results of this method. In other 497 * words, the numerical value of the input string is converted 498 * directly to the target floating-point type. In general, the 499 * two-step sequence of conversions, string to {@code double} 500 * followed by {@code double} to {@code float}, is 501 * <em>not</em> equivalent to converting a string directly to 502 * {@code float}. For example, if first converted to an 503 * intermediate {@code double} and then to 504 * {@code float}, the string<br> 505 * {@code "1.00000017881393421514957253748434595763683319091796875001d"}<br> 506 * results in the {@code float} value 507 * {@code 1.0000002f}; if the string is converted directly to 508 * {@code float}, <code>1.000000<b>1</b>f</code> results. 509 * 510 * <p>To avoid calling this method on an invalid string and having 511 * a {@code NumberFormatException} be thrown, the documentation 512 * for {@link Double#valueOf Double.valueOf} lists a regular 513 * expression which can be used to screen the input. 514 * 515 * @param s the string to be parsed. 516 * @return a {@code Float} object holding the value 517 * represented by the {@code String} argument. 518 * @throws NumberFormatException if the string does not contain a 519 * parsable number. 520 */ valueOf(String s)521 public static Float valueOf(String s) throws NumberFormatException { 522 return new Float(parseFloat(s)); 523 } 524 525 /** 526 * Returns a {@code Float} instance representing the specified 527 * {@code float} value. 528 * If a new {@code Float} instance is not required, this method 529 * should generally be used in preference to the constructor 530 * {@link #Float(float)}, as this method is likely to yield 531 * significantly better space and time performance by caching 532 * frequently requested values. 533 * 534 * @param f a float value. 535 * @return a {@code Float} instance representing {@code f}. 536 * @since 1.5 537 */ 538 @IntrinsicCandidate valueOf(float f)539 public static Float valueOf(float f) { 540 return new Float(f); 541 } 542 543 /** 544 * Returns a new {@code float} initialized to the value 545 * represented by the specified {@code String}, as performed 546 * by the {@code valueOf} method of class {@code Float}. 547 * 548 * @param s the string to be parsed. 549 * @return the {@code float} value represented by the string 550 * argument. 551 * @throws NullPointerException if the string is null 552 * @throws NumberFormatException if the string does not contain a 553 * parsable {@code float}. 554 * @see java.lang.Float#valueOf(String) 555 * @since 1.2 556 */ parseFloat(String s)557 public static float parseFloat(String s) throws NumberFormatException { 558 return FloatingDecimal.parseFloat(s); 559 } 560 561 /** 562 * Returns {@code true} if the specified number is a 563 * Not-a-Number (NaN) value, {@code false} otherwise. 564 * 565 * @apiNote 566 * This method corresponds to the isNaN operation defined in IEEE 567 * 754. 568 * 569 * @param v the value to be tested. 570 * @return {@code true} if the argument is NaN; 571 * {@code false} otherwise. 572 */ isNaN(float v)573 public static boolean isNaN(float v) { 574 return (v != v); 575 } 576 577 /** 578 * Returns {@code true} if the specified number is infinitely 579 * large in magnitude, {@code false} otherwise. 580 * 581 * @apiNote 582 * This method corresponds to the isInfinite operation defined in 583 * IEEE 754. 584 * 585 * @param v the value to be tested. 586 * @return {@code true} if the argument is positive infinity or 587 * negative infinity; {@code false} otherwise. 588 */ 589 @IntrinsicCandidate isInfinite(float v)590 public static boolean isInfinite(float v) { 591 return Math.abs(v) > MAX_VALUE; 592 } 593 594 595 /** 596 * Returns {@code true} if the argument is a finite floating-point 597 * value; returns {@code false} otherwise (for NaN and infinity 598 * arguments). 599 * 600 * @apiNote 601 * This method corresponds to the isFinite operation defined in 602 * IEEE 754. 603 * 604 * @param f the {@code float} value to be tested 605 * @return {@code true} if the argument is a finite 606 * floating-point value, {@code false} otherwise. 607 * @since 1.8 608 */ 609 @IntrinsicCandidate isFinite(float f)610 public static boolean isFinite(float f) { 611 return Math.abs(f) <= Float.MAX_VALUE; 612 } 613 614 /** 615 * The value of the Float. 616 * 617 * @serial 618 */ 619 private final float value; 620 621 /** 622 * Constructs a newly allocated {@code Float} object that 623 * represents the primitive {@code float} argument. 624 * 625 * @param value the value to be represented by the {@code Float}. 626 * 627 * @deprecated 628 * It is rarely appropriate to use this constructor. The static factory 629 * {@link #valueOf(float)} is generally a better choice, as it is 630 * likely to yield significantly better space and time performance. 631 */ 632 // Android-changed: not yet forRemoval on Android. 633 @Deprecated(since="9"/*, forRemoval = true*/) Float(float value)634 public Float(float value) { 635 this.value = value; 636 } 637 638 /** 639 * Constructs a newly allocated {@code Float} object that 640 * represents the argument converted to type {@code float}. 641 * 642 * @param value the value to be represented by the {@code Float}. 643 * 644 * @deprecated 645 * It is rarely appropriate to use this constructor. Instead, use the 646 * static factory method {@link #valueOf(float)} method as follows: 647 * {@code Float.valueOf((float)value)}. 648 */ 649 // Android-changed: not yet forRemoval on Android. 650 @Deprecated(since="9"/*, forRemoval = true*/) Float(double value)651 public Float(double value) { 652 this.value = (float)value; 653 } 654 655 /** 656 * Constructs a newly allocated {@code Float} object that 657 * represents the floating-point value of type {@code float} 658 * represented by the string. The string is converted to a 659 * {@code float} value as if by the {@code valueOf} method. 660 * 661 * @param s a string to be converted to a {@code Float}. 662 * @throws NumberFormatException if the string does not contain a 663 * parsable number. 664 * 665 * @deprecated 666 * It is rarely appropriate to use this constructor. 667 * Use {@link #parseFloat(String)} to convert a string to a 668 * {@code float} primitive, or use {@link #valueOf(String)} 669 * to convert a string to a {@code Float} object. 670 */ 671 // Android-changed: not yet forRemoval on Android. 672 @Deprecated(since="9"/*, forRemoval = true*/) Float(String s)673 public Float(String s) throws NumberFormatException { 674 value = parseFloat(s); 675 } 676 677 /** 678 * Returns {@code true} if this {@code Float} value is a 679 * Not-a-Number (NaN), {@code false} otherwise. 680 * 681 * @return {@code true} if the value represented by this object is 682 * NaN; {@code false} otherwise. 683 */ isNaN()684 public boolean isNaN() { 685 return isNaN(value); 686 } 687 688 /** 689 * Returns {@code true} if this {@code Float} value is 690 * infinitely large in magnitude, {@code false} otherwise. 691 * 692 * @return {@code true} if the value represented by this object is 693 * positive infinity or negative infinity; 694 * {@code false} otherwise. 695 */ isInfinite()696 public boolean isInfinite() { 697 return isInfinite(value); 698 } 699 700 /** 701 * Returns a string representation of this {@code Float} object. 702 * The primitive {@code float} value represented by this object 703 * is converted to a {@code String} exactly as if by the method 704 * {@code toString} of one argument. 705 * 706 * @return a {@code String} representation of this object. 707 * @see java.lang.Float#toString(float) 708 */ toString()709 public String toString() { 710 return Float.toString(value); 711 } 712 713 /** 714 * Returns the value of this {@code Float} as a {@code byte} after 715 * a narrowing primitive conversion. 716 * 717 * @return the {@code float} value represented by this object 718 * converted to type {@code byte} 719 * @jls 5.1.3 Narrowing Primitive Conversion 720 */ byteValue()721 public byte byteValue() { 722 return (byte)value; 723 } 724 725 /** 726 * Returns the value of this {@code Float} as a {@code short} 727 * after a narrowing primitive conversion. 728 * 729 * @return the {@code float} value represented by this object 730 * converted to type {@code short} 731 * @jls 5.1.3 Narrowing Primitive Conversion 732 * @since 1.1 733 */ shortValue()734 public short shortValue() { 735 return (short)value; 736 } 737 738 /** 739 * Returns the value of this {@code Float} as an {@code int} after 740 * a narrowing primitive conversion. 741 * 742 * @return the {@code float} value represented by this object 743 * converted to type {@code int} 744 * @jls 5.1.3 Narrowing Primitive Conversion 745 */ intValue()746 public int intValue() { 747 return (int)value; 748 } 749 750 /** 751 * Returns value of this {@code Float} as a {@code long} after a 752 * narrowing primitive conversion. 753 * 754 * @return the {@code float} value represented by this object 755 * converted to type {@code long} 756 * @jls 5.1.3 Narrowing Primitive Conversion 757 */ longValue()758 public long longValue() { 759 return (long)value; 760 } 761 762 /** 763 * Returns the {@code float} value of this {@code Float} object. 764 * 765 * @return the {@code float} value represented by this object 766 */ 767 @IntrinsicCandidate floatValue()768 public float floatValue() { 769 return value; 770 } 771 772 /** 773 * Returns the value of this {@code Float} as a {@code double} 774 * after a widening primitive conversion. 775 * 776 * @apiNote 777 * This method corresponds to the convertFormat operation defined 778 * in IEEE 754. 779 * 780 * @return the {@code float} value represented by this 781 * object converted to type {@code double} 782 * @jls 5.1.2 Widening Primitive Conversion 783 */ doubleValue()784 public double doubleValue() { 785 return (double)value; 786 } 787 788 /** 789 * Returns a hash code for this {@code Float} object. The 790 * result is the integer bit representation, exactly as produced 791 * by the method {@link #floatToIntBits(float)}, of the primitive 792 * {@code float} value represented by this {@code Float} 793 * object. 794 * 795 * @return a hash code value for this object. 796 */ 797 @Override hashCode()798 public int hashCode() { 799 return Float.hashCode(value); 800 } 801 802 /** 803 * Returns a hash code for a {@code float} value; compatible with 804 * {@code Float.hashCode()}. 805 * 806 * @param value the value to hash 807 * @return a hash code value for a {@code float} value. 808 * @since 1.8 809 */ hashCode(float value)810 public static int hashCode(float value) { 811 return floatToIntBits(value); 812 } 813 814 /** 815 * Compares this object against the specified object. The result 816 * is {@code true} if and only if the argument is not 817 * {@code null} and is a {@code Float} object that 818 * represents a {@code float} with the same value as the 819 * {@code float} represented by this object. For this 820 * purpose, two {@code float} values are considered to be the 821 * same if and only if the method {@link #floatToIntBits(float)} 822 * returns the identical {@code int} value when applied to 823 * each. 824 * 825 * @apiNote 826 * This method is defined in terms of {@link 827 * #floatToIntBits(float)} rather than the {@code ==} operator on 828 * {@code float} values since the {@code ==} operator does 829 * <em>not</em> define an equivalence relation and to satisfy the 830 * {@linkplain Object#equals equals contract} an equivalence 831 * relation must be implemented; see <a 832 * href="Double.html#equivalenceRelation">this discussion</a> for 833 * details of floating-point equality and equivalence. 834 * 835 * @param obj the object to be compared 836 * @return {@code true} if the objects are the same; 837 * {@code false} otherwise. 838 * @see java.lang.Float#floatToIntBits(float) 839 * @jls 15.21.1 Numerical Equality Operators == and != 840 */ equals(Object obj)841 public boolean equals(Object obj) { 842 return (obj instanceof Float) 843 && (floatToIntBits(((Float)obj).value) == floatToIntBits(value)); 844 } 845 846 /** 847 * Returns a representation of the specified floating-point value 848 * according to the IEEE 754 floating-point "single format" bit 849 * layout. 850 * 851 * <p>Bit 31 (the bit that is selected by the mask 852 * {@code 0x80000000}) represents the sign of the floating-point 853 * number. 854 * Bits 30-23 (the bits that are selected by the mask 855 * {@code 0x7f800000}) represent the exponent. 856 * Bits 22-0 (the bits that are selected by the mask 857 * {@code 0x007fffff}) represent the significand (sometimes called 858 * the mantissa) of the floating-point number. 859 * 860 * <p>If the argument is positive infinity, the result is 861 * {@code 0x7f800000}. 862 * 863 * <p>If the argument is negative infinity, the result is 864 * {@code 0xff800000}. 865 * 866 * <p>If the argument is NaN, the result is {@code 0x7fc00000}. 867 * 868 * <p>In all cases, the result is an integer that, when given to the 869 * {@link #intBitsToFloat(int)} method, will produce a floating-point 870 * value the same as the argument to {@code floatToIntBits} 871 * (except all NaN values are collapsed to a single 872 * "canonical" NaN value). 873 * 874 * @param value a floating-point number. 875 * @return the bits that represent the floating-point number. 876 */ 877 @IntrinsicCandidate floatToIntBits(float value)878 public static int floatToIntBits(float value) { 879 if (!isNaN(value)) { 880 return floatToRawIntBits(value); 881 } 882 return 0x7fc00000; 883 } 884 885 /** 886 * Returns a representation of the specified floating-point value 887 * according to the IEEE 754 floating-point "single format" bit 888 * layout, preserving Not-a-Number (NaN) values. 889 * 890 * <p>Bit 31 (the bit that is selected by the mask 891 * {@code 0x80000000}) represents the sign of the floating-point 892 * number. 893 * Bits 30-23 (the bits that are selected by the mask 894 * {@code 0x7f800000}) represent the exponent. 895 * Bits 22-0 (the bits that are selected by the mask 896 * {@code 0x007fffff}) represent the significand (sometimes called 897 * the mantissa) of the floating-point number. 898 * 899 * <p>If the argument is positive infinity, the result is 900 * {@code 0x7f800000}. 901 * 902 * <p>If the argument is negative infinity, the result is 903 * {@code 0xff800000}. 904 * 905 * <p>If the argument is NaN, the result is the integer representing 906 * the actual NaN value. Unlike the {@code floatToIntBits} 907 * method, {@code floatToRawIntBits} does not collapse all the 908 * bit patterns encoding a NaN to a single "canonical" 909 * NaN value. 910 * 911 * <p>In all cases, the result is an integer that, when given to the 912 * {@link #intBitsToFloat(int)} method, will produce a 913 * floating-point value the same as the argument to 914 * {@code floatToRawIntBits}. 915 * 916 * @param value a floating-point number. 917 * @return the bits that represent the floating-point number. 918 * @since 1.3 919 */ 920 @IntrinsicCandidate floatToRawIntBits(float value)921 public static native int floatToRawIntBits(float value); 922 923 /** 924 * Returns the {@code float} value corresponding to a given 925 * bit representation. 926 * The argument is considered to be a representation of a 927 * floating-point value according to the IEEE 754 floating-point 928 * "single format" bit layout. 929 * 930 * <p>If the argument is {@code 0x7f800000}, the result is positive 931 * infinity. 932 * 933 * <p>If the argument is {@code 0xff800000}, the result is negative 934 * infinity. 935 * 936 * <p>If the argument is any value in the range 937 * {@code 0x7f800001} through {@code 0x7fffffff} or in 938 * the range {@code 0xff800001} through 939 * {@code 0xffffffff}, the result is a NaN. No IEEE 754 940 * floating-point operation provided by Java can distinguish 941 * between two NaN values of the same type with different bit 942 * patterns. Distinct values of NaN are only distinguishable by 943 * use of the {@code Float.floatToRawIntBits} method. 944 * 945 * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three 946 * values that can be computed from the argument: 947 * 948 * {@snippet lang="java" : 949 * int s = ((bits >> 31) == 0) ? 1 : -1; 950 * int e = ((bits >> 23) & 0xff); 951 * int m = (e == 0) ? 952 * (bits & 0x7fffff) << 1 : 953 * (bits & 0x7fffff) | 0x800000; 954 * } 955 * 956 * Then the floating-point result equals the value of the mathematical 957 * expression <i>s</i>·<i>m</i>·2<sup><i>e</i>-150</sup>. 958 * 959 * <p>Note that this method may not be able to return a 960 * {@code float} NaN with exactly same bit pattern as the 961 * {@code int} argument. IEEE 754 distinguishes between two 962 * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>. The 963 * differences between the two kinds of NaN are generally not 964 * visible in Java. Arithmetic operations on signaling NaNs turn 965 * them into quiet NaNs with a different, but often similar, bit 966 * pattern. However, on some processors merely copying a 967 * signaling NaN also performs that conversion. In particular, 968 * copying a signaling NaN to return it to the calling method may 969 * perform this conversion. So {@code intBitsToFloat} may 970 * not be able to return a {@code float} with a signaling NaN 971 * bit pattern. Consequently, for some {@code int} values, 972 * {@code floatToRawIntBits(intBitsToFloat(start))} may 973 * <i>not</i> equal {@code start}. Moreover, which 974 * particular bit patterns represent signaling NaNs is platform 975 * dependent; although all NaN bit patterns, quiet or signaling, 976 * must be in the NaN range identified above. 977 * 978 * @param bits an integer. 979 * @return the {@code float} floating-point value with the same bit 980 * pattern. 981 */ 982 @IntrinsicCandidate intBitsToFloat(int bits)983 public static native float intBitsToFloat(int bits); 984 985 // Android-changed: marked as hide while a compiler plugin issue is not resolved. 986 /** 987 * {@return the {@code float} value closest to the numerical value 988 * of the argument, a floating-point binary16 value encoded in a 989 * {@code short}} The conversion is exact; all binary16 values can 990 * be exactly represented in {@code float}. 991 * 992 * Special cases: 993 * <ul> 994 * <li> If the argument is zero, the result is a zero with the 995 * same sign as the argument. 996 * <li> If the argument is infinite, the result is an infinity 997 * with the same sign as the argument. 998 * <li> If the argument is a NaN, the result is a NaN. 999 * </ul> 1000 * 1001 * <h4><a id=binary16Format>IEEE 754 binary16 format</a></h4> 1002 * The IEEE 754 standard defines binary16 as a 16-bit format, along 1003 * with the 32-bit binary32 format (corresponding to the {@code 1004 * float} type) and the 64-bit binary64 format (corresponding to 1005 * the {@code double} type). The binary16 format is similar to the 1006 * other IEEE 754 formats, except smaller, having all the usual 1007 * IEEE 754 values such as NaN, signed infinities, signed zeros, 1008 * and subnormals. The parameters (JLS {@jls 4.2.3}) for the 1009 * binary16 format are N = 11 precision bits, K = 5 exponent bits, 1010 * <i>E</i><sub><i>max</i></sub> = 15, and 1011 * <i>E</i><sub><i>min</i></sub> = -14. 1012 * 1013 * @apiNote 1014 * This method corresponds to the convertFormat operation defined 1015 * in IEEE 754 from the binary16 format to the binary32 format. 1016 * The operation of this method is analogous to a primitive 1017 * widening conversion (JLS {@jls 5.1.2}). 1018 * 1019 * @param floatBinary16 the binary16 value to convert to {@code float} 1020 * @since 20 1021 */ 1022 @IntrinsicCandidate float16ToFloat(short floatBinary16)1023 public static float float16ToFloat(short floatBinary16) { 1024 /* 1025 * The binary16 format has 1 sign bit, 5 exponent bits, and 10 1026 * significand bits. The exponent bias is 15. 1027 */ 1028 int bin16arg = (int)floatBinary16; 1029 int bin16SignBit = 0x8000 & bin16arg; 1030 int bin16ExpBits = 0x7c00 & bin16arg; 1031 int bin16SignifBits = 0x03FF & bin16arg; 1032 1033 // Shift left difference in the number of significand bits in 1034 // the float and binary16 formats 1035 final int SIGNIF_SHIFT = (FloatConsts.SIGNIFICAND_WIDTH - 11); 1036 1037 float sign = (bin16SignBit != 0) ? -1.0f : 1.0f; 1038 1039 // Extract binary16 exponent, remove its bias, add in the bias 1040 // of a float exponent and shift to correct bit location 1041 // (significand width includes the implicit bit so shift one 1042 // less). 1043 int bin16Exp = (bin16ExpBits >> 10) - 15; 1044 if (bin16Exp == -15) { 1045 // For subnormal binary16 values and 0, the numerical 1046 // value is 2^24 * the significand as an integer (no 1047 // implicit bit). 1048 return sign * (0x1p-24f * bin16SignifBits); 1049 } else if (bin16Exp == 16) { 1050 return (bin16SignifBits == 0) ? 1051 sign * Float.POSITIVE_INFINITY : 1052 Float.intBitsToFloat((bin16SignBit << 16) | 1053 0x7f80_0000 | 1054 // Preserve NaN signif bits 1055 ( bin16SignifBits << SIGNIF_SHIFT )); 1056 } 1057 1058 assert -15 < bin16Exp && bin16Exp < 16; 1059 1060 int floatExpBits = (bin16Exp + FloatConsts.EXP_BIAS) 1061 << (FloatConsts.SIGNIFICAND_WIDTH - 1); 1062 1063 // Compute and combine result sign, exponent, and significand bits. 1064 return Float.intBitsToFloat((bin16SignBit << 16) | 1065 floatExpBits | 1066 (bin16SignifBits << SIGNIF_SHIFT)); 1067 } 1068 1069 // Android-changed: marked as hide while a compiler plugin issue is not resolved. 1070 /** 1071 * {@return the floating-point binary16 value, encoded in a {@code 1072 * short}, closest in value to the argument} 1073 * The conversion is computed under the {@linkplain 1074 * java.math.RoundingMode#HALF_EVEN round to nearest even rounding 1075 * mode}. 1076 * 1077 * Special cases: 1078 * <ul> 1079 * <li> If the argument is zero, the result is a zero with the 1080 * same sign as the argument. 1081 * <li> If the argument is infinite, the result is an infinity 1082 * with the same sign as the argument. 1083 * <li> If the argument is a NaN, the result is a NaN. 1084 * </ul> 1085 * 1086 * The <a href="#binary16Format">binary16 format</a> is discussed in 1087 * more detail in the {@link #float16ToFloat} method. 1088 * 1089 * @apiNote 1090 * This method corresponds to the convertFormat operation defined 1091 * in IEEE 754 from the binary32 format to the binary16 format. 1092 * The operation of this method is analogous to a primitive 1093 * narrowing conversion (JLS {@jls 5.1.3}). 1094 * 1095 * @param f the {@code float} value to convert to binary16 1096 * @since 20 1097 */ 1098 @IntrinsicCandidate 1099 public static short floatToFloat16(float f) { 1100 int doppel = Float.floatToRawIntBits(f); 1101 short sign_bit = (short)((doppel & 0x8000_0000) >> 16); 1102 1103 if (Float.isNaN(f)) { 1104 // Preserve sign and attempt to preserve significand bits 1105 return (short)(sign_bit 1106 | 0x7c00 // max exponent + 1 1107 // Preserve high order bit of float NaN in the 1108 // binary16 result NaN (tenth bit); OR in remaining 1109 // bits into lower 9 bits of binary 16 significand. 1110 | (doppel & 0x007f_e000) >> 13 // 10 bits 1111 | (doppel & 0x0000_1ff0) >> 4 // 9 bits 1112 | (doppel & 0x0000_000f)); // 4 bits 1113 } 1114 1115 float abs_f = Math.abs(f); 1116 1117 // The overflow threshold is binary16 MAX_VALUE + 1/2 ulp 1118 if (abs_f >= (0x1.ffcp15f + 0x0.002p15f) ) { 1119 return (short)(sign_bit | 0x7c00); // Positive or negative infinity 1120 } 1121 1122 // Smallest magnitude nonzero representable binary16 value 1123 // is equal to 0x1.0p-24; half-way and smaller rounds to zero. 1124 if (abs_f <= 0x1.0p-24f * 0.5f) { // Covers float zeros and subnormals. 1125 return sign_bit; // Positive or negative zero 1126 } 1127 1128 // Dealing with finite values in exponent range of binary16 1129 // (when rounding is done, could still round up) 1130 int exp = Math.getExponent(f); 1131 assert -25 <= exp && exp <= 15; 1132 1133 // For binary16 subnormals, beside forcing exp to -15, retain 1134 // the difference expdelta = E_min - exp. This is the excess 1135 // shift value, in addition to 13, to be used in the 1136 // computations below. Further the (hidden) msb with value 1 1137 // in f must be involved as well. 1138 int expdelta = 0; 1139 int msb = 0x0000_0000; 1140 if (exp < -14) { 1141 expdelta = -14 - exp; 1142 exp = -15; 1143 msb = 0x0080_0000; 1144 } 1145 int f_signif_bits = doppel & 0x007f_ffff | msb; 1146 1147 // Significand bits as if using rounding to zero (truncation). 1148 short signif_bits = (short)(f_signif_bits >> (13 + expdelta)); 1149 1150 // For round to nearest even, determining whether or not to 1151 // round up (in magnitude) is a function of the least 1152 // significant bit (LSB), the next bit position (the round 1153 // position), and the sticky bit (whether there are any 1154 // nonzero bits in the exact result to the right of the round 1155 // digit). An increment occurs in three cases: 1156 // 1157 // LSB Round Sticky 1158 // 0 1 1 1159 // 1 1 0 1160 // 1 1 1 1161 // See "Computer Arithmetic Algorithms," Koren, Table 4.9 1162 1163 int lsb = f_signif_bits & (1 << 13 + expdelta); 1164 int round = f_signif_bits & (1 << 12 + expdelta); 1165 int sticky = f_signif_bits & ((1 << 12 + expdelta) - 1); 1166 1167 if (round != 0 && ((lsb | sticky) != 0 )) { 1168 signif_bits++; 1169 } 1170 1171 // No bits set in significand beyond the *first* exponent bit, 1172 // not just the significand; quantity is added to the exponent 1173 // to implement a carry out from rounding the significand. 1174 assert (0xf800 & signif_bits) == 0x0; 1175 1176 return (short)(sign_bit | ( ((exp + 15) << 10) + signif_bits ) ); 1177 } 1178 1179 /** 1180 * Compares two {@code Float} objects numerically. 1181 * 1182 * This method imposes a total order on {@code Float} objects 1183 * with two differences compared to the incomplete order defined by 1184 * the Java language numerical comparison operators ({@code <, <=, 1185 * ==, >=, >}) on {@code float} values. 1186 * 1187 * <ul><li> A NaN is <em>unordered</em> with respect to other 1188 * values and unequal to itself under the comparison 1189 * operators. This method chooses to define {@code 1190 * Float.NaN} to be equal to itself and greater than all 1191 * other {@code double} values (including {@code 1192 * Float.POSITIVE_INFINITY}). 1193 * 1194 * <li> Positive zero and negative zero compare equal 1195 * numerically, but are distinct and distinguishable values. 1196 * This method chooses to define positive zero ({@code +0.0f}), 1197 * to be greater than negative zero ({@code -0.0f}). 1198 * </ul> 1199 * 1200 * This ensures that the <i>natural ordering</i> of {@code Float} 1201 * objects imposed by this method is <i>consistent with 1202 * equals</i>; see <a href="Double.html#equivalenceRelation">this 1203 * discussion</a> for details of floating-point comparison and 1204 * ordering. 1205 * 1206 * 1207 * @param anotherFloat the {@code Float} to be compared. 1208 * @return the value {@code 0} if {@code anotherFloat} is 1209 * numerically equal to this {@code Float}; a value 1210 * less than {@code 0} if this {@code Float} 1211 * is numerically less than {@code anotherFloat}; 1212 * and a value greater than {@code 0} if this 1213 * {@code Float} is numerically greater than 1214 * {@code anotherFloat}. 1215 * 1216 * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=} 1217 * @since 1.2 1218 */ 1219 public int compareTo(Float anotherFloat) { 1220 return Float.compare(value, anotherFloat.value); 1221 } 1222 1223 /** 1224 * Compares the two specified {@code float} values. The sign 1225 * of the integer value returned is the same as that of the 1226 * integer that would be returned by the call: 1227 * <pre> 1228 * Float.valueOf(f1).compareTo(Float.valueOf(f2)) 1229 * </pre> 1230 * 1231 * @param f1 the first {@code float} to compare. 1232 * @param f2 the second {@code float} to compare. 1233 * @return the value {@code 0} if {@code f1} is 1234 * numerically equal to {@code f2}; a value less than 1235 * {@code 0} if {@code f1} is numerically less than 1236 * {@code f2}; and a value greater than {@code 0} 1237 * if {@code f1} is numerically greater than 1238 * {@code f2}. 1239 * @since 1.4 1240 */ 1241 public static int compare(float f1, float f2) { 1242 if (f1 < f2) 1243 return -1; // Neither val is NaN, thisVal is smaller 1244 if (f1 > f2) 1245 return 1; // Neither val is NaN, thisVal is larger 1246 1247 // Cannot use floatToRawIntBits because of possibility of NaNs. 1248 int thisBits = Float.floatToIntBits(f1); 1249 int anotherBits = Float.floatToIntBits(f2); 1250 1251 return (thisBits == anotherBits ? 0 : // Values are equal 1252 (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 1253 1)); // (0.0, -0.0) or (NaN, !NaN) 1254 } 1255 1256 /** 1257 * Adds two {@code float} values together as per the + operator. 1258 * 1259 * @apiNote This method corresponds to the addition operation 1260 * defined in IEEE 754. 1261 * 1262 * @param a the first operand 1263 * @param b the second operand 1264 * @return the sum of {@code a} and {@code b} 1265 * @jls 4.2.4 Floating-Point Operations 1266 * @see java.util.function.BinaryOperator 1267 * @since 1.8 1268 */ 1269 public static float sum(float a, float b) { 1270 return a + b; 1271 } 1272 1273 /** 1274 * Returns the greater of two {@code float} values 1275 * as if by calling {@link Math#max(float, float) Math.max}. 1276 * 1277 * @apiNote 1278 * This method corresponds to the maximum operation defined in 1279 * IEEE 754. 1280 * 1281 * @param a the first operand 1282 * @param b the second operand 1283 * @return the greater of {@code a} and {@code b} 1284 * @see java.util.function.BinaryOperator 1285 * @since 1.8 1286 */ 1287 public static float max(float a, float b) { 1288 return Math.max(a, b); 1289 } 1290 1291 /** 1292 * Returns the smaller of two {@code float} values 1293 * as if by calling {@link Math#min(float, float) Math.min}. 1294 * 1295 * @apiNote 1296 * This method corresponds to the minimum operation defined in 1297 * IEEE 754. 1298 * 1299 * @param a the first operand 1300 * @param b the second operand 1301 * @return the smaller of {@code a} and {@code b} 1302 * @see java.util.function.BinaryOperator 1303 * @since 1.8 1304 */ 1305 public static float min(float a, float b) { 1306 return Math.min(a, b); 1307 } 1308 1309 /** 1310 * Returns an {@link Optional} containing the nominal descriptor for this 1311 * instance, which is the instance itself. 1312 * 1313 * @return an {@link Optional} describing the {@linkplain Float} instance 1314 * @since 12 1315 * @hide 1316 */ 1317 @Override 1318 public Optional<Float> describeConstable() { 1319 return Optional.of(this); 1320 } 1321 1322 /** 1323 * Resolves this instance as a {@link ConstantDesc}, the result of which is 1324 * the instance itself. 1325 * 1326 * @param lookup ignored 1327 * @return the {@linkplain Float} instance 1328 * @since 12 1329 * @hide 1330 */ 1331 @Override 1332 public Float resolveConstantDesc(MethodHandles.Lookup lookup) { 1333 return this; 1334 } 1335 1336 /** use serialVersionUID from JDK 1.0.2 for interoperability */ 1337 @java.io.Serial 1338 private static final long serialVersionUID = -2671257302660747028L; 1339 } 1340