f32.rs - source

core/num/

f32.rs

1//! Constants for the `f32` single-precision floating point type.
2//!
3//! *[See also the `f32` primitive type][f32].*
4//!
5//! Mathematically significant numbers are provided in the `consts` sub-module.
6//!
7//! For the constants defined directly in this module
8//! (as distinct from those defined in the `consts` sub-module),
9//! new code should instead use the associated constants
10//! defined directly on the `f32` type.
11
12#![stable(feature = "rust1", since = "1.0.0")]
13
14use crate::convert::FloatToInt;
15use crate::num::FpCategory;
16use crate::panic::const_assert;
17use crate::{cfg_select, intrinsics, mem};
18
19/// The radix or base of the internal representation of `f32`.
20/// Use [`f32::RADIX`] instead.
21///
22/// # Examples
23///
24/// ```rust
25/// // deprecated way
26/// # #[allow(deprecated, deprecated_in_future)]
27/// let r = std::f32::RADIX;
28///
29/// // intended way
30/// let r = f32::RADIX;
31/// ```
32#[stable(feature = "rust1", since = "1.0.0")]
33#[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f32`")]
34#[rustc_diagnostic_item = "f32_legacy_const_radix"]
35pub const RADIX: u32 = f32::RADIX;
36
37/// Number of significant digits in base 2.
38/// Use [`f32::MANTISSA_DIGITS`] instead.
39///
40/// # Examples
41///
42/// ```rust
43/// // deprecated way
44/// # #[allow(deprecated, deprecated_in_future)]
45/// let d = std::f32::MANTISSA_DIGITS;
46///
47/// // intended way
48/// let d = f32::MANTISSA_DIGITS;
49/// ```
50#[stable(feature = "rust1", since = "1.0.0")]
51#[deprecated(
52    since = "TBD",
53    note = "replaced by the `MANTISSA_DIGITS` associated constant on `f32`"
54)]
55#[rustc_diagnostic_item = "f32_legacy_const_mantissa_dig"]
56pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
57
58/// Approximate number of significant digits in base 10.
59/// Use [`f32::DIGITS`] instead.
60///
61/// # Examples
62///
63/// ```rust
64/// // deprecated way
65/// # #[allow(deprecated, deprecated_in_future)]
66/// let d = std::f32::DIGITS;
67///
68/// // intended way
69/// let d = f32::DIGITS;
70/// ```
71#[stable(feature = "rust1", since = "1.0.0")]
72#[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f32`")]
73#[rustc_diagnostic_item = "f32_legacy_const_digits"]
74pub const DIGITS: u32 = f32::DIGITS;
75
76/// [Machine epsilon] value for `f32`.
77/// Use [`f32::EPSILON`] instead.
78///
79/// This is the difference between `1.0` and the next larger representable number.
80///
81/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
82///
83/// # Examples
84///
85/// ```rust
86/// // deprecated way
87/// # #[allow(deprecated, deprecated_in_future)]
88/// let e = std::f32::EPSILON;
89///
90/// // intended way
91/// let e = f32::EPSILON;
92/// ```
93#[stable(feature = "rust1", since = "1.0.0")]
94#[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f32`")]
95#[rustc_diagnostic_item = "f32_legacy_const_epsilon"]
96pub const EPSILON: f32 = f32::EPSILON;
97
98/// Smallest finite `f32` value.
99/// Use [`f32::MIN`] instead.
100///
101/// # Examples
102///
103/// ```rust
104/// // deprecated way
105/// # #[allow(deprecated, deprecated_in_future)]
106/// let min = std::f32::MIN;
107///
108/// // intended way
109/// let min = f32::MIN;
110/// ```
111#[stable(feature = "rust1", since = "1.0.0")]
112#[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f32`")]
113#[rustc_diagnostic_item = "f32_legacy_const_min"]
114pub const MIN: f32 = f32::MIN;
115
116/// Smallest positive normal `f32` value.
117/// Use [`f32::MIN_POSITIVE`] instead.
118///
119/// # Examples
120///
121/// ```rust
122/// // deprecated way
123/// # #[allow(deprecated, deprecated_in_future)]
124/// let min = std::f32::MIN_POSITIVE;
125///
126/// // intended way
127/// let min = f32::MIN_POSITIVE;
128/// ```
129#[stable(feature = "rust1", since = "1.0.0")]
130#[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f32`")]
131#[rustc_diagnostic_item = "f32_legacy_const_min_positive"]
132pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
133
134/// Largest finite `f32` value.
135/// Use [`f32::MAX`] instead.
136///
137/// # Examples
138///
139/// ```rust
140/// // deprecated way
141/// # #[allow(deprecated, deprecated_in_future)]
142/// let max = std::f32::MAX;
143///
144/// // intended way
145/// let max = f32::MAX;
146/// ```
147#[stable(feature = "rust1", since = "1.0.0")]
148#[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f32`")]
149#[rustc_diagnostic_item = "f32_legacy_const_max"]
150pub const MAX: f32 = f32::MAX;
151
152/// One greater than the minimum possible normal power of 2 exponent.
153/// Use [`f32::MIN_EXP`] instead.
154///
155/// # Examples
156///
157/// ```rust
158/// // deprecated way
159/// # #[allow(deprecated, deprecated_in_future)]
160/// let min = std::f32::MIN_EXP;
161///
162/// // intended way
163/// let min = f32::MIN_EXP;
164/// ```
165#[stable(feature = "rust1", since = "1.0.0")]
166#[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f32`")]
167#[rustc_diagnostic_item = "f32_legacy_const_min_exp"]
168pub const MIN_EXP: i32 = f32::MIN_EXP;
169
170/// Maximum possible power of 2 exponent.
171/// Use [`f32::MAX_EXP`] instead.
172///
173/// # Examples
174///
175/// ```rust
176/// // deprecated way
177/// # #[allow(deprecated, deprecated_in_future)]
178/// let max = std::f32::MAX_EXP;
179///
180/// // intended way
181/// let max = f32::MAX_EXP;
182/// ```
183#[stable(feature = "rust1", since = "1.0.0")]
184#[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f32`")]
185#[rustc_diagnostic_item = "f32_legacy_const_max_exp"]
186pub const MAX_EXP: i32 = f32::MAX_EXP;
187
188/// Minimum possible normal power of 10 exponent.
189/// Use [`f32::MIN_10_EXP`] instead.
190///
191/// # Examples
192///
193/// ```rust
194/// // deprecated way
195/// # #[allow(deprecated, deprecated_in_future)]
196/// let min = std::f32::MIN_10_EXP;
197///
198/// // intended way
199/// let min = f32::MIN_10_EXP;
200/// ```
201#[stable(feature = "rust1", since = "1.0.0")]
202#[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f32`")]
203#[rustc_diagnostic_item = "f32_legacy_const_min_10_exp"]
204pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
205
206/// Maximum possible power of 10 exponent.
207/// Use [`f32::MAX_10_EXP`] instead.
208///
209/// # Examples
210///
211/// ```rust
212/// // deprecated way
213/// # #[allow(deprecated, deprecated_in_future)]
214/// let max = std::f32::MAX_10_EXP;
215///
216/// // intended way
217/// let max = f32::MAX_10_EXP;
218/// ```
219#[stable(feature = "rust1", since = "1.0.0")]
220#[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f32`")]
221#[rustc_diagnostic_item = "f32_legacy_const_max_10_exp"]
222pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
223
224/// Not a Number (NaN).
225/// Use [`f32::NAN`] instead.
226///
227/// # Examples
228///
229/// ```rust
230/// // deprecated way
231/// # #[allow(deprecated, deprecated_in_future)]
232/// let nan = std::f32::NAN;
233///
234/// // intended way
235/// let nan = f32::NAN;
236/// ```
237#[stable(feature = "rust1", since = "1.0.0")]
238#[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f32`")]
239#[rustc_diagnostic_item = "f32_legacy_const_nan"]
240pub const NAN: f32 = f32::NAN;
241
242/// Infinity (∞).
243/// Use [`f32::INFINITY`] instead.
244///
245/// # Examples
246///
247/// ```rust
248/// // deprecated way
249/// # #[allow(deprecated, deprecated_in_future)]
250/// let inf = std::f32::INFINITY;
251///
252/// // intended way
253/// let inf = f32::INFINITY;
254/// ```
255#[stable(feature = "rust1", since = "1.0.0")]
256#[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f32`")]
257#[rustc_diagnostic_item = "f32_legacy_const_infinity"]
258pub const INFINITY: f32 = f32::INFINITY;
259
260/// Negative infinity (−∞).
261/// Use [`f32::NEG_INFINITY`] instead.
262///
263/// # Examples
264///
265/// ```rust
266/// // deprecated way
267/// # #[allow(deprecated, deprecated_in_future)]
268/// let ninf = std::f32::NEG_INFINITY;
269///
270/// // intended way
271/// let ninf = f32::NEG_INFINITY;
272/// ```
273#[stable(feature = "rust1", since = "1.0.0")]
274#[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f32`")]
275#[rustc_diagnostic_item = "f32_legacy_const_neg_infinity"]
276pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
277
278/// Basic mathematical constants.
279#[stable(feature = "rust1", since = "1.0.0")]
280#[rustc_diagnostic_item = "f32_consts_mod"]
281pub mod consts {
282    // FIXME: replace with mathematical constants from cmath.
283
284    /// Archimedes' constant (π)
285    #[stable(feature = "rust1", since = "1.0.0")]
286    pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
287
288    /// The full circle constant (τ)
289    ///
290    /// Equal to 2π.
291    #[stable(feature = "tau_constant", since = "1.47.0")]
292    pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
293
294    /// The golden ratio (φ)
295    #[stable(feature = "euler_gamma_golden_ratio", since = "1.94.0")]
296    pub const GOLDEN_RATIO: f32 = 1.618033988749894848204586834365638118_f32;
297
298    /// The Euler-Mascheroni constant (γ)
299    #[stable(feature = "euler_gamma_golden_ratio", since = "1.94.0")]
300    pub const EULER_GAMMA: f32 = 0.577215664901532860606512090082402431_f32;
301
302    /// π/2
303    #[stable(feature = "rust1", since = "1.0.0")]
304    pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
305
306    /// π/3
307    #[stable(feature = "rust1", since = "1.0.0")]
308    pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
309
310    /// π/4
311    #[stable(feature = "rust1", since = "1.0.0")]
312    pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
313
314    /// π/6
315    #[stable(feature = "rust1", since = "1.0.0")]
316    pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
317
318    /// π/8
319    #[stable(feature = "rust1", since = "1.0.0")]
320    pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
321
322    /// 1/π
323    #[stable(feature = "rust1", since = "1.0.0")]
324    pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
325
326    /// 1/sqrt(π)
327    #[unstable(feature = "more_float_constants", issue = "146939")]
328    pub const FRAC_1_SQRT_PI: f32 = 0.564189583547756286948079451560772586_f32;
329
330    /// 1/sqrt(2π)
331    #[doc(alias = "FRAC_1_SQRT_TAU")]
332    #[unstable(feature = "more_float_constants", issue = "146939")]
333    pub const FRAC_1_SQRT_2PI: f32 = 0.398942280401432677939946059934381868_f32;
334
335    /// 2/π
336    #[stable(feature = "rust1", since = "1.0.0")]
337    pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
338
339    /// 2/sqrt(π)
340    #[stable(feature = "rust1", since = "1.0.0")]
341    pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
342
343    /// sqrt(2)
344    #[stable(feature = "rust1", since = "1.0.0")]
345    pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
346
347    /// 1/sqrt(2)
348    #[stable(feature = "rust1", since = "1.0.0")]
349    pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
350
351    /// sqrt(3)
352    #[unstable(feature = "more_float_constants", issue = "146939")]
353    pub const SQRT_3: f32 = 1.732050807568877293527446341505872367_f32;
354
355    /// 1/sqrt(3)
356    #[unstable(feature = "more_float_constants", issue = "146939")]
357    pub const FRAC_1_SQRT_3: f32 = 0.577350269189625764509148780501957456_f32;
358
359    /// sqrt(5)
360    #[unstable(feature = "more_float_constants", issue = "146939")]
361    pub const SQRT_5: f32 = 2.23606797749978969640917366873127623_f32;
362
363    /// 1/sqrt(5)
364    #[unstable(feature = "more_float_constants", issue = "146939")]
365    pub const FRAC_1_SQRT_5: f32 = 0.44721359549995793928183473374625524_f32;
366
367    /// Euler's number (e)
368    #[stable(feature = "rust1", since = "1.0.0")]
369    pub const E: f32 = 2.71828182845904523536028747135266250_f32;
370
371    /// log<sub>2</sub>(e)
372    #[stable(feature = "rust1", since = "1.0.0")]
373    pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
374
375    /// log<sub>2</sub>(10)
376    #[stable(feature = "extra_log_consts", since = "1.43.0")]
377    pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
378
379    /// log<sub>10</sub>(e)
380    #[stable(feature = "rust1", since = "1.0.0")]
381    pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
382
383    /// log<sub>10</sub>(2)
384    #[stable(feature = "extra_log_consts", since = "1.43.0")]
385    pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
386
387    /// ln(2)
388    #[stable(feature = "rust1", since = "1.0.0")]
389    pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
390
391    /// ln(10)
392    #[stable(feature = "rust1", since = "1.0.0")]
393    pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
394}
395
396impl f32 {
397    /// The radix or base of the internal representation of `f32`.
398    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
399    pub const RADIX: u32 = 2;
400
401    /// The size of this float type in bits.
402    #[unstable(feature = "float_bits_const", issue = "151073")]
403    pub const BITS: u32 = 32;
404
405    /// Number of significant digits in base 2.
406    ///
407    /// Note that the size of the mantissa in the bitwise representation is one
408    /// smaller than this since the leading 1 is not stored explicitly.
409    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
410    pub const MANTISSA_DIGITS: u32 = 24;
411
412    /// Approximate number of significant digits in base 10.
413    ///
414    /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
415    /// significant digits can be converted to `f32` and back without loss.
416    ///
417    /// Equal to floor(log<sub>10</sub>&nbsp;2<sup>[`MANTISSA_DIGITS`]&nbsp;&minus;&nbsp;1</sup>).
418    ///
419    /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
420    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
421    pub const DIGITS: u32 = 6;
422
423    /// [Machine epsilon] value for `f32`.
424    ///
425    /// This is the difference between `1.0` and the next larger representable number.
426    ///
427    /// Equal to 2<sup>1&nbsp;&minus;&nbsp;[`MANTISSA_DIGITS`]</sup>.
428    ///
429    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
430    /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
431    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
432    #[rustc_diagnostic_item = "f32_epsilon"]
433    pub const EPSILON: f32 = 1.19209290e-07_f32;
434
435    /// Smallest finite `f32` value.
436    ///
437    /// Equal to &minus;[`MAX`].
438    ///
439    /// [`MAX`]: f32::MAX
440    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
441    pub const MIN: f32 = -3.40282347e+38_f32;
442    /// Smallest positive normal `f32` value.
443    ///
444    /// Equal to 2<sup>[`MIN_EXP`]&nbsp;&minus;&nbsp;1</sup>.
445    ///
446    /// [`MIN_EXP`]: f32::MIN_EXP
447    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
448    pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
449    /// Largest finite `f32` value.
450    ///
451    /// Equal to
452    /// (1&nbsp;&minus;&nbsp;2<sup>&minus;[`MANTISSA_DIGITS`]</sup>)&nbsp;2<sup>[`MAX_EXP`]</sup>.
453    ///
454    /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
455    /// [`MAX_EXP`]: f32::MAX_EXP
456    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
457    pub const MAX: f32 = 3.40282347e+38_f32;
458
459    /// One greater than the minimum possible *normal* power of 2 exponent
460    /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
461    ///
462    /// This corresponds to the exact minimum possible *normal* power of 2 exponent
463    /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
464    /// In other words, all normal numbers representable by this type are
465    /// greater than or equal to 0.5&nbsp;×&nbsp;2<sup><i>MIN_EXP</i></sup>.
466    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
467    pub const MIN_EXP: i32 = -125;
468    /// One greater than the maximum possible power of 2 exponent
469    /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
470    ///
471    /// This corresponds to the exact maximum possible power of 2 exponent
472    /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
473    /// In other words, all numbers representable by this type are
474    /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
475    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
476    pub const MAX_EXP: i32 = 128;
477
478    /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
479    ///
480    /// Equal to ceil(log<sub>10</sub>&nbsp;[`MIN_POSITIVE`]).
481    ///
482    /// [`MIN_POSITIVE`]: f32::MIN_POSITIVE
483    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
484    pub const MIN_10_EXP: i32 = -37;
485    /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
486    ///
487    /// Equal to floor(log<sub>10</sub>&nbsp;[`MAX`]).
488    ///
489    /// [`MAX`]: f32::MAX
490    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
491    pub const MAX_10_EXP: i32 = 38;
492
493    /// Not a Number (NaN).
494    ///
495    /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
496    /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
497    /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
498    /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
499    /// info.
500    ///
501    /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
502    /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
503    /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
504    /// The concrete bit pattern may change across Rust versions and target platforms.
505    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
506    #[rustc_diagnostic_item = "f32_nan"]
507    #[allow(clippy::eq_op)]
508    pub const NAN: f32 = 0.0_f32 / 0.0_f32;
509    /// Infinity (∞).
510    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
511    pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
512    /// Negative infinity (−∞).
513    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
514    pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
515
516    /// Maximum integer that can be represented exactly in an [`f32`] value,
517    /// with no other integer converting to the same floating point value.
518    ///
519    /// For an integer `x` which satisfies `MIN_EXACT_INTEGER <= x <= MAX_EXACT_INTEGER`,
520    /// there is a "one-to-one" mapping between [`i32`] and [`f32`] values.
521    /// `MAX_EXACT_INTEGER + 1` also converts losslessly to [`f32`] and back to
522    /// [`i32`], but `MAX_EXACT_INTEGER + 2` converts to the same [`f32`] value
523    /// (and back to `MAX_EXACT_INTEGER + 1` as an integer) so there is not a
524    /// "one-to-one" mapping.
525    ///
526    /// [`MAX_EXACT_INTEGER`]: f32::MAX_EXACT_INTEGER
527    /// [`MIN_EXACT_INTEGER`]: f32::MIN_EXACT_INTEGER
528    /// ```
529    /// #![feature(float_exact_integer_constants)]
530    /// # // FIXME(#152635): Float rounding on `i586` does not adhere to IEEE 754
531    /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] {
532    /// let max_exact_int = f32::MAX_EXACT_INTEGER;
533    /// assert_eq!(max_exact_int, max_exact_int as f32 as i32);
534    /// assert_eq!(max_exact_int + 1, (max_exact_int + 1) as f32 as i32);
535    /// assert_ne!(max_exact_int + 2, (max_exact_int + 2) as f32 as i32);
536    ///
537    /// // Beyond `f32::MAX_EXACT_INTEGER`, multiple integers can map to one float value
538    /// assert_eq!((max_exact_int + 1) as f32, (max_exact_int + 2) as f32);
539    /// # }
540    /// ```
541    #[unstable(feature = "float_exact_integer_constants", issue = "152466")]
542    pub const MAX_EXACT_INTEGER: i32 = (1 << Self::MANTISSA_DIGITS) - 1;
543
544    /// Minimum integer that can be represented exactly in an [`f32`] value,
545    /// with no other integer converting to the same floating point value.
546    ///
547    /// For an integer `x` which satisfies `MIN_EXACT_INTEGER <= x <= MAX_EXACT_INTEGER`,
548    /// there is a "one-to-one" mapping between [`i32`] and [`f32`] values.
549    /// `MAX_EXACT_INTEGER + 1` also converts losslessly to [`f32`] and back to
550    /// [`i32`], but `MAX_EXACT_INTEGER + 2` converts to the same [`f32`] value
551    /// (and back to `MAX_EXACT_INTEGER + 1` as an integer) so there is not a
552    /// "one-to-one" mapping.
553    ///
554    /// This constant is equivalent to `-MAX_EXACT_INTEGER`.
555    ///
556    /// [`MAX_EXACT_INTEGER`]: f32::MAX_EXACT_INTEGER
557    /// [`MIN_EXACT_INTEGER`]: f32::MIN_EXACT_INTEGER
558    /// ```
559    /// #![feature(float_exact_integer_constants)]
560    /// # // FIXME(#152635): Float rounding on `i586` does not adhere to IEEE 754
561    /// # #[cfg(not(all(target_arch = "x86", not(target_feature = "sse"))))] {
562    /// let min_exact_int = f32::MIN_EXACT_INTEGER;
563    /// assert_eq!(min_exact_int, min_exact_int as f32 as i32);
564    /// assert_eq!(min_exact_int - 1, (min_exact_int - 1) as f32 as i32);
565    /// assert_ne!(min_exact_int - 2, (min_exact_int - 2) as f32 as i32);
566    ///
567    /// // Below `f32::MIN_EXACT_INTEGER`, multiple integers can map to one float value
568    /// assert_eq!((min_exact_int - 1) as f32, (min_exact_int - 2) as f32);
569    /// # }
570    /// ```
571    #[unstable(feature = "float_exact_integer_constants", issue = "152466")]
572    pub const MIN_EXACT_INTEGER: i32 = -Self::MAX_EXACT_INTEGER;
573
574    /// Sign bit
575    pub(crate) const SIGN_MASK: u32 = 0x8000_0000;
576
577    /// Exponent mask
578    pub(crate) const EXP_MASK: u32 = 0x7f80_0000;
579
580    /// Mantissa mask
581    pub(crate) const MAN_MASK: u32 = 0x007f_ffff;
582
583    /// Minimum representable positive value (min subnormal)
584    const TINY_BITS: u32 = 0x1;
585
586    /// Minimum representable negative value (min negative subnormal)
587    const NEG_TINY_BITS: u32 = Self::TINY_BITS | Self::SIGN_MASK;
588
589    /// Returns `true` if this value is NaN.
590    ///
591    /// ```
592    /// let nan = f32::NAN;
593    /// let f = 7.0_f32;
594    ///
595    /// assert!(nan.is_nan());
596    /// assert!(!f.is_nan());
597    /// ```
598    #[must_use]
599    #[stable(feature = "rust1", since = "1.0.0")]
600    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
601    #[inline]
602    #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
603    pub const fn is_nan(self) -> bool {
604        self != self
605    }
606
607    /// Returns `true` if this value is positive infinity or negative infinity, and
608    /// `false` otherwise.
609    ///
610    /// ```
611    /// let f = 7.0f32;
612    /// let inf = f32::INFINITY;
613    /// let neg_inf = f32::NEG_INFINITY;
614    /// let nan = f32::NAN;
615    ///
616    /// assert!(!f.is_infinite());
617    /// assert!(!nan.is_infinite());
618    ///
619    /// assert!(inf.is_infinite());
620    /// assert!(neg_inf.is_infinite());
621    /// ```
622    #[must_use]
623    #[stable(feature = "rust1", since = "1.0.0")]
624    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
625    #[inline]
626    pub const fn is_infinite(self) -> bool {
627        // Getting clever with transmutation can result in incorrect answers on some FPUs
628        // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
629        // See https://github.com/rust-lang/rust/issues/72327
630        (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
631    }
632
633    /// Returns `true` if this number is neither infinite nor NaN.
634    ///
635    /// ```
636    /// let f = 7.0f32;
637    /// let inf = f32::INFINITY;
638    /// let neg_inf = f32::NEG_INFINITY;
639    /// let nan = f32::NAN;
640    ///
641    /// assert!(f.is_finite());
642    ///
643    /// assert!(!nan.is_finite());
644    /// assert!(!inf.is_finite());
645    /// assert!(!neg_inf.is_finite());
646    /// ```
647    #[must_use]
648    #[stable(feature = "rust1", since = "1.0.0")]
649    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
650    #[inline]
651    pub const fn is_finite(self) -> bool {
652        // There's no need to handle NaN separately: if self is NaN,
653        // the comparison is not true, exactly as desired.
654        self.abs() < Self::INFINITY
655    }
656
657    /// Returns `true` if the number is [subnormal].
658    ///
659    /// ```
660    /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
661    /// let max = f32::MAX;
662    /// let lower_than_min = 1.0e-40_f32;
663    /// let zero = 0.0_f32;
664    ///
665    /// assert!(!min.is_subnormal());
666    /// assert!(!max.is_subnormal());
667    ///
668    /// assert!(!zero.is_subnormal());
669    /// assert!(!f32::NAN.is_subnormal());
670    /// assert!(!f32::INFINITY.is_subnormal());
671    /// // Values between `0` and `min` are Subnormal.
672    /// assert!(lower_than_min.is_subnormal());
673    /// ```
674    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
675    #[must_use]
676    #[stable(feature = "is_subnormal", since = "1.53.0")]
677    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
678    #[inline]
679    pub const fn is_subnormal(self) -> bool {
680        matches!(self.classify(), FpCategory::Subnormal)
681    }
682
683    /// Returns `true` if the number is neither zero, infinite,
684    /// [subnormal], or NaN.
685    ///
686    /// ```
687    /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
688    /// let max = f32::MAX;
689    /// let lower_than_min = 1.0e-40_f32;
690    /// let zero = 0.0_f32;
691    ///
692    /// assert!(min.is_normal());
693    /// assert!(max.is_normal());
694    ///
695    /// assert!(!zero.is_normal());
696    /// assert!(!f32::NAN.is_normal());
697    /// assert!(!f32::INFINITY.is_normal());
698    /// // Values between `0` and `min` are Subnormal.
699    /// assert!(!lower_than_min.is_normal());
700    /// ```
701    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
702    #[must_use]
703    #[stable(feature = "rust1", since = "1.0.0")]
704    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
705    #[inline]
706    pub const fn is_normal(self) -> bool {
707        matches!(self.classify(), FpCategory::Normal)
708    }
709
710    /// Returns the floating point category of the number. If only one property
711    /// is going to be tested, it is generally faster to use the specific
712    /// predicate instead.
713    ///
714    /// ```
715    /// use std::num::FpCategory;
716    ///
717    /// let num = 12.4_f32;
718    /// let inf = f32::INFINITY;
719    ///
720    /// assert_eq!(num.classify(), FpCategory::Normal);
721    /// assert_eq!(inf.classify(), FpCategory::Infinite);
722    /// ```
723    #[stable(feature = "rust1", since = "1.0.0")]
724    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
725    pub const fn classify(self) -> FpCategory {
726        // We used to have complicated logic here that avoids the simple bit-based tests to work
727        // around buggy codegen for x87 targets (see
728        // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none
729        // of our tests is able to find any difference between the complicated and the naive
730        // version, so now we are back to the naive version.
731        let b = self.to_bits();
732        match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
733            (0, Self::EXP_MASK) => FpCategory::Infinite,
734            (_, Self::EXP_MASK) => FpCategory::Nan,
735            (0, 0) => FpCategory::Zero,
736            (_, 0) => FpCategory::Subnormal,
737            _ => FpCategory::Normal,
738        }
739    }
740
741    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
742    /// positive sign bit and positive infinity.
743    ///
744    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
745    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
746    /// conserved over arithmetic operations, the result of `is_sign_positive` on
747    /// a NaN might produce an unexpected or non-portable result. See the [specification
748    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
749    /// if you need fully portable behavior (will return `false` for all NaNs).
750    ///
751    /// ```
752    /// let f = 7.0_f32;
753    /// let g = -7.0_f32;
754    ///
755    /// assert!(f.is_sign_positive());
756    /// assert!(!g.is_sign_positive());
757    /// ```
758    #[must_use]
759    #[stable(feature = "rust1", since = "1.0.0")]
760    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
761    #[inline]
762    pub const fn is_sign_positive(self) -> bool {
763        !self.is_sign_negative()
764    }
765
766    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
767    /// negative sign bit and negative infinity.
768    ///
769    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
770    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
771    /// conserved over arithmetic operations, the result of `is_sign_negative` on
772    /// a NaN might produce an unexpected or non-portable result. See the [specification
773    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
774    /// if you need fully portable behavior (will return `false` for all NaNs).
775    ///
776    /// ```
777    /// let f = 7.0f32;
778    /// let g = -7.0f32;
779    ///
780    /// assert!(!f.is_sign_negative());
781    /// assert!(g.is_sign_negative());
782    /// ```
783    #[must_use]
784    #[stable(feature = "rust1", since = "1.0.0")]
785    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
786    #[inline]
787    pub const fn is_sign_negative(self) -> bool {
788        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
789        // applies to zeros and NaNs as well.
790        self.to_bits() & 0x8000_0000 != 0
791    }
792
793    /// Returns the least number greater than `self`.
794    ///
795    /// Let `TINY` be the smallest representable positive `f32`. Then,
796    ///  - if `self.is_nan()`, this returns `self`;
797    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
798    ///  - if `self` is `-TINY`, this returns -0.0;
799    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
800    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
801    ///  - otherwise the unique least value greater than `self` is returned.
802    ///
803    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
804    /// is finite `x == x.next_up().next_down()` also holds.
805    ///
806    /// ```rust
807    /// // f32::EPSILON is the difference between 1.0 and the next number up.
808    /// assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
809    /// // But not for most numbers.
810    /// assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
811    /// assert_eq!(16777216f32.next_up(), 16777218.0);
812    /// ```
813    ///
814    /// This operation corresponds to IEEE-754 `nextUp`.
815    ///
816    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
817    /// [`INFINITY`]: Self::INFINITY
818    /// [`MIN`]: Self::MIN
819    /// [`MAX`]: Self::MAX
820    #[inline]
821    #[doc(alias = "nextUp")]
822    #[stable(feature = "float_next_up_down", since = "1.86.0")]
823    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
824    pub const fn next_up(self) -> Self {
825        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
826        // denormals to zero. This is in general unsound and unsupported, but here
827        // we do our best to still produce the correct result on such targets.
828        let bits = self.to_bits();
829        if self.is_nan() || bits == Self::INFINITY.to_bits() {
830            return self;
831        }
832
833        let abs = bits & !Self::SIGN_MASK;
834        let next_bits = if abs == 0 {
835            Self::TINY_BITS
836        } else if bits == abs {
837            bits + 1
838        } else {
839            bits - 1
840        };
841        Self::from_bits(next_bits)
842    }
843
844    /// Returns the greatest number less than `self`.
845    ///
846    /// Let `TINY` be the smallest representable positive `f32`. Then,
847    ///  - if `self.is_nan()`, this returns `self`;
848    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
849    ///  - if `self` is `TINY`, this returns 0.0;
850    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
851    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
852    ///  - otherwise the unique greatest value less than `self` is returned.
853    ///
854    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
855    /// is finite `x == x.next_down().next_up()` also holds.
856    ///
857    /// ```rust
858    /// let x = 1.0f32;
859    /// // Clamp value into range [0, 1).
860    /// let clamped = x.clamp(0.0, 1.0f32.next_down());
861    /// assert!(clamped < 1.0);
862    /// assert_eq!(clamped.next_up(), 1.0);
863    /// ```
864    ///
865    /// This operation corresponds to IEEE-754 `nextDown`.
866    ///
867    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
868    /// [`INFINITY`]: Self::INFINITY
869    /// [`MIN`]: Self::MIN
870    /// [`MAX`]: Self::MAX
871    #[inline]
872    #[doc(alias = "nextDown")]
873    #[stable(feature = "float_next_up_down", since = "1.86.0")]
874    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
875    pub const fn next_down(self) -> Self {
876        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
877        // denormals to zero. This is in general unsound and unsupported, but here
878        // we do our best to still produce the correct result on such targets.
879        let bits = self.to_bits();
880        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
881            return self;
882        }
883
884        let abs = bits & !Self::SIGN_MASK;
885        let next_bits = if abs == 0 {
886            Self::NEG_TINY_BITS
887        } else if bits == abs {
888            bits - 1
889        } else {
890            bits + 1
891        };
892        Self::from_bits(next_bits)
893    }
894
895    /// Takes the reciprocal (inverse) of a number, `1/x`.
896    ///
897    /// ```
898    /// let x = 2.0_f32;
899    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
900    ///
901    /// assert!(abs_difference <= f32::EPSILON);
902    /// ```
903    #[must_use = "this returns the result of the operation, without modifying the original"]
904    #[stable(feature = "rust1", since = "1.0.0")]
905    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
906    #[inline]
907    pub const fn recip(self) -> f32 {
908        1.0 / self
909    }
910
911    /// Converts radians to degrees.
912    ///
913    /// # Unspecified precision
914    ///
915    /// The precision of this function is non-deterministic. This means it varies by platform,
916    /// Rust version, and can even differ within the same execution from one invocation to the next.
917    ///
918    /// # Examples
919    ///
920    /// ```
921    /// let angle = std::f32::consts::PI;
922    ///
923    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
924    /// # #[cfg(any(not(target_arch = "x86"), target_feature = "sse2"))]
925    /// assert!(abs_difference <= f32::EPSILON);
926    /// ```
927    #[must_use = "this returns the result of the operation, \
928                  without modifying the original"]
929    #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
930    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
931    #[inline]
932    pub const fn to_degrees(self) -> f32 {
933        // Use a literal to avoid double rounding, consts::PI is already rounded,
934        // and dividing would round again.
935        const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
936        self * PIS_IN_180
937    }
938
939    /// Converts degrees to radians.
940    ///
941    /// # Unspecified precision
942    ///
943    /// The precision of this function is non-deterministic. This means it varies by platform,
944    /// Rust version, and can even differ within the same execution from one invocation to the next.
945    ///
946    /// # Examples
947    ///
948    /// ```
949    /// let angle = 180.0f32;
950    ///
951    /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
952    ///
953    /// assert!(abs_difference <= f32::EPSILON);
954    /// ```
955    #[must_use = "this returns the result of the operation, \
956                  without modifying the original"]
957    #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
958    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
959    #[inline]
960    pub const fn to_radians(self) -> f32 {
961        // The division here is correctly rounded with respect to the true value of π/180.
962        // Although π is irrational and already rounded, the double rounding happens
963        // to produce correct result for f32.
964        const RADS_PER_DEG: f32 = consts::PI / 180.0;
965        self * RADS_PER_DEG
966    }
967
968    /// Returns the maximum of the two numbers, ignoring NaN.
969    ///
970    /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
971    /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
972    /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
973    /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
974    /// non-deterministically.
975    ///
976    /// The handling of NaNs follows the IEEE 754-2019 semantics for `maximumNumber`, treating all
977    /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
978    /// follows the IEEE 754-2008 semantics for `maxNum`.
979    ///
980    /// ```
981    /// let x = 1.0f32;
982    /// let y = 2.0f32;
983    ///
984    /// assert_eq!(x.max(y), y);
985    /// assert_eq!(x.max(f32::NAN), x);
986    /// ```
987    #[must_use = "this returns the result of the comparison, without modifying either input"]
988    #[stable(feature = "rust1", since = "1.0.0")]
989    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
990    #[inline]
991    pub const fn max(self, other: f32) -> f32 {
992        intrinsics::maxnumf32(self, other)
993    }
994
995    /// Returns the minimum of the two numbers, ignoring NaN.
996    ///
997    /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
998    /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
999    /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
1000    /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
1001    /// non-deterministically.
1002    ///
1003    /// The handling of NaNs follows the IEEE 754-2019 semantics for `minimumNumber`, treating all
1004    /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
1005    /// follows the IEEE 754-2008 semantics for `minNum`.
1006    ///
1007    /// ```
1008    /// let x = 1.0f32;
1009    /// let y = 2.0f32;
1010    ///
1011    /// assert_eq!(x.min(y), x);
1012    /// assert_eq!(x.min(f32::NAN), x);
1013    /// ```
1014    #[must_use = "this returns the result of the comparison, without modifying either input"]
1015    #[stable(feature = "rust1", since = "1.0.0")]
1016    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1017    #[inline]
1018    pub const fn min(self, other: f32) -> f32 {
1019        intrinsics::minnumf32(self, other)
1020    }
1021
1022    /// Returns the maximum of the two numbers, propagating NaN.
1023    ///
1024    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
1025    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
1026    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
1027    /// non-NaN inputs.
1028    ///
1029    /// This is in contrast to [`f32::max`] which only returns NaN when *both* arguments are NaN,
1030    /// and which does not reliably order `-0.0` and `+0.0`.
1031    ///
1032    /// This follows the IEEE 754-2019 semantics for `maximum`.
1033    ///
1034    /// ```
1035    /// #![feature(float_minimum_maximum)]
1036    /// let x = 1.0f32;
1037    /// let y = 2.0f32;
1038    ///
1039    /// assert_eq!(x.maximum(y), y);
1040    /// assert!(x.maximum(f32::NAN).is_nan());
1041    /// ```
1042    #[must_use = "this returns the result of the comparison, without modifying either input"]
1043    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
1044    #[inline]
1045    pub const fn maximum(self, other: f32) -> f32 {
1046        intrinsics::maximumf32(self, other)
1047    }
1048
1049    /// Returns the minimum of the two numbers, propagating NaN.
1050    ///
1051    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
1052    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
1053    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
1054    /// non-NaN inputs.
1055    ///
1056    /// This is in contrast to [`f32::min`] which only returns NaN when *both* arguments are NaN,
1057    /// and which does not reliably order `-0.0` and `+0.0`.
1058    ///
1059    /// This follows the IEEE 754-2019 semantics for `minimum`.
1060    ///
1061    /// ```
1062    /// #![feature(float_minimum_maximum)]
1063    /// let x = 1.0f32;
1064    /// let y = 2.0f32;
1065    ///
1066    /// assert_eq!(x.minimum(y), x);
1067    /// assert!(x.minimum(f32::NAN).is_nan());
1068    /// ```
1069    #[must_use = "this returns the result of the comparison, without modifying either input"]
1070    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
1071    #[inline]
1072    pub const fn minimum(self, other: f32) -> f32 {
1073        intrinsics::minimumf32(self, other)
1074    }
1075
1076    /// Calculates the midpoint (average) between `self` and `rhs`.
1077    ///
1078    /// This returns NaN when *either* argument is NaN or if a combination of
1079    /// +inf and -inf is provided as arguments.
1080    ///
1081    /// # Examples
1082    ///
1083    /// ```
1084    /// assert_eq!(1f32.midpoint(4.0), 2.5);
1085    /// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
1086    /// ```
1087    #[inline]
1088    #[doc(alias = "average")]
1089    #[stable(feature = "num_midpoint", since = "1.85.0")]
1090    #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1091    pub const fn midpoint(self, other: f32) -> f32 {
1092        cfg_select! {
1093            // Allow faster implementation that have known good 64-bit float
1094            // implementations. Falling back to the branchy code on targets that don't
1095            // have 64-bit hardware floats or buggy implementations.
1096            // https://github.com/rust-lang/rust/pull/121062#issuecomment-2123408114
1097            any(
1098                target_arch = "x86_64",
1099                target_arch = "aarch64",
1100                all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "d"),
1101                all(target_arch = "loongarch64", target_feature = "d"),
1102                all(target_arch = "arm", target_feature = "vfp2"),
1103                target_arch = "wasm32",
1104                target_arch = "wasm64",
1105            ) => {
1106                ((self as f64 + other as f64) / 2.0) as f32
1107            }
1108            _ => {
1109                const HI: f32 = f32::MAX / 2.;
1110
1111                let (a, b) = (self, other);
1112                let abs_a = a.abs();
1113                let abs_b = b.abs();
1114
1115                if abs_a <= HI && abs_b <= HI {
1116                    // Overflow is impossible
1117                    (a + b) / 2.
1118                } else {
1119                    (a / 2.) + (b / 2.)
1120                }
1121            }
1122        }
1123    }
1124
1125    /// Rounds toward zero and converts to any primitive integer type,
1126    /// assuming that the value is finite and fits in that type.
1127    ///
1128    /// ```
1129    /// let value = 4.6_f32;
1130    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1131    /// assert_eq!(rounded, 4);
1132    ///
1133    /// let value = -128.9_f32;
1134    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1135    /// assert_eq!(rounded, i8::MIN);
1136    /// ```
1137    ///
1138    /// # Safety
1139    ///
1140    /// The value must:
1141    ///
1142    /// * Not be `NaN`
1143    /// * Not be infinite
1144    /// * Be representable in the return type `Int`, after truncating off its fractional part
1145    #[must_use = "this returns the result of the operation, \
1146                  without modifying the original"]
1147    #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
1148    #[inline]
1149    pub unsafe fn to_int_unchecked<Int>(self) -> Int
1150    where
1151        Self: FloatToInt<Int>,
1152    {
1153        // SAFETY: the caller must uphold the safety contract for
1154        // `FloatToInt::to_int_unchecked`.
1155        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1156    }
1157
1158    /// Raw transmutation to `u32`.
1159    ///
1160    /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
1161    ///
1162    /// See [`from_bits`](Self::from_bits) for some discussion of the
1163    /// portability of this operation (there are almost no issues).
1164    ///
1165    /// Note that this function is distinct from `as` casting, which attempts to
1166    /// preserve the *numeric* value, and not the bitwise value.
1167    ///
1168    /// # Examples
1169    ///
1170    /// ```
1171    /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
1172    /// assert_eq!((12.5f32).to_bits(), 0x41480000);
1173    ///
1174    /// ```
1175    #[must_use = "this returns the result of the operation, \
1176                  without modifying the original"]
1177    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1178    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1179    #[inline]
1180    #[allow(unnecessary_transmutes)]
1181    pub const fn to_bits(self) -> u32 {
1182        // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1183        unsafe { mem::transmute(self) }
1184    }
1185
1186    /// Raw transmutation from `u32`.
1187    ///
1188    /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1189    /// It turns out this is incredibly portable, for two reasons:
1190    ///
1191    /// * Floats and Ints have the same endianness on all supported platforms.
1192    /// * IEEE 754 very precisely specifies the bit layout of floats.
1193    ///
1194    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1195    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1196    /// (notably x86 and ARM) picked the interpretation that was ultimately
1197    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1198    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1199    ///
1200    /// Rather than trying to preserve signaling-ness cross-platform, this
1201    /// implementation favors preserving the exact bits. This means that
1202    /// any payloads encoded in NaNs will be preserved even if the result of
1203    /// this method is sent over the network from an x86 machine to a MIPS one.
1204    ///
1205    /// If the results of this method are only manipulated by the same
1206    /// architecture that produced them, then there is no portability concern.
1207    ///
1208    /// If the input isn't NaN, then there is no portability concern.
1209    ///
1210    /// If you don't care about signalingness (very likely), then there is no
1211    /// portability concern.
1212    ///
1213    /// Note that this function is distinct from `as` casting, which attempts to
1214    /// preserve the *numeric* value, and not the bitwise value.
1215    ///
1216    /// # Examples
1217    ///
1218    /// ```
1219    /// let v = f32::from_bits(0x41480000);
1220    /// assert_eq!(v, 12.5);
1221    /// ```
1222    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1223    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1224    #[must_use]
1225    #[inline]
1226    #[allow(unnecessary_transmutes)]
1227    pub const fn from_bits(v: u32) -> Self {
1228        // It turns out the safety issues with sNaN were overblown! Hooray!
1229        // SAFETY: `u32` is a plain old datatype so we can always transmute from it.
1230        unsafe { mem::transmute(v) }
1231    }
1232
1233    /// Returns the memory representation of this floating point number as a byte array in
1234    /// big-endian (network) byte order.
1235    ///
1236    /// See [`from_bits`](Self::from_bits) for some discussion of the
1237    /// portability of this operation (there are almost no issues).
1238    ///
1239    /// # Examples
1240    ///
1241    /// ```
1242    /// let bytes = 12.5f32.to_be_bytes();
1243    /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1244    /// ```
1245    #[must_use = "this returns the result of the operation, \
1246                  without modifying the original"]
1247    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1248    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1249    #[inline]
1250    pub const fn to_be_bytes(self) -> [u8; 4] {
1251        self.to_bits().to_be_bytes()
1252    }
1253
1254    /// Returns the memory representation of this floating point number as a byte array in
1255    /// little-endian byte order.
1256    ///
1257    /// See [`from_bits`](Self::from_bits) for some discussion of the
1258    /// portability of this operation (there are almost no issues).
1259    ///
1260    /// # Examples
1261    ///
1262    /// ```
1263    /// let bytes = 12.5f32.to_le_bytes();
1264    /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1265    /// ```
1266    #[must_use = "this returns the result of the operation, \
1267                  without modifying the original"]
1268    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1269    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1270    #[inline]
1271    pub const fn to_le_bytes(self) -> [u8; 4] {
1272        self.to_bits().to_le_bytes()
1273    }
1274
1275    /// Returns the memory representation of this floating point number as a byte array in
1276    /// native byte order.
1277    ///
1278    /// As the target platform's native endianness is used, portable code
1279    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1280    ///
1281    /// [`to_be_bytes`]: f32::to_be_bytes
1282    /// [`to_le_bytes`]: f32::to_le_bytes
1283    ///
1284    /// See [`from_bits`](Self::from_bits) for some discussion of the
1285    /// portability of this operation (there are almost no issues).
1286    ///
1287    /// # Examples
1288    ///
1289    /// ```
1290    /// let bytes = 12.5f32.to_ne_bytes();
1291    /// assert_eq!(
1292    ///     bytes,
1293    ///     if cfg!(target_endian = "big") {
1294    ///         [0x41, 0x48, 0x00, 0x00]
1295    ///     } else {
1296    ///         [0x00, 0x00, 0x48, 0x41]
1297    ///     }
1298    /// );
1299    /// ```
1300    #[must_use = "this returns the result of the operation, \
1301                  without modifying the original"]
1302    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1303    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1304    #[inline]
1305    pub const fn to_ne_bytes(self) -> [u8; 4] {
1306        self.to_bits().to_ne_bytes()
1307    }
1308
1309    /// Creates a floating point value from its representation as a byte array in big endian.
1310    ///
1311    /// See [`from_bits`](Self::from_bits) for some discussion of the
1312    /// portability of this operation (there are almost no issues).
1313    ///
1314    /// # Examples
1315    ///
1316    /// ```
1317    /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1318    /// assert_eq!(value, 12.5);
1319    /// ```
1320    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1321    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1322    #[must_use]
1323    #[inline]
1324    pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1325        Self::from_bits(u32::from_be_bytes(bytes))
1326    }
1327
1328    /// Creates a floating point value from its representation as a byte array in little endian.
1329    ///
1330    /// See [`from_bits`](Self::from_bits) for some discussion of the
1331    /// portability of this operation (there are almost no issues).
1332    ///
1333    /// # Examples
1334    ///
1335    /// ```
1336    /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1337    /// assert_eq!(value, 12.5);
1338    /// ```
1339    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1340    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1341    #[must_use]
1342    #[inline]
1343    pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1344        Self::from_bits(u32::from_le_bytes(bytes))
1345    }
1346
1347    /// Creates a floating point value from its representation as a byte array in native endian.
1348    ///
1349    /// As the target platform's native endianness is used, portable code
1350    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1351    /// appropriate instead.
1352    ///
1353    /// [`from_be_bytes`]: f32::from_be_bytes
1354    /// [`from_le_bytes`]: f32::from_le_bytes
1355    ///
1356    /// See [`from_bits`](Self::from_bits) for some discussion of the
1357    /// portability of this operation (there are almost no issues).
1358    ///
1359    /// # Examples
1360    ///
1361    /// ```
1362    /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1363    ///     [0x41, 0x48, 0x00, 0x00]
1364    /// } else {
1365    ///     [0x00, 0x00, 0x48, 0x41]
1366    /// });
1367    /// assert_eq!(value, 12.5);
1368    /// ```
1369    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1370    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1371    #[must_use]
1372    #[inline]
1373    pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1374        Self::from_bits(u32::from_ne_bytes(bytes))
1375    }
1376
1377    /// Returns the ordering between `self` and `other`.
1378    ///
1379    /// Unlike the standard partial comparison between floating point numbers,
1380    /// this comparison always produces an ordering in accordance to
1381    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1382    /// floating point standard. The values are ordered in the following sequence:
1383    ///
1384    /// - negative quiet NaN
1385    /// - negative signaling NaN
1386    /// - negative infinity
1387    /// - negative numbers
1388    /// - negative subnormal numbers
1389    /// - negative zero
1390    /// - positive zero
1391    /// - positive subnormal numbers
1392    /// - positive numbers
1393    /// - positive infinity
1394    /// - positive signaling NaN
1395    /// - positive quiet NaN.
1396    ///
1397    /// The ordering established by this function does not always agree with the
1398    /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1399    /// they consider negative and positive zero equal, while `total_cmp`
1400    /// doesn't.
1401    ///
1402    /// The interpretation of the signaling NaN bit follows the definition in
1403    /// the IEEE 754 standard, which may not match the interpretation by some of
1404    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1405    ///
1406    /// # Example
1407    ///
1408    /// ```
1409    /// struct GoodBoy {
1410    ///     name: String,
1411    ///     weight: f32,
1412    /// }
1413    ///
1414    /// let mut bois = vec![
1415    ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1416    ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1417    ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1418    ///     GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1419    ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1420    ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1421    /// ];
1422    ///
1423    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1424    ///
1425    /// // `f32::NAN` could be positive or negative, which will affect the sort order.
1426    /// if f32::NAN.is_sign_negative() {
1427    ///     assert!(bois.into_iter().map(|b| b.weight)
1428    ///         .zip([f32::NAN, -5.0, 0.1, 10.0, 99.0, f32::INFINITY].iter())
1429    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1430    /// } else {
1431    ///     assert!(bois.into_iter().map(|b| b.weight)
1432    ///         .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1433    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1434    /// }
1435    /// ```
1436    #[stable(feature = "total_cmp", since = "1.62.0")]
1437    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1438    #[must_use]
1439    #[inline]
1440    pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1441        let mut left = self.to_bits() as i32;
1442        let mut right = other.to_bits() as i32;
1443
1444        // In case of negatives, flip all the bits except the sign
1445        // to achieve a similar layout as two's complement integers
1446        //
1447        // Why does this work? IEEE 754 floats consist of three fields:
1448        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1449        // fields as a whole have the property that their bitwise order is
1450        // equal to the numeric magnitude where the magnitude is defined.
1451        // The magnitude is not normally defined on NaN values, but
1452        // IEEE 754 totalOrder defines the NaN values also to follow the
1453        // bitwise order. This leads to order explained in the doc comment.
1454        // However, the representation of magnitude is the same for negative
1455        // and positive numbers – only the sign bit is different.
1456        // To easily compare the floats as signed integers, we need to
1457        // flip the exponent and mantissa bits in case of negative numbers.
1458        // We effectively convert the numbers to "two's complement" form.
1459        //
1460        // To do the flipping, we construct a mask and XOR against it.
1461        // We branchlessly calculate an "all-ones except for the sign bit"
1462        // mask from negative-signed values: right shifting sign-extends
1463        // the integer, so we "fill" the mask with sign bits, and then
1464        // convert to unsigned to push one more zero bit.
1465        // On positive values, the mask is all zeros, so it's a no-op.
1466        left ^= (((left >> 31) as u32) >> 1) as i32;
1467        right ^= (((right >> 31) as u32) >> 1) as i32;
1468
1469        left.cmp(&right)
1470    }
1471
1472    /// Restrict a value to a certain interval unless it is NaN.
1473    ///
1474    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1475    /// less than `min`. Otherwise this returns `self`.
1476    ///
1477    /// Note that this function returns NaN if the initial value was NaN as
1478    /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1479    /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1480    ///
1481    /// # Panics
1482    ///
1483    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1484    ///
1485    /// # Examples
1486    ///
1487    /// ```
1488    /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1489    /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1490    /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1491    /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1492    ///
1493    /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1494    /// assert!((0.0f32).clamp(-0.0, -0.0) == 0.0);
1495    /// assert!((1.0f32).clamp(-0.0, 0.0) == 0.0);
1496    /// // This is definitely a negative zero.
1497    /// assert!((-1.0f32).clamp(-0.0, 1.0).is_sign_negative());
1498    /// ```
1499    #[must_use = "method returns a new number and does not mutate the original value"]
1500    #[stable(feature = "clamp", since = "1.50.0")]
1501    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1502    #[inline]
1503    pub const fn clamp(mut self, min: f32, max: f32) -> f32 {
1504        const_assert!(
1505            min <= max,
1506            "min > max, or either was NaN",
1507            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1508            min: f32,
1509            max: f32,
1510        );
1511
1512        if self < min {
1513            self = min;
1514        }
1515        if self > max {
1516            self = max;
1517        }
1518        self
1519    }
1520
1521    /// Clamps this number to a symmetric range centered around zero.
1522    ///
1523    /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1524    ///
1525    /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1526    /// explicit about the intent.
1527    ///
1528    /// # Panics
1529    ///
1530    /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1531    ///
1532    /// # Examples
1533    ///
1534    /// ```
1535    /// #![feature(clamp_magnitude)]
1536    /// assert_eq!(5.0f32.clamp_magnitude(3.0), 3.0);
1537    /// assert_eq!((-5.0f32).clamp_magnitude(3.0), -3.0);
1538    /// assert_eq!(2.0f32.clamp_magnitude(3.0), 2.0);
1539    /// assert_eq!((-2.0f32).clamp_magnitude(3.0), -2.0);
1540    /// ```
1541    #[must_use = "this returns the clamped value and does not modify the original"]
1542    #[unstable(feature = "clamp_magnitude", issue = "148519")]
1543    #[inline]
1544    pub fn clamp_magnitude(self, limit: f32) -> f32 {
1545        assert!(limit >= 0.0, "limit must be non-negative");
1546        let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1547        self.clamp(-limit, limit)
1548    }
1549
1550    /// Computes the absolute value of `self`.
1551    ///
1552    /// This function always returns the precise result.
1553    ///
1554    /// # Examples
1555    ///
1556    /// ```
1557    /// let x = 3.5_f32;
1558    /// let y = -3.5_f32;
1559    ///
1560    /// assert_eq!(x.abs(), x);
1561    /// assert_eq!(y.abs(), -y);
1562    ///
1563    /// assert!(f32::NAN.abs().is_nan());
1564    /// ```
1565    #[must_use = "method returns a new number and does not mutate the original value"]
1566    #[stable(feature = "rust1", since = "1.0.0")]
1567    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1568    #[inline]
1569    pub const fn abs(self) -> f32 {
1570        intrinsics::fabsf32(self)
1571    }
1572
1573    /// Returns a number that represents the sign of `self`.
1574    ///
1575    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1576    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1577    /// - NaN if the number is NaN
1578    ///
1579    /// # Examples
1580    ///
1581    /// ```
1582    /// let f = 3.5_f32;
1583    ///
1584    /// assert_eq!(f.signum(), 1.0);
1585    /// assert_eq!(f32::NEG_INFINITY.signum(), -1.0);
1586    ///
1587    /// assert!(f32::NAN.signum().is_nan());
1588    /// ```
1589    #[must_use = "method returns a new number and does not mutate the original value"]
1590    #[stable(feature = "rust1", since = "1.0.0")]
1591    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1592    #[inline]
1593    pub const fn signum(self) -> f32 {
1594        if self.is_nan() { Self::NAN } else { 1.0_f32.copysign(self) }
1595    }
1596
1597    /// Returns a number composed of the magnitude of `self` and the sign of
1598    /// `sign`.
1599    ///
1600    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1601    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1602    /// returned.
1603    ///
1604    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1605    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1606    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1607    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1608    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1609    /// info.
1610    ///
1611    /// # Examples
1612    ///
1613    /// ```
1614    /// let f = 3.5_f32;
1615    ///
1616    /// assert_eq!(f.copysign(0.42), 3.5_f32);
1617    /// assert_eq!(f.copysign(-0.42), -3.5_f32);
1618    /// assert_eq!((-f).copysign(0.42), 3.5_f32);
1619    /// assert_eq!((-f).copysign(-0.42), -3.5_f32);
1620    ///
1621    /// assert!(f32::NAN.copysign(1.0).is_nan());
1622    /// ```
1623    #[must_use = "method returns a new number and does not mutate the original value"]
1624    #[inline]
1625    #[stable(feature = "copysign", since = "1.35.0")]
1626    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1627    pub const fn copysign(self, sign: f32) -> f32 {
1628        intrinsics::copysignf32(self, sign)
1629    }
1630
1631    /// Float addition that allows optimizations based on algebraic rules.
1632    ///
1633    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1634    #[must_use = "method returns a new number and does not mutate the original value"]
1635    #[unstable(feature = "float_algebraic", issue = "136469")]
1636    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1637    #[inline]
1638    pub const fn algebraic_add(self, rhs: f32) -> f32 {
1639        intrinsics::fadd_algebraic(self, rhs)
1640    }
1641
1642    /// Float subtraction that allows optimizations based on algebraic rules.
1643    ///
1644    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1645    #[must_use = "method returns a new number and does not mutate the original value"]
1646    #[unstable(feature = "float_algebraic", issue = "136469")]
1647    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1648    #[inline]
1649    pub const fn algebraic_sub(self, rhs: f32) -> f32 {
1650        intrinsics::fsub_algebraic(self, rhs)
1651    }
1652
1653    /// Float multiplication that allows optimizations based on algebraic rules.
1654    ///
1655    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1656    #[must_use = "method returns a new number and does not mutate the original value"]
1657    #[unstable(feature = "float_algebraic", issue = "136469")]
1658    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1659    #[inline]
1660    pub const fn algebraic_mul(self, rhs: f32) -> f32 {
1661        intrinsics::fmul_algebraic(self, rhs)
1662    }
1663
1664    /// Float division that allows optimizations based on algebraic rules.
1665    ///
1666    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1667    #[must_use = "method returns a new number and does not mutate the original value"]
1668    #[unstable(feature = "float_algebraic", issue = "136469")]
1669    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1670    #[inline]
1671    pub const fn algebraic_div(self, rhs: f32) -> f32 {
1672        intrinsics::fdiv_algebraic(self, rhs)
1673    }
1674
1675    /// Float remainder that allows optimizations based on algebraic rules.
1676    ///
1677    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1678    #[must_use = "method returns a new number and does not mutate the original value"]
1679    #[unstable(feature = "float_algebraic", issue = "136469")]
1680    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1681    #[inline]
1682    pub const fn algebraic_rem(self, rhs: f32) -> f32 {
1683        intrinsics::frem_algebraic(self, rhs)
1684    }
1685}
1686
1687/// Experimental implementations of floating point functions in `core`.
1688///
1689/// _The standalone functions in this module are for testing only.
1690/// They will be stabilized as inherent methods._
1691#[unstable(feature = "core_float_math", issue = "137578")]
1692pub mod math {
1693    use crate::intrinsics;
1694    use crate::num::libm;
1695
1696    /// Experimental version of `floor` in `core`. See [`f32::floor`] for details.
1697    ///
1698    /// # Examples
1699    ///
1700    /// ```
1701    /// #![feature(core_float_math)]
1702    ///
1703    /// use core::f32;
1704    ///
1705    /// let f = 3.7_f32;
1706    /// let g = 3.0_f32;
1707    /// let h = -3.7_f32;
1708    ///
1709    /// assert_eq!(f32::math::floor(f), 3.0);
1710    /// assert_eq!(f32::math::floor(g), 3.0);
1711    /// assert_eq!(f32::math::floor(h), -4.0);
1712    /// ```
1713    ///
1714    /// _This standalone function is for testing only.
1715    /// It will be stabilized as an inherent method._
1716    ///
1717    /// [`f32::floor`]: ../../../std/primitive.f32.html#method.floor
1718    #[inline]
1719    #[unstable(feature = "core_float_math", issue = "137578")]
1720    #[must_use = "method returns a new number and does not mutate the original value"]
1721    pub const fn floor(x: f32) -> f32 {
1722        intrinsics::floorf32(x)
1723    }
1724
1725    /// Experimental version of `ceil` in `core`. See [`f32::ceil`] for details.
1726    ///
1727    /// # Examples
1728    ///
1729    /// ```
1730    /// #![feature(core_float_math)]
1731    ///
1732    /// use core::f32;
1733    ///
1734    /// let f = 3.01_f32;
1735    /// let g = 4.0_f32;
1736    ///
1737    /// assert_eq!(f32::math::ceil(f), 4.0);
1738    /// assert_eq!(f32::math::ceil(g), 4.0);
1739    /// ```
1740    ///
1741    /// _This standalone function is for testing only.
1742    /// It will be stabilized as an inherent method._
1743    ///
1744    /// [`f32::ceil`]: ../../../std/primitive.f32.html#method.ceil
1745    #[inline]
1746    #[doc(alias = "ceiling")]
1747    #[must_use = "method returns a new number and does not mutate the original value"]
1748    #[unstable(feature = "core_float_math", issue = "137578")]
1749    pub const fn ceil(x: f32) -> f32 {
1750        intrinsics::ceilf32(x)
1751    }
1752
1753    /// Experimental version of `round` in `core`. See [`f32::round`] for details.
1754    ///
1755    /// # Examples
1756    ///
1757    /// ```
1758    /// #![feature(core_float_math)]
1759    ///
1760    /// use core::f32;
1761    ///
1762    /// let f = 3.3_f32;
1763    /// let g = -3.3_f32;
1764    /// let h = -3.7_f32;
1765    /// let i = 3.5_f32;
1766    /// let j = 4.5_f32;
1767    ///
1768    /// assert_eq!(f32::math::round(f), 3.0);
1769    /// assert_eq!(f32::math::round(g), -3.0);
1770    /// assert_eq!(f32::math::round(h), -4.0);
1771    /// assert_eq!(f32::math::round(i), 4.0);
1772    /// assert_eq!(f32::math::round(j), 5.0);
1773    /// ```
1774    ///
1775    /// _This standalone function is for testing only.
1776    /// It will be stabilized as an inherent method._
1777    ///
1778    /// [`f32::round`]: ../../../std/primitive.f32.html#method.round
1779    #[inline]
1780    #[unstable(feature = "core_float_math", issue = "137578")]
1781    #[must_use = "method returns a new number and does not mutate the original value"]
1782    pub const fn round(x: f32) -> f32 {
1783        intrinsics::roundf32(x)
1784    }
1785
1786    /// Experimental version of `round_ties_even` in `core`. See [`f32::round_ties_even`] for
1787    /// details.
1788    ///
1789    /// # Examples
1790    ///
1791    /// ```
1792    /// #![feature(core_float_math)]
1793    ///
1794    /// use core::f32;
1795    ///
1796    /// let f = 3.3_f32;
1797    /// let g = -3.3_f32;
1798    /// let h = 3.5_f32;
1799    /// let i = 4.5_f32;
1800    ///
1801    /// assert_eq!(f32::math::round_ties_even(f), 3.0);
1802    /// assert_eq!(f32::math::round_ties_even(g), -3.0);
1803    /// assert_eq!(f32::math::round_ties_even(h), 4.0);
1804    /// assert_eq!(f32::math::round_ties_even(i), 4.0);
1805    /// ```
1806    ///
1807    /// _This standalone function is for testing only.
1808    /// It will be stabilized as an inherent method._
1809    ///
1810    /// [`f32::round_ties_even`]: ../../../std/primitive.f32.html#method.round_ties_even
1811    #[inline]
1812    #[unstable(feature = "core_float_math", issue = "137578")]
1813    #[must_use = "method returns a new number and does not mutate the original value"]
1814    pub const fn round_ties_even(x: f32) -> f32 {
1815        intrinsics::round_ties_even_f32(x)
1816    }
1817
1818    /// Experimental version of `trunc` in `core`. See [`f32::trunc`] for details.
1819    ///
1820    /// # Examples
1821    ///
1822    /// ```
1823    /// #![feature(core_float_math)]
1824    ///
1825    /// use core::f32;
1826    ///
1827    /// let f = 3.7_f32;
1828    /// let g = 3.0_f32;
1829    /// let h = -3.7_f32;
1830    ///
1831    /// assert_eq!(f32::math::trunc(f), 3.0);
1832    /// assert_eq!(f32::math::trunc(g), 3.0);
1833    /// assert_eq!(f32::math::trunc(h), -3.0);
1834    /// ```
1835    ///
1836    /// _This standalone function is for testing only.
1837    /// It will be stabilized as an inherent method._
1838    ///
1839    /// [`f32::trunc`]: ../../../std/primitive.f32.html#method.trunc
1840    #[inline]
1841    #[doc(alias = "truncate")]
1842    #[must_use = "method returns a new number and does not mutate the original value"]
1843    #[unstable(feature = "core_float_math", issue = "137578")]
1844    pub const fn trunc(x: f32) -> f32 {
1845        intrinsics::truncf32(x)
1846    }
1847
1848    /// Experimental version of `fract` in `core`. See [`f32::fract`] for details.
1849    ///
1850    /// # Examples
1851    ///
1852    /// ```
1853    /// #![feature(core_float_math)]
1854    ///
1855    /// use core::f32;
1856    ///
1857    /// let x = 3.6_f32;
1858    /// let y = -3.6_f32;
1859    /// let abs_difference_x = (f32::math::fract(x) - 0.6).abs();
1860    /// let abs_difference_y = (f32::math::fract(y) - (-0.6)).abs();
1861    ///
1862    /// assert!(abs_difference_x <= f32::EPSILON);
1863    /// assert!(abs_difference_y <= f32::EPSILON);
1864    /// ```
1865    ///
1866    /// _This standalone function is for testing only.
1867    /// It will be stabilized as an inherent method._
1868    ///
1869    /// [`f32::fract`]: ../../../std/primitive.f32.html#method.fract
1870    #[inline]
1871    #[unstable(feature = "core_float_math", issue = "137578")]
1872    #[must_use = "method returns a new number and does not mutate the original value"]
1873    pub const fn fract(x: f32) -> f32 {
1874        x - trunc(x)
1875    }
1876
1877    /// Experimental version of `mul_add` in `core`. See [`f32::mul_add`] for details.
1878    ///
1879    /// # Examples
1880    ///
1881    /// ```
1882    /// # #![allow(unused_features)]
1883    /// #![feature(core_float_math)]
1884    ///
1885    /// # // FIXME(#140515): mingw has an incorrect fma
1886    /// # // https://sourceforge.net/p/mingw-w64/bugs/848/
1887    /// # #[cfg(all(target_os = "windows", target_env = "gnu", not(target_abi = "llvm")))] {
1888    /// use core::f32;
1889    ///
1890    /// let m = 10.0_f32;
1891    /// let x = 4.0_f32;
1892    /// let b = 60.0_f32;
1893    ///
1894    /// assert_eq!(f32::math::mul_add(m, x, b), 100.0);
1895    /// assert_eq!(m * x + b, 100.0);
1896    ///
1897    /// let one_plus_eps = 1.0_f32 + f32::EPSILON;
1898    /// let one_minus_eps = 1.0_f32 - f32::EPSILON;
1899    /// let minus_one = -1.0_f32;
1900    ///
1901    /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1902    /// assert_eq!(
1903    ///     f32::math::mul_add(one_plus_eps, one_minus_eps, minus_one),
1904    ///     -f32::EPSILON * f32::EPSILON
1905    /// );
1906    /// // Different rounding with the non-fused multiply and add.
1907    /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1908    /// # }
1909    /// ```
1910    ///
1911    /// _This standalone function is for testing only.
1912    /// It will be stabilized as an inherent method._
1913    ///
1914    /// [`f32::mul_add`]: ../../../std/primitive.f32.html#method.mul_add
1915    #[inline]
1916    #[doc(alias = "fmaf", alias = "fusedMultiplyAdd")]
1917    #[must_use = "method returns a new number and does not mutate the original value"]
1918    #[unstable(feature = "core_float_math", issue = "137578")]
1919    pub const fn mul_add(x: f32, y: f32, z: f32) -> f32 {
1920        intrinsics::fmaf32(x, y, z)
1921    }
1922
1923    /// Experimental version of `div_euclid` in `core`. See [`f32::div_euclid`] for details.
1924    ///
1925    /// # Examples
1926    ///
1927    /// ```
1928    /// #![feature(core_float_math)]
1929    ///
1930    /// use core::f32;
1931    ///
1932    /// let a: f32 = 7.0;
1933    /// let b = 4.0;
1934    /// assert_eq!(f32::math::div_euclid(a, b), 1.0); // 7.0 > 4.0 * 1.0
1935    /// assert_eq!(f32::math::div_euclid(-a, b), -2.0); // -7.0 >= 4.0 * -2.0
1936    /// assert_eq!(f32::math::div_euclid(a, -b), -1.0); // 7.0 >= -4.0 * -1.0
1937    /// assert_eq!(f32::math::div_euclid(-a, -b), 2.0); // -7.0 >= -4.0 * 2.0
1938    /// ```
1939    ///
1940    /// _This standalone function is for testing only.
1941    /// It will be stabilized as an inherent method._
1942    ///
1943    /// [`f32::div_euclid`]: ../../../std/primitive.f32.html#method.div_euclid
1944    #[inline]
1945    #[unstable(feature = "core_float_math", issue = "137578")]
1946    #[must_use = "method returns a new number and does not mutate the original value"]
1947    pub fn div_euclid(x: f32, rhs: f32) -> f32 {
1948        let q = trunc(x / rhs);
1949        if x % rhs < 0.0 {
1950            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1951        }
1952        q
1953    }
1954
1955    /// Experimental version of `rem_euclid` in `core`. See [`f32::rem_euclid`] for details.
1956    ///
1957    /// # Examples
1958    ///
1959    /// ```
1960    /// #![feature(core_float_math)]
1961    ///
1962    /// use core::f32;
1963    ///
1964    /// let a: f32 = 7.0;
1965    /// let b = 4.0;
1966    /// assert_eq!(f32::math::rem_euclid(a, b), 3.0);
1967    /// assert_eq!(f32::math::rem_euclid(-a, b), 1.0);
1968    /// assert_eq!(f32::math::rem_euclid(a, -b), 3.0);
1969    /// assert_eq!(f32::math::rem_euclid(-a, -b), 1.0);
1970    /// // limitation due to round-off error
1971    /// assert!(f32::math::rem_euclid(-f32::EPSILON, 3.0) != 0.0);
1972    /// ```
1973    ///
1974    /// _This standalone function is for testing only.
1975    /// It will be stabilized as an inherent method._
1976    ///
1977    /// [`f32::rem_euclid`]: ../../../std/primitive.f32.html#method.rem_euclid
1978    #[inline]
1979    #[doc(alias = "modulo", alias = "mod")]
1980    #[unstable(feature = "core_float_math", issue = "137578")]
1981    #[must_use = "method returns a new number and does not mutate the original value"]
1982    pub fn rem_euclid(x: f32, rhs: f32) -> f32 {
1983        let r = x % rhs;
1984        if r < 0.0 { r + rhs.abs() } else { r }
1985    }
1986
1987    /// Experimental version of `powi` in `core`. See [`f32::powi`] for details.
1988    ///
1989    /// # Examples
1990    ///
1991    /// ```
1992    /// #![feature(core_float_math)]
1993    ///
1994    /// use core::f32;
1995    ///
1996    /// let x = 2.0_f32;
1997    /// let abs_difference = (f32::math::powi(x, 2) - (x * x)).abs();
1998    /// assert!(abs_difference <= 1e-5);
1999    ///
2000    /// assert_eq!(f32::math::powi(f32::NAN, 0), 1.0);
2001    /// ```
2002    ///
2003    /// _This standalone function is for testing only.
2004    /// It will be stabilized as an inherent method._
2005    ///
2006    /// [`f32::powi`]: ../../../std/primitive.f32.html#method.powi
2007    #[inline]
2008    #[must_use = "method returns a new number and does not mutate the original value"]
2009    #[unstable(feature = "core_float_math", issue = "137578")]
2010    pub fn powi(x: f32, n: i32) -> f32 {
2011        intrinsics::powif32(x, n)
2012    }
2013
2014    /// Experimental version of `sqrt` in `core`. See [`f32::sqrt`] for details.
2015    ///
2016    /// # Examples
2017    ///
2018    /// ```
2019    /// #![feature(core_float_math)]
2020    ///
2021    /// use core::f32;
2022    ///
2023    /// let positive = 4.0_f32;
2024    /// let negative = -4.0_f32;
2025    /// let negative_zero = -0.0_f32;
2026    ///
2027    /// assert_eq!(f32::math::sqrt(positive), 2.0);
2028    /// assert!(f32::math::sqrt(negative).is_nan());
2029    /// assert_eq!(f32::math::sqrt(negative_zero), negative_zero);
2030    /// ```
2031    ///
2032    /// _This standalone function is for testing only.
2033    /// It will be stabilized as an inherent method._
2034    ///
2035    /// [`f32::sqrt`]: ../../../std/primitive.f32.html#method.sqrt
2036    #[inline]
2037    #[doc(alias = "squareRoot")]
2038    #[unstable(feature = "core_float_math", issue = "137578")]
2039    #[must_use = "method returns a new number and does not mutate the original value"]
2040    pub fn sqrt(x: f32) -> f32 {
2041        intrinsics::sqrtf32(x)
2042    }
2043
2044    /// Experimental version of `abs_sub` in `core`. See [`f32::abs_sub`] for details.
2045    ///
2046    /// # Examples
2047    ///
2048    /// ```
2049    /// #![feature(core_float_math)]
2050    ///
2051    /// use core::f32;
2052    ///
2053    /// let x = 3.0f32;
2054    /// let y = -3.0f32;
2055    ///
2056    /// let abs_difference_x = (f32::math::abs_sub(x, 1.0) - 2.0).abs();
2057    /// let abs_difference_y = (f32::math::abs_sub(y, 1.0) - 0.0).abs();
2058    ///
2059    /// assert!(abs_difference_x <= 1e-6);
2060    /// assert!(abs_difference_y <= 1e-6);
2061    /// ```
2062    ///
2063    /// _This standalone function is for testing only.
2064    /// It will be stabilized as an inherent method._
2065    ///
2066    /// [`f32::abs_sub`]: ../../../std/primitive.f32.html#method.abs_sub
2067    #[inline]
2068    #[stable(feature = "rust1", since = "1.0.0")]
2069    #[deprecated(
2070        since = "1.10.0",
2071        note = "you probably meant `(self - other).abs()`: \
2072            this operation is `(self - other).max(0.0)` \
2073            except that `abs_sub` also propagates NaNs (also \
2074            known as `fdimf` in C). If you truly need the positive \
2075            difference, consider using that expression or the C function \
2076            `fdimf`, depending on how you wish to handle NaN (please consider \
2077            filing an issue describing your use-case too)."
2078    )]
2079    #[must_use = "method returns a new number and does not mutate the original value"]
2080    pub fn abs_sub(x: f32, other: f32) -> f32 {
2081        libm::fdimf(x, other)
2082    }
2083
2084    /// Experimental version of `cbrt` in `core`. See [`f32::cbrt`] for details.
2085    ///
2086    /// # Unspecified precision
2087    ///
2088    /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
2089    /// can even differ within the same execution from one invocation to the next.
2090    /// This function currently corresponds to the `cbrtf` from libc on Unix
2091    /// and Windows. Note that this might change in the future.
2092    ///
2093    /// # Examples
2094    ///
2095    /// ```
2096    /// #![feature(core_float_math)]
2097    ///
2098    /// use core::f32;
2099    ///
2100    /// let x = 8.0f32;
2101    ///
2102    /// // x^(1/3) - 2 == 0
2103    /// let abs_difference = (f32::math::cbrt(x) - 2.0).abs();
2104    ///
2105    /// assert!(abs_difference <= 1e-6);
2106    /// ```
2107    ///
2108    /// _This standalone function is for testing only.
2109    /// It will be stabilized as an inherent method._
2110    ///
2111    /// [`f32::cbrt`]: ../../../std/primitive.f32.html#method.cbrt
2112    #[inline]
2113    #[must_use = "method returns a new number and does not mutate the original value"]
2114    #[unstable(feature = "core_float_math", issue = "137578")]
2115    pub fn cbrt(x: f32) -> f32 {
2116        libm::cbrtf(x)
2117    }
2118}