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