Skip to main content

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