core/num/
f32.rs

1//! Constants for the `f32` single-precision floating point type.
2//!
3//! *[See also the `f32` primitive type][f32].*
4//!
5//! Mathematically significant numbers are provided in the `consts` sub-module.
6//!
7//! For the constants defined directly in this module
8//! (as distinct from those defined in the `consts` sub-module),
9//! new code should instead use the associated constants
10//! defined directly on the `f32` type.
11
12#![stable(feature = "rust1", since = "1.0.0")]
13
14use crate::convert::FloatToInt;
15use crate::num::FpCategory;
16use crate::panic::const_assert;
17use crate::{cfg_match, intrinsics, mem};
18
19/// The radix or base of the internal representation of `f32`.
20/// Use [`f32::RADIX`] instead.
21///
22/// # Examples
23///
24/// ```rust
25/// // deprecated way
26/// # #[allow(deprecated, deprecated_in_future)]
27/// let r = std::f32::RADIX;
28///
29/// // intended way
30/// let r = f32::RADIX;
31/// ```
32#[stable(feature = "rust1", since = "1.0.0")]
33#[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f32`")]
34#[rustc_diagnostic_item = "f32_legacy_const_radix"]
35pub const RADIX: u32 = f32::RADIX;
36
37/// Number of significant digits in base 2.
38/// Use [`f32::MANTISSA_DIGITS`] instead.
39///
40/// # Examples
41///
42/// ```rust
43/// // deprecated way
44/// # #[allow(deprecated, deprecated_in_future)]
45/// let d = std::f32::MANTISSA_DIGITS;
46///
47/// // intended way
48/// let d = f32::MANTISSA_DIGITS;
49/// ```
50#[stable(feature = "rust1", since = "1.0.0")]
51#[deprecated(
52    since = "TBD",
53    note = "replaced by the `MANTISSA_DIGITS` associated constant on `f32`"
54)]
55#[rustc_diagnostic_item = "f32_legacy_const_mantissa_dig"]
56pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
57
58/// Approximate number of significant digits in base 10.
59/// Use [`f32::DIGITS`] instead.
60///
61/// # Examples
62///
63/// ```rust
64/// // deprecated way
65/// # #[allow(deprecated, deprecated_in_future)]
66/// let d = std::f32::DIGITS;
67///
68/// // intended way
69/// let d = f32::DIGITS;
70/// ```
71#[stable(feature = "rust1", since = "1.0.0")]
72#[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f32`")]
73#[rustc_diagnostic_item = "f32_legacy_const_digits"]
74pub const DIGITS: u32 = f32::DIGITS;
75
76/// [Machine epsilon] value for `f32`.
77/// Use [`f32::EPSILON`] instead.
78///
79/// This is the difference between `1.0` and the next larger representable number.
80///
81/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
82///
83/// # Examples
84///
85/// ```rust
86/// // deprecated way
87/// # #[allow(deprecated, deprecated_in_future)]
88/// let e = std::f32::EPSILON;
89///
90/// // intended way
91/// let e = f32::EPSILON;
92/// ```
93#[stable(feature = "rust1", since = "1.0.0")]
94#[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f32`")]
95#[rustc_diagnostic_item = "f32_legacy_const_epsilon"]
96pub const EPSILON: f32 = f32::EPSILON;
97
98/// Smallest finite `f32` value.
99/// Use [`f32::MIN`] instead.
100///
101/// # Examples
102///
103/// ```rust
104/// // deprecated way
105/// # #[allow(deprecated, deprecated_in_future)]
106/// let min = std::f32::MIN;
107///
108/// // intended way
109/// let min = f32::MIN;
110/// ```
111#[stable(feature = "rust1", since = "1.0.0")]
112#[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f32`")]
113#[rustc_diagnostic_item = "f32_legacy_const_min"]
114pub const MIN: f32 = f32::MIN;
115
116/// Smallest positive normal `f32` value.
117/// Use [`f32::MIN_POSITIVE`] instead.
118///
119/// # Examples
120///
121/// ```rust
122/// // deprecated way
123/// # #[allow(deprecated, deprecated_in_future)]
124/// let min = std::f32::MIN_POSITIVE;
125///
126/// // intended way
127/// let min = f32::MIN_POSITIVE;
128/// ```
129#[stable(feature = "rust1", since = "1.0.0")]
130#[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f32`")]
131#[rustc_diagnostic_item = "f32_legacy_const_min_positive"]
132pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
133
134/// Largest finite `f32` value.
135/// Use [`f32::MAX`] instead.
136///
137/// # Examples
138///
139/// ```rust
140/// // deprecated way
141/// # #[allow(deprecated, deprecated_in_future)]
142/// let max = std::f32::MAX;
143///
144/// // intended way
145/// let max = f32::MAX;
146/// ```
147#[stable(feature = "rust1", since = "1.0.0")]
148#[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f32`")]
149#[rustc_diagnostic_item = "f32_legacy_const_max"]
150pub const MAX: f32 = f32::MAX;
151
152/// One greater than the minimum possible normal power of 2 exponent.
153/// Use [`f32::MIN_EXP`] instead.
154///
155/// # Examples
156///
157/// ```rust
158/// // deprecated way
159/// # #[allow(deprecated, deprecated_in_future)]
160/// let min = std::f32::MIN_EXP;
161///
162/// // intended way
163/// let min = f32::MIN_EXP;
164/// ```
165#[stable(feature = "rust1", since = "1.0.0")]
166#[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f32`")]
167#[rustc_diagnostic_item = "f32_legacy_const_min_exp"]
168pub const MIN_EXP: i32 = f32::MIN_EXP;
169
170/// Maximum possible power of 2 exponent.
171/// Use [`f32::MAX_EXP`] instead.
172///
173/// # Examples
174///
175/// ```rust
176/// // deprecated way
177/// # #[allow(deprecated, deprecated_in_future)]
178/// let max = std::f32::MAX_EXP;
179///
180/// // intended way
181/// let max = f32::MAX_EXP;
182/// ```
183#[stable(feature = "rust1", since = "1.0.0")]
184#[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f32`")]
185#[rustc_diagnostic_item = "f32_legacy_const_max_exp"]
186pub const MAX_EXP: i32 = f32::MAX_EXP;
187
188/// Minimum possible normal power of 10 exponent.
189/// Use [`f32::MIN_10_EXP`] instead.
190///
191/// # Examples
192///
193/// ```rust
194/// // deprecated way
195/// # #[allow(deprecated, deprecated_in_future)]
196/// let min = std::f32::MIN_10_EXP;
197///
198/// // intended way
199/// let min = f32::MIN_10_EXP;
200/// ```
201#[stable(feature = "rust1", since = "1.0.0")]
202#[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f32`")]
203#[rustc_diagnostic_item = "f32_legacy_const_min_10_exp"]
204pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
205
206/// Maximum possible power of 10 exponent.
207/// Use [`f32::MAX_10_EXP`] instead.
208///
209/// # Examples
210///
211/// ```rust
212/// // deprecated way
213/// # #[allow(deprecated, deprecated_in_future)]
214/// let max = std::f32::MAX_10_EXP;
215///
216/// // intended way
217/// let max = f32::MAX_10_EXP;
218/// ```
219#[stable(feature = "rust1", since = "1.0.0")]
220#[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f32`")]
221#[rustc_diagnostic_item = "f32_legacy_const_max_10_exp"]
222pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
223
224/// Not a Number (NaN).
225/// Use [`f32::NAN`] instead.
226///
227/// # Examples
228///
229/// ```rust
230/// // deprecated way
231/// # #[allow(deprecated, deprecated_in_future)]
232/// let nan = std::f32::NAN;
233///
234/// // intended way
235/// let nan = f32::NAN;
236/// ```
237#[stable(feature = "rust1", since = "1.0.0")]
238#[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f32`")]
239#[rustc_diagnostic_item = "f32_legacy_const_nan"]
240pub const NAN: f32 = f32::NAN;
241
242/// Infinity (∞).
243/// Use [`f32::INFINITY`] instead.
244///
245/// # Examples
246///
247/// ```rust
248/// // deprecated way
249/// # #[allow(deprecated, deprecated_in_future)]
250/// let inf = std::f32::INFINITY;
251///
252/// // intended way
253/// let inf = f32::INFINITY;
254/// ```
255#[stable(feature = "rust1", since = "1.0.0")]
256#[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f32`")]
257#[rustc_diagnostic_item = "f32_legacy_const_infinity"]
258pub const INFINITY: f32 = f32::INFINITY;
259
260/// Negative infinity (−∞).
261/// Use [`f32::NEG_INFINITY`] instead.
262///
263/// # Examples
264///
265/// ```rust
266/// // deprecated way
267/// # #[allow(deprecated, deprecated_in_future)]
268/// let ninf = std::f32::NEG_INFINITY;
269///
270/// // intended way
271/// let ninf = f32::NEG_INFINITY;
272/// ```
273#[stable(feature = "rust1", since = "1.0.0")]
274#[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f32`")]
275#[rustc_diagnostic_item = "f32_legacy_const_neg_infinity"]
276pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
277
278/// Basic mathematical constants.
279#[stable(feature = "rust1", since = "1.0.0")]
280pub mod consts {
281    // FIXME: replace with mathematical constants from cmath.
282
283    /// Archimedes' constant (π)
284    #[stable(feature = "rust1", since = "1.0.0")]
285    pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
286
287    /// The full circle constant (τ)
288    ///
289    /// Equal to 2π.
290    #[stable(feature = "tau_constant", since = "1.47.0")]
291    pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
292
293    /// The golden ratio (φ)
294    #[unstable(feature = "more_float_constants", issue = "103883")]
295    pub const PHI: f32 = 1.618033988749894848204586834365638118_f32;
296
297    /// The Euler-Mascheroni constant (γ)
298    #[unstable(feature = "more_float_constants", issue = "103883")]
299    pub const EGAMMA: f32 = 0.577215664901532860606512090082402431_f32;
300
301    /// π/2
302    #[stable(feature = "rust1", since = "1.0.0")]
303    pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
304
305    /// π/3
306    #[stable(feature = "rust1", since = "1.0.0")]
307    pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
308
309    /// π/4
310    #[stable(feature = "rust1", since = "1.0.0")]
311    pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
312
313    /// π/6
314    #[stable(feature = "rust1", since = "1.0.0")]
315    pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
316
317    /// π/8
318    #[stable(feature = "rust1", since = "1.0.0")]
319    pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
320
321    /// 1/π
322    #[stable(feature = "rust1", since = "1.0.0")]
323    pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
324
325    /// 1/sqrt(π)
326    #[unstable(feature = "more_float_constants", issue = "103883")]
327    pub const FRAC_1_SQRT_PI: f32 = 0.564189583547756286948079451560772586_f32;
328
329    /// 1/sqrt(2π)
330    #[doc(alias = "FRAC_1_SQRT_TAU")]
331    #[unstable(feature = "more_float_constants", issue = "103883")]
332    pub const FRAC_1_SQRT_2PI: f32 = 0.398942280401432677939946059934381868_f32;
333
334    /// 2/π
335    #[stable(feature = "rust1", since = "1.0.0")]
336    pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
337
338    /// 2/sqrt(π)
339    #[stable(feature = "rust1", since = "1.0.0")]
340    pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
341
342    /// sqrt(2)
343    #[stable(feature = "rust1", since = "1.0.0")]
344    pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
345
346    /// 1/sqrt(2)
347    #[stable(feature = "rust1", since = "1.0.0")]
348    pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
349
350    /// sqrt(3)
351    #[unstable(feature = "more_float_constants", issue = "103883")]
352    pub const SQRT_3: f32 = 1.732050807568877293527446341505872367_f32;
353
354    /// 1/sqrt(3)
355    #[unstable(feature = "more_float_constants", issue = "103883")]
356    pub const FRAC_1_SQRT_3: f32 = 0.577350269189625764509148780501957456_f32;
357
358    /// Euler's number (e)
359    #[stable(feature = "rust1", since = "1.0.0")]
360    pub const E: f32 = 2.71828182845904523536028747135266250_f32;
361
362    /// log<sub>2</sub>(e)
363    #[stable(feature = "rust1", since = "1.0.0")]
364    pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
365
366    /// log<sub>2</sub>(10)
367    #[stable(feature = "extra_log_consts", since = "1.43.0")]
368    pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
369
370    /// log<sub>10</sub>(e)
371    #[stable(feature = "rust1", since = "1.0.0")]
372    pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
373
374    /// log<sub>10</sub>(2)
375    #[stable(feature = "extra_log_consts", since = "1.43.0")]
376    pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
377
378    /// ln(2)
379    #[stable(feature = "rust1", since = "1.0.0")]
380    pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
381
382    /// ln(10)
383    #[stable(feature = "rust1", since = "1.0.0")]
384    pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
385}
386
387impl f32 {
388    /// The radix or base of the internal representation of `f32`.
389    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
390    pub const RADIX: u32 = 2;
391
392    /// Number of significant digits in base 2.
393    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
394    pub const MANTISSA_DIGITS: u32 = 24;
395
396    /// Approximate number of significant digits in base 10.
397    ///
398    /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
399    /// significant digits can be converted to `f32` and back without loss.
400    ///
401    /// Equal to floor(log<sub>10</sub>&nbsp;2<sup>[`MANTISSA_DIGITS`]&nbsp;&minus;&nbsp;1</sup>).
402    ///
403    /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
404    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
405    pub const DIGITS: u32 = 6;
406
407    /// [Machine epsilon] value for `f32`.
408    ///
409    /// This is the difference between `1.0` and the next larger representable number.
410    ///
411    /// Equal to 2<sup>1&nbsp;&minus;&nbsp;[`MANTISSA_DIGITS`]</sup>.
412    ///
413    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
414    /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
415    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
416    #[rustc_diagnostic_item = "f32_epsilon"]
417    pub const EPSILON: f32 = 1.19209290e-07_f32;
418
419    /// Smallest finite `f32` value.
420    ///
421    /// Equal to &minus;[`MAX`].
422    ///
423    /// [`MAX`]: f32::MAX
424    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
425    pub const MIN: f32 = -3.40282347e+38_f32;
426    /// Smallest positive normal `f32` value.
427    ///
428    /// Equal to 2<sup>[`MIN_EXP`]&nbsp;&minus;&nbsp;1</sup>.
429    ///
430    /// [`MIN_EXP`]: f32::MIN_EXP
431    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
432    pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
433    /// Largest finite `f32` value.
434    ///
435    /// Equal to
436    /// (1&nbsp;&minus;&nbsp;2<sup>&minus;[`MANTISSA_DIGITS`]</sup>)&nbsp;2<sup>[`MAX_EXP`]</sup>.
437    ///
438    /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
439    /// [`MAX_EXP`]: f32::MAX_EXP
440    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
441    pub const MAX: f32 = 3.40282347e+38_f32;
442
443    /// One greater than the minimum possible normal power of 2 exponent.
444    ///
445    /// If <i>x</i>&nbsp;=&nbsp;`MIN_EXP`, then normal numbers
446    /// ≥&nbsp;0.5&nbsp;×&nbsp;2<sup><i>x</i></sup>.
447    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
448    pub const MIN_EXP: i32 = -125;
449    /// Maximum possible power of 2 exponent.
450    ///
451    /// If <i>x</i>&nbsp;=&nbsp;`MAX_EXP`, then normal numbers
452    /// &lt;&nbsp;1&nbsp;×&nbsp;2<sup><i>x</i></sup>.
453    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
454    pub const MAX_EXP: i32 = 128;
455
456    /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
457    ///
458    /// Equal to ceil(log<sub>10</sub>&nbsp;[`MIN_POSITIVE`]).
459    ///
460    /// [`MIN_POSITIVE`]: f32::MIN_POSITIVE
461    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
462    pub const MIN_10_EXP: i32 = -37;
463    /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
464    ///
465    /// Equal to floor(log<sub>10</sub>&nbsp;[`MAX`]).
466    ///
467    /// [`MAX`]: f32::MAX
468    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
469    pub const MAX_10_EXP: i32 = 38;
470
471    /// Not a Number (NaN).
472    ///
473    /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
474    /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
475    /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
476    /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
477    /// info.
478    ///
479    /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
480    /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
481    /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
482    /// The concrete bit pattern may change across Rust versions and target platforms.
483    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
484    #[rustc_diagnostic_item = "f32_nan"]
485    #[allow(clippy::eq_op)]
486    pub const NAN: f32 = 0.0_f32 / 0.0_f32;
487    /// Infinity (∞).
488    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
489    pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
490    /// Negative infinity (−∞).
491    #[stable(feature = "assoc_int_consts", since = "1.43.0")]
492    pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
493
494    /// Sign bit
495    pub(crate) const SIGN_MASK: u32 = 0x8000_0000;
496
497    /// Exponent mask
498    pub(crate) const EXP_MASK: u32 = 0x7f80_0000;
499
500    /// Mantissa mask
501    pub(crate) const MAN_MASK: u32 = 0x007f_ffff;
502
503    /// Minimum representable positive value (min subnormal)
504    const TINY_BITS: u32 = 0x1;
505
506    /// Minimum representable negative value (min negative subnormal)
507    const NEG_TINY_BITS: u32 = Self::TINY_BITS | Self::SIGN_MASK;
508
509    /// Returns `true` if this value is NaN.
510    ///
511    /// ```
512    /// let nan = f32::NAN;
513    /// let f = 7.0_f32;
514    ///
515    /// assert!(nan.is_nan());
516    /// assert!(!f.is_nan());
517    /// ```
518    #[must_use]
519    #[stable(feature = "rust1", since = "1.0.0")]
520    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
521    #[inline]
522    #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
523    pub const fn is_nan(self) -> bool {
524        self != self
525    }
526
527    /// Returns `true` if this value is positive infinity or negative infinity, and
528    /// `false` otherwise.
529    ///
530    /// ```
531    /// let f = 7.0f32;
532    /// let inf = f32::INFINITY;
533    /// let neg_inf = f32::NEG_INFINITY;
534    /// let nan = f32::NAN;
535    ///
536    /// assert!(!f.is_infinite());
537    /// assert!(!nan.is_infinite());
538    ///
539    /// assert!(inf.is_infinite());
540    /// assert!(neg_inf.is_infinite());
541    /// ```
542    #[must_use]
543    #[stable(feature = "rust1", since = "1.0.0")]
544    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
545    #[inline]
546    pub const fn is_infinite(self) -> bool {
547        // Getting clever with transmutation can result in incorrect answers on some FPUs
548        // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
549        // See https://github.com/rust-lang/rust/issues/72327
550        (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
551    }
552
553    /// Returns `true` if this number is neither infinite nor NaN.
554    ///
555    /// ```
556    /// let f = 7.0f32;
557    /// let inf = f32::INFINITY;
558    /// let neg_inf = f32::NEG_INFINITY;
559    /// let nan = f32::NAN;
560    ///
561    /// assert!(f.is_finite());
562    ///
563    /// assert!(!nan.is_finite());
564    /// assert!(!inf.is_finite());
565    /// assert!(!neg_inf.is_finite());
566    /// ```
567    #[must_use]
568    #[stable(feature = "rust1", since = "1.0.0")]
569    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
570    #[inline]
571    pub const fn is_finite(self) -> bool {
572        // There's no need to handle NaN separately: if self is NaN,
573        // the comparison is not true, exactly as desired.
574        self.abs() < Self::INFINITY
575    }
576
577    /// Returns `true` if the number is [subnormal].
578    ///
579    /// ```
580    /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
581    /// let max = f32::MAX;
582    /// let lower_than_min = 1.0e-40_f32;
583    /// let zero = 0.0_f32;
584    ///
585    /// assert!(!min.is_subnormal());
586    /// assert!(!max.is_subnormal());
587    ///
588    /// assert!(!zero.is_subnormal());
589    /// assert!(!f32::NAN.is_subnormal());
590    /// assert!(!f32::INFINITY.is_subnormal());
591    /// // Values between `0` and `min` are Subnormal.
592    /// assert!(lower_than_min.is_subnormal());
593    /// ```
594    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
595    #[must_use]
596    #[stable(feature = "is_subnormal", since = "1.53.0")]
597    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
598    #[inline]
599    pub const fn is_subnormal(self) -> bool {
600        matches!(self.classify(), FpCategory::Subnormal)
601    }
602
603    /// Returns `true` if the number is neither zero, infinite,
604    /// [subnormal], or NaN.
605    ///
606    /// ```
607    /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
608    /// let max = f32::MAX;
609    /// let lower_than_min = 1.0e-40_f32;
610    /// let zero = 0.0_f32;
611    ///
612    /// assert!(min.is_normal());
613    /// assert!(max.is_normal());
614    ///
615    /// assert!(!zero.is_normal());
616    /// assert!(!f32::NAN.is_normal());
617    /// assert!(!f32::INFINITY.is_normal());
618    /// // Values between `0` and `min` are Subnormal.
619    /// assert!(!lower_than_min.is_normal());
620    /// ```
621    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
622    #[must_use]
623    #[stable(feature = "rust1", since = "1.0.0")]
624    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
625    #[inline]
626    pub const fn is_normal(self) -> bool {
627        matches!(self.classify(), FpCategory::Normal)
628    }
629
630    /// Returns the floating point category of the number. If only one property
631    /// is going to be tested, it is generally faster to use the specific
632    /// predicate instead.
633    ///
634    /// ```
635    /// use std::num::FpCategory;
636    ///
637    /// let num = 12.4_f32;
638    /// let inf = f32::INFINITY;
639    ///
640    /// assert_eq!(num.classify(), FpCategory::Normal);
641    /// assert_eq!(inf.classify(), FpCategory::Infinite);
642    /// ```
643    #[stable(feature = "rust1", since = "1.0.0")]
644    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
645    pub const fn classify(self) -> FpCategory {
646        // We used to have complicated logic here that avoids the simple bit-based tests to work
647        // around buggy codegen for x87 targets (see
648        // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none
649        // of our tests is able to find any difference between the complicated and the naive
650        // version, so now we are back to the naive version.
651        let b = self.to_bits();
652        match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
653            (0, Self::EXP_MASK) => FpCategory::Infinite,
654            (_, Self::EXP_MASK) => FpCategory::Nan,
655            (0, 0) => FpCategory::Zero,
656            (_, 0) => FpCategory::Subnormal,
657            _ => FpCategory::Normal,
658        }
659    }
660
661    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
662    /// positive sign bit and positive infinity.
663    ///
664    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
665    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
666    /// conserved over arithmetic operations, the result of `is_sign_positive` on
667    /// a NaN might produce an unexpected or non-portable result. See the [specification
668    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
669    /// if you need fully portable behavior (will return `false` for all NaNs).
670    ///
671    /// ```
672    /// let f = 7.0_f32;
673    /// let g = -7.0_f32;
674    ///
675    /// assert!(f.is_sign_positive());
676    /// assert!(!g.is_sign_positive());
677    /// ```
678    #[must_use]
679    #[stable(feature = "rust1", since = "1.0.0")]
680    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
681    #[inline]
682    pub const fn is_sign_positive(self) -> bool {
683        !self.is_sign_negative()
684    }
685
686    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
687    /// negative sign bit and negative infinity.
688    ///
689    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
690    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
691    /// conserved over arithmetic operations, the result of `is_sign_negative` on
692    /// a NaN might produce an unexpected or non-portable result. See the [specification
693    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
694    /// if you need fully portable behavior (will return `false` for all NaNs).
695    ///
696    /// ```
697    /// let f = 7.0f32;
698    /// let g = -7.0f32;
699    ///
700    /// assert!(!f.is_sign_negative());
701    /// assert!(g.is_sign_negative());
702    /// ```
703    #[must_use]
704    #[stable(feature = "rust1", since = "1.0.0")]
705    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
706    #[inline]
707    pub const fn is_sign_negative(self) -> bool {
708        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
709        // applies to zeros and NaNs as well.
710        // SAFETY: This is just transmuting to get the sign bit, it's fine.
711        unsafe { mem::transmute::<f32, u32>(self) & 0x8000_0000 != 0 }
712    }
713
714    /// Returns the least number greater than `self`.
715    ///
716    /// Let `TINY` be the smallest representable positive `f32`. Then,
717    ///  - if `self.is_nan()`, this returns `self`;
718    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
719    ///  - if `self` is `-TINY`, this returns -0.0;
720    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
721    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
722    ///  - otherwise the unique least value greater than `self` is returned.
723    ///
724    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
725    /// is finite `x == x.next_up().next_down()` also holds.
726    ///
727    /// ```rust
728    /// // f32::EPSILON is the difference between 1.0 and the next number up.
729    /// assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
730    /// // But not for most numbers.
731    /// assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
732    /// assert_eq!(16777216f32.next_up(), 16777218.0);
733    /// ```
734    ///
735    /// This operation corresponds to IEEE-754 `nextUp`.
736    ///
737    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
738    /// [`INFINITY`]: Self::INFINITY
739    /// [`MIN`]: Self::MIN
740    /// [`MAX`]: Self::MAX
741    #[inline]
742    #[doc(alias = "nextUp")]
743    #[stable(feature = "float_next_up_down", since = "1.86.0")]
744    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
745    pub const fn next_up(self) -> Self {
746        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
747        // denormals to zero. This is in general unsound and unsupported, but here
748        // we do our best to still produce the correct result on such targets.
749        let bits = self.to_bits();
750        if self.is_nan() || bits == Self::INFINITY.to_bits() {
751            return self;
752        }
753
754        let abs = bits & !Self::SIGN_MASK;
755        let next_bits = if abs == 0 {
756            Self::TINY_BITS
757        } else if bits == abs {
758            bits + 1
759        } else {
760            bits - 1
761        };
762        Self::from_bits(next_bits)
763    }
764
765    /// Returns the greatest number less than `self`.
766    ///
767    /// Let `TINY` be the smallest representable positive `f32`. Then,
768    ///  - if `self.is_nan()`, this returns `self`;
769    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
770    ///  - if `self` is `TINY`, this returns 0.0;
771    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
772    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
773    ///  - otherwise the unique greatest value less than `self` is returned.
774    ///
775    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
776    /// is finite `x == x.next_down().next_up()` also holds.
777    ///
778    /// ```rust
779    /// let x = 1.0f32;
780    /// // Clamp value into range [0, 1).
781    /// let clamped = x.clamp(0.0, 1.0f32.next_down());
782    /// assert!(clamped < 1.0);
783    /// assert_eq!(clamped.next_up(), 1.0);
784    /// ```
785    ///
786    /// This operation corresponds to IEEE-754 `nextDown`.
787    ///
788    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
789    /// [`INFINITY`]: Self::INFINITY
790    /// [`MIN`]: Self::MIN
791    /// [`MAX`]: Self::MAX
792    #[inline]
793    #[doc(alias = "nextDown")]
794    #[stable(feature = "float_next_up_down", since = "1.86.0")]
795    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
796    pub const fn next_down(self) -> Self {
797        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
798        // denormals to zero. This is in general unsound and unsupported, but here
799        // we do our best to still produce the correct result on such targets.
800        let bits = self.to_bits();
801        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
802            return self;
803        }
804
805        let abs = bits & !Self::SIGN_MASK;
806        let next_bits = if abs == 0 {
807            Self::NEG_TINY_BITS
808        } else if bits == abs {
809            bits - 1
810        } else {
811            bits + 1
812        };
813        Self::from_bits(next_bits)
814    }
815
816    /// Takes the reciprocal (inverse) of a number, `1/x`.
817    ///
818    /// ```
819    /// let x = 2.0_f32;
820    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
821    ///
822    /// assert!(abs_difference <= f32::EPSILON);
823    /// ```
824    #[must_use = "this returns the result of the operation, without modifying the original"]
825    #[stable(feature = "rust1", since = "1.0.0")]
826    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
827    #[inline]
828    pub const fn recip(self) -> f32 {
829        1.0 / self
830    }
831
832    /// Converts radians to degrees.
833    ///
834    /// ```
835    /// let angle = std::f32::consts::PI;
836    ///
837    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
838    /// # #[cfg(any(not(target_arch = "x86"), target_feature = "sse2"))]
839    /// assert!(abs_difference <= f32::EPSILON);
840    /// ```
841    #[must_use = "this returns the result of the operation, \
842                  without modifying the original"]
843    #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
844    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
845    #[inline]
846    pub const fn to_degrees(self) -> f32 {
847        // Use a constant for better precision.
848        const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
849        self * PIS_IN_180
850    }
851
852    /// Converts degrees to radians.
853    ///
854    /// ```
855    /// let angle = 180.0f32;
856    ///
857    /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
858    ///
859    /// assert!(abs_difference <= f32::EPSILON);
860    /// ```
861    #[must_use = "this returns the result of the operation, \
862                  without modifying the original"]
863    #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
864    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
865    #[inline]
866    pub const fn to_radians(self) -> f32 {
867        const RADS_PER_DEG: f32 = consts::PI / 180.0;
868        self * RADS_PER_DEG
869    }
870
871    /// Returns the maximum of the two numbers, ignoring NaN.
872    ///
873    /// If one of the arguments is NaN, then the other argument is returned.
874    /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
875    /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
876    /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
877    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
878    ///
879    /// ```
880    /// let x = 1.0f32;
881    /// let y = 2.0f32;
882    ///
883    /// assert_eq!(x.max(y), y);
884    /// ```
885    #[must_use = "this returns the result of the comparison, without modifying either input"]
886    #[stable(feature = "rust1", since = "1.0.0")]
887    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
888    #[inline]
889    pub const fn max(self, other: f32) -> f32 {
890        intrinsics::maxnumf32(self, other)
891    }
892
893    /// Returns the minimum of the two numbers, ignoring NaN.
894    ///
895    /// If one of the arguments is NaN, then the other argument is returned.
896    /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
897    /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
898    /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
899    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
900    ///
901    /// ```
902    /// let x = 1.0f32;
903    /// let y = 2.0f32;
904    ///
905    /// assert_eq!(x.min(y), x);
906    /// ```
907    #[must_use = "this returns the result of the comparison, without modifying either input"]
908    #[stable(feature = "rust1", since = "1.0.0")]
909    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
910    #[inline]
911    pub const fn min(self, other: f32) -> f32 {
912        intrinsics::minnumf32(self, other)
913    }
914
915    /// Returns the maximum of the two numbers, propagating NaN.
916    ///
917    /// This returns NaN when *either* argument is NaN, as opposed to
918    /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
919    ///
920    /// ```
921    /// #![feature(float_minimum_maximum)]
922    /// let x = 1.0f32;
923    /// let y = 2.0f32;
924    ///
925    /// assert_eq!(x.maximum(y), y);
926    /// assert!(x.maximum(f32::NAN).is_nan());
927    /// ```
928    ///
929    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
930    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
931    /// Note that this follows the semantics specified in IEEE 754-2019.
932    ///
933    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
934    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
935    #[must_use = "this returns the result of the comparison, without modifying either input"]
936    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
937    #[inline]
938    pub const fn maximum(self, other: f32) -> f32 {
939        if self > other {
940            self
941        } else if other > self {
942            other
943        } else if self == other {
944            if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
945        } else {
946            self + other
947        }
948    }
949
950    /// Returns the minimum of the two numbers, propagating NaN.
951    ///
952    /// This returns NaN when *either* argument is NaN, as opposed to
953    /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
954    ///
955    /// ```
956    /// #![feature(float_minimum_maximum)]
957    /// let x = 1.0f32;
958    /// let y = 2.0f32;
959    ///
960    /// assert_eq!(x.minimum(y), x);
961    /// assert!(x.minimum(f32::NAN).is_nan());
962    /// ```
963    ///
964    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
965    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
966    /// Note that this follows the semantics specified in IEEE 754-2019.
967    ///
968    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
969    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
970    #[must_use = "this returns the result of the comparison, without modifying either input"]
971    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
972    #[inline]
973    pub const fn minimum(self, other: f32) -> f32 {
974        if self < other {
975            self
976        } else if other < self {
977            other
978        } else if self == other {
979            if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
980        } else {
981            // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
982            self + other
983        }
984    }
985
986    /// Calculates the middle point of `self` and `rhs`.
987    ///
988    /// This returns NaN when *either* argument is NaN or if a combination of
989    /// +inf and -inf is provided as arguments.
990    ///
991    /// # Examples
992    ///
993    /// ```
994    /// assert_eq!(1f32.midpoint(4.0), 2.5);
995    /// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
996    /// ```
997    #[inline]
998    #[stable(feature = "num_midpoint", since = "1.85.0")]
999    #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1000    pub const fn midpoint(self, other: f32) -> f32 {
1001        cfg_match! {
1002            // Allow faster implementation that have known good 64-bit float
1003            // implementations. Falling back to the branchy code on targets that don't
1004            // have 64-bit hardware floats or buggy implementations.
1005            // https://github.com/rust-lang/rust/pull/121062#issuecomment-2123408114
1006            any(
1007                target_arch = "x86_64",
1008                target_arch = "aarch64",
1009                all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "d"),
1010                all(target_arch = "arm", target_feature = "vfp2"),
1011                target_arch = "wasm32",
1012                target_arch = "wasm64",
1013            ) => {
1014                ((self as f64 + other as f64) / 2.0) as f32
1015            }
1016            _ => {
1017                const LO: f32 = f32::MIN_POSITIVE * 2.;
1018                const HI: f32 = f32::MAX / 2.;
1019
1020                let (a, b) = (self, other);
1021                let abs_a = a.abs();
1022                let abs_b = b.abs();
1023
1024                if abs_a <= HI && abs_b <= HI {
1025                    // Overflow is impossible
1026                    (a + b) / 2.
1027                } else if abs_a < LO {
1028                    // Not safe to halve `a` (would underflow)
1029                    a + (b / 2.)
1030                } else if abs_b < LO {
1031                    // Not safe to halve `b` (would underflow)
1032                    (a / 2.) + b
1033                } else {
1034                    // Safe to halve `a` and `b`
1035                    (a / 2.) + (b / 2.)
1036                }
1037            }
1038        }
1039    }
1040
1041    /// Rounds toward zero and converts to any primitive integer type,
1042    /// assuming that the value is finite and fits in that type.
1043    ///
1044    /// ```
1045    /// let value = 4.6_f32;
1046    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1047    /// assert_eq!(rounded, 4);
1048    ///
1049    /// let value = -128.9_f32;
1050    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1051    /// assert_eq!(rounded, i8::MIN);
1052    /// ```
1053    ///
1054    /// # Safety
1055    ///
1056    /// The value must:
1057    ///
1058    /// * Not be `NaN`
1059    /// * Not be infinite
1060    /// * Be representable in the return type `Int`, after truncating off its fractional part
1061    #[must_use = "this returns the result of the operation, \
1062                  without modifying the original"]
1063    #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
1064    #[inline]
1065    pub unsafe fn to_int_unchecked<Int>(self) -> Int
1066    where
1067        Self: FloatToInt<Int>,
1068    {
1069        // SAFETY: the caller must uphold the safety contract for
1070        // `FloatToInt::to_int_unchecked`.
1071        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1072    }
1073
1074    /// Raw transmutation to `u32`.
1075    ///
1076    /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
1077    ///
1078    /// See [`from_bits`](Self::from_bits) for some discussion of the
1079    /// portability of this operation (there are almost no issues).
1080    ///
1081    /// Note that this function is distinct from `as` casting, which attempts to
1082    /// preserve the *numeric* value, and not the bitwise value.
1083    ///
1084    /// # Examples
1085    ///
1086    /// ```
1087    /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
1088    /// assert_eq!((12.5f32).to_bits(), 0x41480000);
1089    ///
1090    /// ```
1091    #[must_use = "this returns the result of the operation, \
1092                  without modifying the original"]
1093    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1094    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1095    #[inline]
1096    pub const fn to_bits(self) -> u32 {
1097        // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1098        unsafe { mem::transmute(self) }
1099    }
1100
1101    /// Raw transmutation from `u32`.
1102    ///
1103    /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1104    /// It turns out this is incredibly portable, for two reasons:
1105    ///
1106    /// * Floats and Ints have the same endianness on all supported platforms.
1107    /// * IEEE 754 very precisely specifies the bit layout of floats.
1108    ///
1109    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1110    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1111    /// (notably x86 and ARM) picked the interpretation that was ultimately
1112    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1113    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1114    ///
1115    /// Rather than trying to preserve signaling-ness cross-platform, this
1116    /// implementation favors preserving the exact bits. This means that
1117    /// any payloads encoded in NaNs will be preserved even if the result of
1118    /// this method is sent over the network from an x86 machine to a MIPS one.
1119    ///
1120    /// If the results of this method are only manipulated by the same
1121    /// architecture that produced them, then there is no portability concern.
1122    ///
1123    /// If the input isn't NaN, then there is no portability concern.
1124    ///
1125    /// If you don't care about signalingness (very likely), then there is no
1126    /// portability concern.
1127    ///
1128    /// Note that this function is distinct from `as` casting, which attempts to
1129    /// preserve the *numeric* value, and not the bitwise value.
1130    ///
1131    /// # Examples
1132    ///
1133    /// ```
1134    /// let v = f32::from_bits(0x41480000);
1135    /// assert_eq!(v, 12.5);
1136    /// ```
1137    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1138    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1139    #[must_use]
1140    #[inline]
1141    pub const fn from_bits(v: u32) -> Self {
1142        // It turns out the safety issues with sNaN were overblown! Hooray!
1143        // SAFETY: `u32` is a plain old datatype so we can always transmute from it.
1144        unsafe { mem::transmute(v) }
1145    }
1146
1147    /// Returns the memory representation of this floating point number as a byte array in
1148    /// big-endian (network) byte order.
1149    ///
1150    /// See [`from_bits`](Self::from_bits) for some discussion of the
1151    /// portability of this operation (there are almost no issues).
1152    ///
1153    /// # Examples
1154    ///
1155    /// ```
1156    /// let bytes = 12.5f32.to_be_bytes();
1157    /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1158    /// ```
1159    #[must_use = "this returns the result of the operation, \
1160                  without modifying the original"]
1161    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1162    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1163    #[inline]
1164    pub const fn to_be_bytes(self) -> [u8; 4] {
1165        self.to_bits().to_be_bytes()
1166    }
1167
1168    /// Returns the memory representation of this floating point number as a byte array in
1169    /// little-endian byte order.
1170    ///
1171    /// See [`from_bits`](Self::from_bits) for some discussion of the
1172    /// portability of this operation (there are almost no issues).
1173    ///
1174    /// # Examples
1175    ///
1176    /// ```
1177    /// let bytes = 12.5f32.to_le_bytes();
1178    /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1179    /// ```
1180    #[must_use = "this returns the result of the operation, \
1181                  without modifying the original"]
1182    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1183    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1184    #[inline]
1185    pub const fn to_le_bytes(self) -> [u8; 4] {
1186        self.to_bits().to_le_bytes()
1187    }
1188
1189    /// Returns the memory representation of this floating point number as a byte array in
1190    /// native byte order.
1191    ///
1192    /// As the target platform's native endianness is used, portable code
1193    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1194    ///
1195    /// [`to_be_bytes`]: f32::to_be_bytes
1196    /// [`to_le_bytes`]: f32::to_le_bytes
1197    ///
1198    /// See [`from_bits`](Self::from_bits) for some discussion of the
1199    /// portability of this operation (there are almost no issues).
1200    ///
1201    /// # Examples
1202    ///
1203    /// ```
1204    /// let bytes = 12.5f32.to_ne_bytes();
1205    /// assert_eq!(
1206    ///     bytes,
1207    ///     if cfg!(target_endian = "big") {
1208    ///         [0x41, 0x48, 0x00, 0x00]
1209    ///     } else {
1210    ///         [0x00, 0x00, 0x48, 0x41]
1211    ///     }
1212    /// );
1213    /// ```
1214    #[must_use = "this returns the result of the operation, \
1215                  without modifying the original"]
1216    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1217    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1218    #[inline]
1219    pub const fn to_ne_bytes(self) -> [u8; 4] {
1220        self.to_bits().to_ne_bytes()
1221    }
1222
1223    /// Creates a floating point value from its representation as a byte array in big endian.
1224    ///
1225    /// See [`from_bits`](Self::from_bits) for some discussion of the
1226    /// portability of this operation (there are almost no issues).
1227    ///
1228    /// # Examples
1229    ///
1230    /// ```
1231    /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1232    /// assert_eq!(value, 12.5);
1233    /// ```
1234    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1235    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1236    #[must_use]
1237    #[inline]
1238    pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1239        Self::from_bits(u32::from_be_bytes(bytes))
1240    }
1241
1242    /// Creates a floating point value from its representation as a byte array in little endian.
1243    ///
1244    /// See [`from_bits`](Self::from_bits) for some discussion of the
1245    /// portability of this operation (there are almost no issues).
1246    ///
1247    /// # Examples
1248    ///
1249    /// ```
1250    /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1251    /// assert_eq!(value, 12.5);
1252    /// ```
1253    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1254    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1255    #[must_use]
1256    #[inline]
1257    pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1258        Self::from_bits(u32::from_le_bytes(bytes))
1259    }
1260
1261    /// Creates a floating point value from its representation as a byte array in native endian.
1262    ///
1263    /// As the target platform's native endianness is used, portable code
1264    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1265    /// appropriate instead.
1266    ///
1267    /// [`from_be_bytes`]: f32::from_be_bytes
1268    /// [`from_le_bytes`]: f32::from_le_bytes
1269    ///
1270    /// See [`from_bits`](Self::from_bits) for some discussion of the
1271    /// portability of this operation (there are almost no issues).
1272    ///
1273    /// # Examples
1274    ///
1275    /// ```
1276    /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1277    ///     [0x41, 0x48, 0x00, 0x00]
1278    /// } else {
1279    ///     [0x00, 0x00, 0x48, 0x41]
1280    /// });
1281    /// assert_eq!(value, 12.5);
1282    /// ```
1283    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1284    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1285    #[must_use]
1286    #[inline]
1287    pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1288        Self::from_bits(u32::from_ne_bytes(bytes))
1289    }
1290
1291    /// Returns the ordering between `self` and `other`.
1292    ///
1293    /// Unlike the standard partial comparison between floating point numbers,
1294    /// this comparison always produces an ordering in accordance to
1295    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1296    /// floating point standard. The values are ordered in the following sequence:
1297    ///
1298    /// - negative quiet NaN
1299    /// - negative signaling NaN
1300    /// - negative infinity
1301    /// - negative numbers
1302    /// - negative subnormal numbers
1303    /// - negative zero
1304    /// - positive zero
1305    /// - positive subnormal numbers
1306    /// - positive numbers
1307    /// - positive infinity
1308    /// - positive signaling NaN
1309    /// - positive quiet NaN.
1310    ///
1311    /// The ordering established by this function does not always agree with the
1312    /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1313    /// they consider negative and positive zero equal, while `total_cmp`
1314    /// doesn't.
1315    ///
1316    /// The interpretation of the signaling NaN bit follows the definition in
1317    /// the IEEE 754 standard, which may not match the interpretation by some of
1318    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1319    ///
1320    /// # Example
1321    ///
1322    /// ```
1323    /// struct GoodBoy {
1324    ///     name: String,
1325    ///     weight: f32,
1326    /// }
1327    ///
1328    /// let mut bois = vec![
1329    ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1330    ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1331    ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1332    ///     GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1333    ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1334    ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1335    /// ];
1336    ///
1337    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1338    ///
1339    /// // `f32::NAN` could be positive or negative, which will affect the sort order.
1340    /// if f32::NAN.is_sign_negative() {
1341    ///     assert!(bois.into_iter().map(|b| b.weight)
1342    ///         .zip([f32::NAN, -5.0, 0.1, 10.0, 99.0, f32::INFINITY].iter())
1343    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1344    /// } else {
1345    ///     assert!(bois.into_iter().map(|b| b.weight)
1346    ///         .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1347    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1348    /// }
1349    /// ```
1350    #[stable(feature = "total_cmp", since = "1.62.0")]
1351    #[must_use]
1352    #[inline]
1353    pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1354        let mut left = self.to_bits() as i32;
1355        let mut right = other.to_bits() as i32;
1356
1357        // In case of negatives, flip all the bits except the sign
1358        // to achieve a similar layout as two's complement integers
1359        //
1360        // Why does this work? IEEE 754 floats consist of three fields:
1361        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1362        // fields as a whole have the property that their bitwise order is
1363        // equal to the numeric magnitude where the magnitude is defined.
1364        // The magnitude is not normally defined on NaN values, but
1365        // IEEE 754 totalOrder defines the NaN values also to follow the
1366        // bitwise order. This leads to order explained in the doc comment.
1367        // However, the representation of magnitude is the same for negative
1368        // and positive numbers – only the sign bit is different.
1369        // To easily compare the floats as signed integers, we need to
1370        // flip the exponent and mantissa bits in case of negative numbers.
1371        // We effectively convert the numbers to "two's complement" form.
1372        //
1373        // To do the flipping, we construct a mask and XOR against it.
1374        // We branchlessly calculate an "all-ones except for the sign bit"
1375        // mask from negative-signed values: right shifting sign-extends
1376        // the integer, so we "fill" the mask with sign bits, and then
1377        // convert to unsigned to push one more zero bit.
1378        // On positive values, the mask is all zeros, so it's a no-op.
1379        left ^= (((left >> 31) as u32) >> 1) as i32;
1380        right ^= (((right >> 31) as u32) >> 1) as i32;
1381
1382        left.cmp(&right)
1383    }
1384
1385    /// Restrict a value to a certain interval unless it is NaN.
1386    ///
1387    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1388    /// less than `min`. Otherwise this returns `self`.
1389    ///
1390    /// Note that this function returns NaN if the initial value was NaN as
1391    /// well.
1392    ///
1393    /// # Panics
1394    ///
1395    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1396    ///
1397    /// # Examples
1398    ///
1399    /// ```
1400    /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1401    /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1402    /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1403    /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1404    /// ```
1405    #[must_use = "method returns a new number and does not mutate the original value"]
1406    #[stable(feature = "clamp", since = "1.50.0")]
1407    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1408    #[inline]
1409    pub const fn clamp(mut self, min: f32, max: f32) -> f32 {
1410        const_assert!(
1411            min <= max,
1412            "min > max, or either was NaN",
1413            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1414            min: f32,
1415            max: f32,
1416        );
1417
1418        if self < min {
1419            self = min;
1420        }
1421        if self > max {
1422            self = max;
1423        }
1424        self
1425    }
1426
1427    /// Computes the absolute value of `self`.
1428    ///
1429    /// This function always returns the precise result.
1430    ///
1431    /// # Examples
1432    ///
1433    /// ```
1434    /// let x = 3.5_f32;
1435    /// let y = -3.5_f32;
1436    ///
1437    /// assert_eq!(x.abs(), x);
1438    /// assert_eq!(y.abs(), -y);
1439    ///
1440    /// assert!(f32::NAN.abs().is_nan());
1441    /// ```
1442    #[must_use = "method returns a new number and does not mutate the original value"]
1443    #[stable(feature = "rust1", since = "1.0.0")]
1444    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1445    #[inline]
1446    pub const fn abs(self) -> f32 {
1447        // SAFETY: this is actually a safe intrinsic
1448        unsafe { intrinsics::fabsf32(self) }
1449    }
1450
1451    /// Returns a number that represents the sign of `self`.
1452    ///
1453    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1454    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1455    /// - NaN if the number is NaN
1456    ///
1457    /// # Examples
1458    ///
1459    /// ```
1460    /// let f = 3.5_f32;
1461    ///
1462    /// assert_eq!(f.signum(), 1.0);
1463    /// assert_eq!(f32::NEG_INFINITY.signum(), -1.0);
1464    ///
1465    /// assert!(f32::NAN.signum().is_nan());
1466    /// ```
1467    #[must_use = "method returns a new number and does not mutate the original value"]
1468    #[stable(feature = "rust1", since = "1.0.0")]
1469    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1470    #[inline]
1471    pub const fn signum(self) -> f32 {
1472        if self.is_nan() { Self::NAN } else { 1.0_f32.copysign(self) }
1473    }
1474
1475    /// Returns a number composed of the magnitude of `self` and the sign of
1476    /// `sign`.
1477    ///
1478    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1479    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1480    /// returned.
1481    ///
1482    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1483    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1484    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1485    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1486    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1487    /// info.
1488    ///
1489    /// # Examples
1490    ///
1491    /// ```
1492    /// let f = 3.5_f32;
1493    ///
1494    /// assert_eq!(f.copysign(0.42), 3.5_f32);
1495    /// assert_eq!(f.copysign(-0.42), -3.5_f32);
1496    /// assert_eq!((-f).copysign(0.42), 3.5_f32);
1497    /// assert_eq!((-f).copysign(-0.42), -3.5_f32);
1498    ///
1499    /// assert!(f32::NAN.copysign(1.0).is_nan());
1500    /// ```
1501    #[must_use = "method returns a new number and does not mutate the original value"]
1502    #[inline]
1503    #[stable(feature = "copysign", since = "1.35.0")]
1504    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1505    pub const fn copysign(self, sign: f32) -> f32 {
1506        // SAFETY: this is actually a safe intrinsic
1507        unsafe { intrinsics::copysignf32(self, sign) }
1508    }
1509
1510    /// Float addition that allows optimizations based on algebraic rules.
1511    ///
1512    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1513    #[must_use = "method returns a new number and does not mutate the original value"]
1514    #[unstable(feature = "float_algebraic", issue = "136469")]
1515    #[inline]
1516    pub fn algebraic_add(self, rhs: f32) -> f32 {
1517        intrinsics::fadd_algebraic(self, rhs)
1518    }
1519
1520    /// Float subtraction that allows optimizations based on algebraic rules.
1521    ///
1522    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1523    #[must_use = "method returns a new number and does not mutate the original value"]
1524    #[unstable(feature = "float_algebraic", issue = "136469")]
1525    #[inline]
1526    pub fn algebraic_sub(self, rhs: f32) -> f32 {
1527        intrinsics::fsub_algebraic(self, rhs)
1528    }
1529
1530    /// Float multiplication that allows optimizations based on algebraic rules.
1531    ///
1532    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1533    #[must_use = "method returns a new number and does not mutate the original value"]
1534    #[unstable(feature = "float_algebraic", issue = "136469")]
1535    #[inline]
1536    pub fn algebraic_mul(self, rhs: f32) -> f32 {
1537        intrinsics::fmul_algebraic(self, rhs)
1538    }
1539
1540    /// Float division that allows optimizations based on algebraic rules.
1541    ///
1542    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1543    #[must_use = "method returns a new number and does not mutate the original value"]
1544    #[unstable(feature = "float_algebraic", issue = "136469")]
1545    #[inline]
1546    pub fn algebraic_div(self, rhs: f32) -> f32 {
1547        intrinsics::fdiv_algebraic(self, rhs)
1548    }
1549
1550    /// Float remainder that allows optimizations based on algebraic rules.
1551    ///
1552    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1553    #[must_use = "method returns a new number and does not mutate the original value"]
1554    #[unstable(feature = "float_algebraic", issue = "136469")]
1555    #[inline]
1556    pub fn algebraic_rem(self, rhs: f32) -> f32 {
1557        intrinsics::frem_algebraic(self, rhs)
1558    }
1559}