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