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