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