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