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_certified"))]
15use crate::convert::FloatToInt;
16#[cfg(not(feature = "ferrocene_certified"))]
17use crate::num::FpCategory;
18#[cfg(not(feature = "ferrocene_certified"))]
19use crate::panic::const_assert;
20#[cfg(not(feature = "ferrocene_certified"))]
21use crate::{cfg_select, intrinsics, mem};
22
23// Ferrocene addition: imports for certified subset
24#[cfg(feature = "ferrocene_certified")]
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_certified"))]
515    pub(crate) const SIGN_MASK: u32 = 0x8000_0000;
516
517    /// Exponent mask
518    #[cfg(not(feature = "ferrocene_certified"))]
519    pub(crate) const EXP_MASK: u32 = 0x7f80_0000;
520
521    /// Mantissa mask
522    #[cfg(not(feature = "ferrocene_certified"))]
523    pub(crate) const MAN_MASK: u32 = 0x007f_ffff;
524
525    /// Minimum representable positive value (min subnormal)
526    #[cfg(not(feature = "ferrocene_certified"))]
527    const TINY_BITS: u32 = 0x1;
528
529    /// Minimum representable negative value (min negative subnormal)
530    #[cfg(not(feature = "ferrocene_certified"))]
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    #[cfg(not(feature = "ferrocene_certified"))]
571    pub const fn is_infinite(self) -> bool {
572        // Getting clever with transmutation can result in incorrect answers on some FPUs
573        // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
574        // See https://github.com/rust-lang/rust/issues/72327
575        (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
576    }
577
578    /// Returns `true` if this number is neither infinite nor NaN.
579    ///
580    /// ```
581    /// let f = 7.0f32;
582    /// let inf = f32::INFINITY;
583    /// let neg_inf = f32::NEG_INFINITY;
584    /// let nan = f32::NAN;
585    ///
586    /// assert!(f.is_finite());
587    ///
588    /// assert!(!nan.is_finite());
589    /// assert!(!inf.is_finite());
590    /// assert!(!neg_inf.is_finite());
591    /// ```
592    #[must_use]
593    #[stable(feature = "rust1", since = "1.0.0")]
594    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
595    #[inline]
596    #[cfg(not(feature = "ferrocene_certified"))]
597    pub const fn is_finite(self) -> bool {
598        // There's no need to handle NaN separately: if self is NaN,
599        // the comparison is not true, exactly as desired.
600        self.abs() < Self::INFINITY
601    }
602
603    /// Returns `true` if the number is [subnormal].
604    ///
605    /// ```
606    /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
607    /// let max = f32::MAX;
608    /// let lower_than_min = 1.0e-40_f32;
609    /// let zero = 0.0_f32;
610    ///
611    /// assert!(!min.is_subnormal());
612    /// assert!(!max.is_subnormal());
613    ///
614    /// assert!(!zero.is_subnormal());
615    /// assert!(!f32::NAN.is_subnormal());
616    /// assert!(!f32::INFINITY.is_subnormal());
617    /// // Values between `0` and `min` are Subnormal.
618    /// assert!(lower_than_min.is_subnormal());
619    /// ```
620    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
621    #[must_use]
622    #[stable(feature = "is_subnormal", since = "1.53.0")]
623    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
624    #[inline]
625    #[cfg(not(feature = "ferrocene_certified"))]
626    pub const fn is_subnormal(self) -> bool {
627        matches!(self.classify(), FpCategory::Subnormal)
628    }
629
630    /// Returns `true` if the number is neither zero, infinite,
631    /// [subnormal], or NaN.
632    ///
633    /// ```
634    /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
635    /// let max = f32::MAX;
636    /// let lower_than_min = 1.0e-40_f32;
637    /// let zero = 0.0_f32;
638    ///
639    /// assert!(min.is_normal());
640    /// assert!(max.is_normal());
641    ///
642    /// assert!(!zero.is_normal());
643    /// assert!(!f32::NAN.is_normal());
644    /// assert!(!f32::INFINITY.is_normal());
645    /// // Values between `0` and `min` are Subnormal.
646    /// assert!(!lower_than_min.is_normal());
647    /// ```
648    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
649    #[must_use]
650    #[stable(feature = "rust1", since = "1.0.0")]
651    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
652    #[inline]
653    #[cfg(not(feature = "ferrocene_certified"))]
654    pub const fn is_normal(self) -> bool {
655        matches!(self.classify(), FpCategory::Normal)
656    }
657
658    /// Returns the floating point category of the number. If only one property
659    /// is going to be tested, it is generally faster to use the specific
660    /// predicate instead.
661    ///
662    /// ```
663    /// use std::num::FpCategory;
664    ///
665    /// let num = 12.4_f32;
666    /// let inf = f32::INFINITY;
667    ///
668    /// assert_eq!(num.classify(), FpCategory::Normal);
669    /// assert_eq!(inf.classify(), FpCategory::Infinite);
670    /// ```
671    #[stable(feature = "rust1", since = "1.0.0")]
672    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
673    #[cfg(not(feature = "ferrocene_certified"))]
674    pub const fn classify(self) -> FpCategory {
675        // We used to have complicated logic here that avoids the simple bit-based tests to work
676        // around buggy codegen for x87 targets (see
677        // https://github.com/rust-lang/rust/issues/114479). However, some LLVM versions later, none
678        // of our tests is able to find any difference between the complicated and the naive
679        // version, so now we are back to the naive version.
680        let b = self.to_bits();
681        match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
682            (0, Self::EXP_MASK) => FpCategory::Infinite,
683            (_, Self::EXP_MASK) => FpCategory::Nan,
684            (0, 0) => FpCategory::Zero,
685            (_, 0) => FpCategory::Subnormal,
686            _ => FpCategory::Normal,
687        }
688    }
689
690    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
691    /// positive sign bit and positive infinity.
692    ///
693    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
694    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
695    /// conserved over arithmetic operations, the result of `is_sign_positive` on
696    /// a NaN might produce an unexpected or non-portable result. See the [specification
697    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
698    /// if you need fully portable behavior (will return `false` for all NaNs).
699    ///
700    /// ```
701    /// let f = 7.0_f32;
702    /// let g = -7.0_f32;
703    ///
704    /// assert!(f.is_sign_positive());
705    /// assert!(!g.is_sign_positive());
706    /// ```
707    #[must_use]
708    #[stable(feature = "rust1", since = "1.0.0")]
709    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
710    #[inline]
711    #[cfg(not(feature = "ferrocene_certified"))]
712    pub const fn is_sign_positive(self) -> bool {
713        !self.is_sign_negative()
714    }
715
716    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
717    /// negative sign bit and negative infinity.
718    ///
719    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
720    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
721    /// conserved over arithmetic operations, the result of `is_sign_negative` on
722    /// a NaN might produce an unexpected or non-portable result. See the [specification
723    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
724    /// if you need fully portable behavior (will return `false` for all NaNs).
725    ///
726    /// ```
727    /// let f = 7.0f32;
728    /// let g = -7.0f32;
729    ///
730    /// assert!(!f.is_sign_negative());
731    /// assert!(g.is_sign_negative());
732    /// ```
733    #[must_use]
734    #[stable(feature = "rust1", since = "1.0.0")]
735    #[rustc_const_stable(feature = "const_float_classify", since = "1.83.0")]
736    #[inline]
737    #[cfg(not(feature = "ferrocene_certified"))]
738    pub const fn is_sign_negative(self) -> bool {
739        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
740        // applies to zeros and NaNs as well.
741        self.to_bits() & 0x8000_0000 != 0
742    }
743
744    /// Returns the least number greater than `self`.
745    ///
746    /// Let `TINY` be the smallest representable positive `f32`. Then,
747    ///  - if `self.is_nan()`, this returns `self`;
748    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
749    ///  - if `self` is `-TINY`, this returns -0.0;
750    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
751    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
752    ///  - otherwise the unique least value greater than `self` is returned.
753    ///
754    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
755    /// is finite `x == x.next_up().next_down()` also holds.
756    ///
757    /// ```rust
758    /// // f32::EPSILON is the difference between 1.0 and the next number up.
759    /// assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
760    /// // But not for most numbers.
761    /// assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
762    /// assert_eq!(16777216f32.next_up(), 16777218.0);
763    /// ```
764    ///
765    /// This operation corresponds to IEEE-754 `nextUp`.
766    ///
767    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
768    /// [`INFINITY`]: Self::INFINITY
769    /// [`MIN`]: Self::MIN
770    /// [`MAX`]: Self::MAX
771    #[inline]
772    #[doc(alias = "nextUp")]
773    #[stable(feature = "float_next_up_down", since = "1.86.0")]
774    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
775    #[cfg(not(feature = "ferrocene_certified"))]
776    pub const fn next_up(self) -> Self {
777        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
778        // denormals to zero. This is in general unsound and unsupported, but here
779        // we do our best to still produce the correct result on such targets.
780        let bits = self.to_bits();
781        if self.is_nan() || bits == Self::INFINITY.to_bits() {
782            return self;
783        }
784
785        let abs = bits & !Self::SIGN_MASK;
786        let next_bits = if abs == 0 {
787            Self::TINY_BITS
788        } else if bits == abs {
789            bits + 1
790        } else {
791            bits - 1
792        };
793        Self::from_bits(next_bits)
794    }
795
796    /// Returns the greatest number less than `self`.
797    ///
798    /// Let `TINY` be the smallest representable positive `f32`. Then,
799    ///  - if `self.is_nan()`, this returns `self`;
800    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
801    ///  - if `self` is `TINY`, this returns 0.0;
802    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
803    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
804    ///  - otherwise the unique greatest value less than `self` is returned.
805    ///
806    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
807    /// is finite `x == x.next_down().next_up()` also holds.
808    ///
809    /// ```rust
810    /// let x = 1.0f32;
811    /// // Clamp value into range [0, 1).
812    /// let clamped = x.clamp(0.0, 1.0f32.next_down());
813    /// assert!(clamped < 1.0);
814    /// assert_eq!(clamped.next_up(), 1.0);
815    /// ```
816    ///
817    /// This operation corresponds to IEEE-754 `nextDown`.
818    ///
819    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
820    /// [`INFINITY`]: Self::INFINITY
821    /// [`MIN`]: Self::MIN
822    /// [`MAX`]: Self::MAX
823    #[inline]
824    #[doc(alias = "nextDown")]
825    #[stable(feature = "float_next_up_down", since = "1.86.0")]
826    #[rustc_const_stable(feature = "float_next_up_down", since = "1.86.0")]
827    #[cfg(not(feature = "ferrocene_certified"))]
828    pub const fn next_down(self) -> Self {
829        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
830        // denormals to zero. This is in general unsound and unsupported, but here
831        // we do our best to still produce the correct result on such targets.
832        let bits = self.to_bits();
833        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
834            return self;
835        }
836
837        let abs = bits & !Self::SIGN_MASK;
838        let next_bits = if abs == 0 {
839            Self::NEG_TINY_BITS
840        } else if bits == abs {
841            bits - 1
842        } else {
843            bits + 1
844        };
845        Self::from_bits(next_bits)
846    }
847
848    /// Takes the reciprocal (inverse) of a number, `1/x`.
849    ///
850    /// ```
851    /// let x = 2.0_f32;
852    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
853    ///
854    /// assert!(abs_difference <= f32::EPSILON);
855    /// ```
856    #[must_use = "this returns the result of the operation, without modifying the original"]
857    #[stable(feature = "rust1", since = "1.0.0")]
858    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
859    #[inline]
860    #[cfg(not(feature = "ferrocene_certified"))]
861    pub const fn recip(self) -> f32 {
862        1.0 / self
863    }
864
865    /// Converts radians to degrees.
866    ///
867    /// # Unspecified precision
868    ///
869    /// The precision of this function is non-deterministic. This means it varies by platform,
870    /// Rust version, and can even differ within the same execution from one invocation to the next.
871    ///
872    /// # Examples
873    ///
874    /// ```
875    /// let angle = std::f32::consts::PI;
876    ///
877    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
878    /// # #[cfg(any(not(target_arch = "x86"), target_feature = "sse2"))]
879    /// assert!(abs_difference <= f32::EPSILON);
880    /// ```
881    #[must_use = "this returns the result of the operation, \
882                  without modifying the original"]
883    #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
884    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
885    #[inline]
886    #[cfg(not(feature = "ferrocene_certified"))]
887    pub const fn to_degrees(self) -> f32 {
888        // Use a literal to avoid double rounding, consts::PI is already rounded,
889        // and dividing would round again.
890        const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
891        self * PIS_IN_180
892    }
893
894    /// Converts degrees to radians.
895    ///
896    /// # Unspecified precision
897    ///
898    /// The precision of this function is non-deterministic. This means it varies by platform,
899    /// Rust version, and can even differ within the same execution from one invocation to the next.
900    ///
901    /// # Examples
902    ///
903    /// ```
904    /// let angle = 180.0f32;
905    ///
906    /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
907    ///
908    /// assert!(abs_difference <= f32::EPSILON);
909    /// ```
910    #[must_use = "this returns the result of the operation, \
911                  without modifying the original"]
912    #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
913    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
914    #[inline]
915    #[cfg(not(feature = "ferrocene_certified"))]
916    pub const fn to_radians(self) -> f32 {
917        // The division here is correctly rounded with respect to the true value of π/180.
918        // Although π is irrational and already rounded, the double rounding happens
919        // to produce correct result for f32.
920        const RADS_PER_DEG: f32 = consts::PI / 180.0;
921        self * RADS_PER_DEG
922    }
923
924    /// Returns the maximum of the two numbers, ignoring NaN.
925    ///
926    /// If one of the arguments is NaN, then the other argument is returned.
927    /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
928    /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
929    /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
930    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
931    ///
932    /// ```
933    /// let x = 1.0f32;
934    /// let y = 2.0f32;
935    ///
936    /// assert_eq!(x.max(y), y);
937    /// ```
938    #[must_use = "this returns the result of the comparison, without modifying either input"]
939    #[stable(feature = "rust1", since = "1.0.0")]
940    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
941    #[inline]
942    pub const fn max(self, other: f32) -> f32 {
943        intrinsics::maxnumf32(self, other)
944    }
945
946    /// Returns the minimum of the two numbers, ignoring NaN.
947    ///
948    /// If one of the arguments is NaN, then the other argument is returned.
949    /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
950    /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
951    /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
952    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
953    ///
954    /// ```
955    /// let x = 1.0f32;
956    /// let y = 2.0f32;
957    ///
958    /// assert_eq!(x.min(y), x);
959    /// ```
960    #[must_use = "this returns the result of the comparison, without modifying either input"]
961    #[stable(feature = "rust1", since = "1.0.0")]
962    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
963    #[inline]
964    pub const fn min(self, other: f32) -> f32 {
965        intrinsics::minnumf32(self, other)
966    }
967
968    /// Returns the maximum of the two numbers, propagating NaN.
969    ///
970    /// This returns NaN when *either* argument is NaN, as opposed to
971    /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
972    ///
973    /// ```
974    /// #![feature(float_minimum_maximum)]
975    /// let x = 1.0f32;
976    /// let y = 2.0f32;
977    ///
978    /// assert_eq!(x.maximum(y), y);
979    /// assert!(x.maximum(f32::NAN).is_nan());
980    /// ```
981    ///
982    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
983    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
984    /// Note that this follows the semantics specified in IEEE 754-2019.
985    ///
986    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
987    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
988    #[must_use = "this returns the result of the comparison, without modifying either input"]
989    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
990    #[inline]
991    #[cfg(not(feature = "ferrocene_certified"))]
992    pub const fn maximum(self, other: f32) -> f32 {
993        intrinsics::maximumf32(self, other)
994    }
995
996    /// Returns the minimum of the two numbers, propagating NaN.
997    ///
998    /// This returns NaN when *either* argument is NaN, as opposed to
999    /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
1000    ///
1001    /// ```
1002    /// #![feature(float_minimum_maximum)]
1003    /// let x = 1.0f32;
1004    /// let y = 2.0f32;
1005    ///
1006    /// assert_eq!(x.minimum(y), x);
1007    /// assert!(x.minimum(f32::NAN).is_nan());
1008    /// ```
1009    ///
1010    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
1011    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
1012    /// Note that this follows the semantics specified in IEEE 754-2019.
1013    ///
1014    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
1015    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
1016    #[must_use = "this returns the result of the comparison, without modifying either input"]
1017    #[unstable(feature = "float_minimum_maximum", issue = "91079")]
1018    #[inline]
1019    #[cfg(not(feature = "ferrocene_certified"))]
1020    pub const fn minimum(self, other: f32) -> f32 {
1021        intrinsics::minimumf32(self, other)
1022    }
1023
1024    /// Calculates the midpoint (average) between `self` and `rhs`.
1025    ///
1026    /// This returns NaN when *either* argument is NaN or if a combination of
1027    /// +inf and -inf is provided as arguments.
1028    ///
1029    /// # Examples
1030    ///
1031    /// ```
1032    /// assert_eq!(1f32.midpoint(4.0), 2.5);
1033    /// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
1034    /// ```
1035    #[inline]
1036    #[doc(alias = "average")]
1037    #[stable(feature = "num_midpoint", since = "1.85.0")]
1038    #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
1039    #[cfg(not(feature = "ferrocene_certified"))]
1040    pub const fn midpoint(self, other: f32) -> f32 {
1041        cfg_select! {
1042            // Allow faster implementation that have known good 64-bit float
1043            // implementations. Falling back to the branchy code on targets that don't
1044            // have 64-bit hardware floats or buggy implementations.
1045            // https://github.com/rust-lang/rust/pull/121062#issuecomment-2123408114
1046            any(
1047                target_arch = "x86_64",
1048                target_arch = "aarch64",
1049                all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "d"),
1050                all(target_arch = "loongarch64", target_feature = "d"),
1051                all(target_arch = "arm", target_feature = "vfp2"),
1052                target_arch = "wasm32",
1053                target_arch = "wasm64",
1054            ) => {
1055                ((self as f64 + other as f64) / 2.0) as f32
1056            }
1057            _ => {
1058                const HI: f32 = f32::MAX / 2.;
1059
1060                let (a, b) = (self, other);
1061                let abs_a = a.abs();
1062                let abs_b = b.abs();
1063
1064                if abs_a <= HI && abs_b <= HI {
1065                    // Overflow is impossible
1066                    (a + b) / 2.
1067                } else {
1068                    (a / 2.) + (b / 2.)
1069                }
1070            }
1071        }
1072    }
1073
1074    /// Rounds toward zero and converts to any primitive integer type,
1075    /// assuming that the value is finite and fits in that type.
1076    ///
1077    /// ```
1078    /// let value = 4.6_f32;
1079    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1080    /// assert_eq!(rounded, 4);
1081    ///
1082    /// let value = -128.9_f32;
1083    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1084    /// assert_eq!(rounded, i8::MIN);
1085    /// ```
1086    ///
1087    /// # Safety
1088    ///
1089    /// The value must:
1090    ///
1091    /// * Not be `NaN`
1092    /// * Not be infinite
1093    /// * Be representable in the return type `Int`, after truncating off its fractional part
1094    #[must_use = "this returns the result of the operation, \
1095                  without modifying the original"]
1096    #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
1097    #[inline]
1098    #[cfg(not(feature = "ferrocene_certified"))]
1099    pub unsafe fn to_int_unchecked<Int>(self) -> Int
1100    where
1101        Self: FloatToInt<Int>,
1102    {
1103        // SAFETY: the caller must uphold the safety contract for
1104        // `FloatToInt::to_int_unchecked`.
1105        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1106    }
1107
1108    /// Raw transmutation to `u32`.
1109    ///
1110    /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
1111    ///
1112    /// See [`from_bits`](Self::from_bits) for some discussion of the
1113    /// portability of this operation (there are almost no issues).
1114    ///
1115    /// Note that this function is distinct from `as` casting, which attempts to
1116    /// preserve the *numeric* value, and not the bitwise value.
1117    ///
1118    /// # Examples
1119    ///
1120    /// ```
1121    /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
1122    /// assert_eq!((12.5f32).to_bits(), 0x41480000);
1123    ///
1124    /// ```
1125    #[must_use = "this returns the result of the operation, \
1126                  without modifying the original"]
1127    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1128    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1129    #[inline]
1130    #[allow(unnecessary_transmutes)]
1131    pub const fn to_bits(self) -> u32 {
1132        // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1133        unsafe { mem::transmute(self) }
1134    }
1135
1136    /// Raw transmutation from `u32`.
1137    ///
1138    /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1139    /// It turns out this is incredibly portable, for two reasons:
1140    ///
1141    /// * Floats and Ints have the same endianness on all supported platforms.
1142    /// * IEEE 754 very precisely specifies the bit layout of floats.
1143    ///
1144    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1145    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1146    /// (notably x86 and ARM) picked the interpretation that was ultimately
1147    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1148    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1149    ///
1150    /// Rather than trying to preserve signaling-ness cross-platform, this
1151    /// implementation favors preserving the exact bits. This means that
1152    /// any payloads encoded in NaNs will be preserved even if the result of
1153    /// this method is sent over the network from an x86 machine to a MIPS one.
1154    ///
1155    /// If the results of this method are only manipulated by the same
1156    /// architecture that produced them, then there is no portability concern.
1157    ///
1158    /// If the input isn't NaN, then there is no portability concern.
1159    ///
1160    /// If you don't care about signalingness (very likely), then there is no
1161    /// portability concern.
1162    ///
1163    /// Note that this function is distinct from `as` casting, which attempts to
1164    /// preserve the *numeric* value, and not the bitwise value.
1165    ///
1166    /// # Examples
1167    ///
1168    /// ```
1169    /// let v = f32::from_bits(0x41480000);
1170    /// assert_eq!(v, 12.5);
1171    /// ```
1172    #[stable(feature = "float_bits_conv", since = "1.20.0")]
1173    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1174    #[must_use]
1175    #[inline]
1176    #[allow(unnecessary_transmutes)]
1177    pub const fn from_bits(v: u32) -> Self {
1178        // It turns out the safety issues with sNaN were overblown! Hooray!
1179        // SAFETY: `u32` is a plain old datatype so we can always transmute from it.
1180        unsafe { mem::transmute(v) }
1181    }
1182
1183    /// Returns the memory representation of this floating point number as a byte array in
1184    /// big-endian (network) byte order.
1185    ///
1186    /// See [`from_bits`](Self::from_bits) for some discussion of the
1187    /// portability of this operation (there are almost no issues).
1188    ///
1189    /// # Examples
1190    ///
1191    /// ```
1192    /// let bytes = 12.5f32.to_be_bytes();
1193    /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1194    /// ```
1195    #[must_use = "this returns the result of the operation, \
1196                  without modifying the original"]
1197    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1198    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1199    #[inline]
1200    #[cfg(not(feature = "ferrocene_certified"))]
1201    pub const fn to_be_bytes(self) -> [u8; 4] {
1202        self.to_bits().to_be_bytes()
1203    }
1204
1205    /// Returns the memory representation of this floating point number as a byte array in
1206    /// little-endian byte order.
1207    ///
1208    /// See [`from_bits`](Self::from_bits) for some discussion of the
1209    /// portability of this operation (there are almost no issues).
1210    ///
1211    /// # Examples
1212    ///
1213    /// ```
1214    /// let bytes = 12.5f32.to_le_bytes();
1215    /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1216    /// ```
1217    #[must_use = "this returns the result of the operation, \
1218                  without modifying the original"]
1219    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1220    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1221    #[inline]
1222    pub const fn to_le_bytes(self) -> [u8; 4] {
1223        self.to_bits().to_le_bytes()
1224    }
1225
1226    /// Returns the memory representation of this floating point number as a byte array in
1227    /// native byte order.
1228    ///
1229    /// As the target platform's native endianness is used, portable code
1230    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1231    ///
1232    /// [`to_be_bytes`]: f32::to_be_bytes
1233    /// [`to_le_bytes`]: f32::to_le_bytes
1234    ///
1235    /// See [`from_bits`](Self::from_bits) for some discussion of the
1236    /// portability of this operation (there are almost no issues).
1237    ///
1238    /// # Examples
1239    ///
1240    /// ```
1241    /// let bytes = 12.5f32.to_ne_bytes();
1242    /// assert_eq!(
1243    ///     bytes,
1244    ///     if cfg!(target_endian = "big") {
1245    ///         [0x41, 0x48, 0x00, 0x00]
1246    ///     } else {
1247    ///         [0x00, 0x00, 0x48, 0x41]
1248    ///     }
1249    /// );
1250    /// ```
1251    #[must_use = "this returns the result of the operation, \
1252                  without modifying the original"]
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    #[inline]
1256    #[cfg(not(feature = "ferrocene_certified"))]
1257    pub const fn to_ne_bytes(self) -> [u8; 4] {
1258        self.to_bits().to_ne_bytes()
1259    }
1260
1261    /// Creates a floating point value from its representation as a byte array in big endian.
1262    ///
1263    /// See [`from_bits`](Self::from_bits) for some discussion of the
1264    /// portability of this operation (there are almost no issues).
1265    ///
1266    /// # Examples
1267    ///
1268    /// ```
1269    /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1270    /// assert_eq!(value, 12.5);
1271    /// ```
1272    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1273    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1274    #[must_use]
1275    #[inline]
1276    #[cfg(not(feature = "ferrocene_certified"))]
1277    pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1278        Self::from_bits(u32::from_be_bytes(bytes))
1279    }
1280
1281    /// Creates a floating point value from its representation as a byte array in little endian.
1282    ///
1283    /// See [`from_bits`](Self::from_bits) for some discussion of the
1284    /// portability of this operation (there are almost no issues).
1285    ///
1286    /// # Examples
1287    ///
1288    /// ```
1289    /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1290    /// assert_eq!(value, 12.5);
1291    /// ```
1292    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1293    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1294    #[must_use]
1295    #[inline]
1296    pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1297        Self::from_bits(u32::from_le_bytes(bytes))
1298    }
1299
1300    /// Creates a floating point value from its representation as a byte array in native endian.
1301    ///
1302    /// As the target platform's native endianness is used, portable code
1303    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1304    /// appropriate instead.
1305    ///
1306    /// [`from_be_bytes`]: f32::from_be_bytes
1307    /// [`from_le_bytes`]: f32::from_le_bytes
1308    ///
1309    /// See [`from_bits`](Self::from_bits) for some discussion of the
1310    /// portability of this operation (there are almost no issues).
1311    ///
1312    /// # Examples
1313    ///
1314    /// ```
1315    /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1316    ///     [0x41, 0x48, 0x00, 0x00]
1317    /// } else {
1318    ///     [0x00, 0x00, 0x48, 0x41]
1319    /// });
1320    /// assert_eq!(value, 12.5);
1321    /// ```
1322    #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1323    #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1324    #[must_use]
1325    #[inline]
1326    #[cfg(not(feature = "ferrocene_certified"))]
1327    pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1328        Self::from_bits(u32::from_ne_bytes(bytes))
1329    }
1330
1331    /// Returns the ordering between `self` and `other`.
1332    ///
1333    /// Unlike the standard partial comparison between floating point numbers,
1334    /// this comparison always produces an ordering in accordance to
1335    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1336    /// floating point standard. The values are ordered in the following sequence:
1337    ///
1338    /// - negative quiet NaN
1339    /// - negative signaling NaN
1340    /// - negative infinity
1341    /// - negative numbers
1342    /// - negative subnormal numbers
1343    /// - negative zero
1344    /// - positive zero
1345    /// - positive subnormal numbers
1346    /// - positive numbers
1347    /// - positive infinity
1348    /// - positive signaling NaN
1349    /// - positive quiet NaN.
1350    ///
1351    /// The ordering established by this function does not always agree with the
1352    /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1353    /// they consider negative and positive zero equal, while `total_cmp`
1354    /// doesn't.
1355    ///
1356    /// The interpretation of the signaling NaN bit follows the definition in
1357    /// the IEEE 754 standard, which may not match the interpretation by some of
1358    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1359    ///
1360    /// # Example
1361    ///
1362    /// ```
1363    /// struct GoodBoy {
1364    ///     name: String,
1365    ///     weight: f32,
1366    /// }
1367    ///
1368    /// let mut bois = vec![
1369    ///     GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1370    ///     GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1371    ///     GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1372    ///     GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1373    ///     GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1374    ///     GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1375    /// ];
1376    ///
1377    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1378    ///
1379    /// // `f32::NAN` could be positive or negative, which will affect the sort order.
1380    /// if f32::NAN.is_sign_negative() {
1381    ///     assert!(bois.into_iter().map(|b| b.weight)
1382    ///         .zip([f32::NAN, -5.0, 0.1, 10.0, 99.0, f32::INFINITY].iter())
1383    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1384    /// } else {
1385    ///     assert!(bois.into_iter().map(|b| b.weight)
1386    ///         .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1387    ///         .all(|(a, b)| a.to_bits() == b.to_bits()))
1388    /// }
1389    /// ```
1390    #[stable(feature = "total_cmp", since = "1.62.0")]
1391    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1392    #[must_use]
1393    #[inline]
1394    #[cfg(not(feature = "ferrocene_certified"))]
1395    pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1396        let mut left = self.to_bits() as i32;
1397        let mut right = other.to_bits() as i32;
1398
1399        // In case of negatives, flip all the bits except the sign
1400        // to achieve a similar layout as two's complement integers
1401        //
1402        // Why does this work? IEEE 754 floats consist of three fields:
1403        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1404        // fields as a whole have the property that their bitwise order is
1405        // equal to the numeric magnitude where the magnitude is defined.
1406        // The magnitude is not normally defined on NaN values, but
1407        // IEEE 754 totalOrder defines the NaN values also to follow the
1408        // bitwise order. This leads to order explained in the doc comment.
1409        // However, the representation of magnitude is the same for negative
1410        // and positive numbers – only the sign bit is different.
1411        // To easily compare the floats as signed integers, we need to
1412        // flip the exponent and mantissa bits in case of negative numbers.
1413        // We effectively convert the numbers to "two's complement" form.
1414        //
1415        // To do the flipping, we construct a mask and XOR against it.
1416        // We branchlessly calculate an "all-ones except for the sign bit"
1417        // mask from negative-signed values: right shifting sign-extends
1418        // the integer, so we "fill" the mask with sign bits, and then
1419        // convert to unsigned to push one more zero bit.
1420        // On positive values, the mask is all zeros, so it's a no-op.
1421        left ^= (((left >> 31) as u32) >> 1) as i32;
1422        right ^= (((right >> 31) as u32) >> 1) as i32;
1423
1424        left.cmp(&right)
1425    }
1426
1427    /// Restrict a value to a certain interval unless it is NaN.
1428    ///
1429    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1430    /// less than `min`. Otherwise this returns `self`.
1431    ///
1432    /// Note that this function returns NaN if the initial value was NaN as
1433    /// well.
1434    ///
1435    /// # Panics
1436    ///
1437    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1438    ///
1439    /// # Examples
1440    ///
1441    /// ```
1442    /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1443    /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1444    /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1445    /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1446    /// ```
1447    #[must_use = "method returns a new number and does not mutate the original value"]
1448    #[stable(feature = "clamp", since = "1.50.0")]
1449    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1450    #[inline]
1451    #[cfg(not(feature = "ferrocene_certified"))]
1452    pub const fn clamp(mut self, min: f32, max: f32) -> f32 {
1453        const_assert!(
1454            min <= max,
1455            "min > max, or either was NaN",
1456            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1457            min: f32,
1458            max: f32,
1459        );
1460
1461        if self < min {
1462            self = min;
1463        }
1464        if self > max {
1465            self = max;
1466        }
1467        self
1468    }
1469
1470    /// Computes the absolute value of `self`.
1471    ///
1472    /// This function always returns the precise result.
1473    ///
1474    /// # Examples
1475    ///
1476    /// ```
1477    /// let x = 3.5_f32;
1478    /// let y = -3.5_f32;
1479    ///
1480    /// assert_eq!(x.abs(), x);
1481    /// assert_eq!(y.abs(), -y);
1482    ///
1483    /// assert!(f32::NAN.abs().is_nan());
1484    /// ```
1485    #[must_use = "method returns a new number and does not mutate the original value"]
1486    #[stable(feature = "rust1", since = "1.0.0")]
1487    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1488    #[inline]
1489    pub const fn abs(self) -> f32 {
1490        intrinsics::fabsf32(self)
1491    }
1492
1493    /// Returns a number that represents the sign of `self`.
1494    ///
1495    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1496    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1497    /// - NaN if the number is NaN
1498    ///
1499    /// # Examples
1500    ///
1501    /// ```
1502    /// let f = 3.5_f32;
1503    ///
1504    /// assert_eq!(f.signum(), 1.0);
1505    /// assert_eq!(f32::NEG_INFINITY.signum(), -1.0);
1506    ///
1507    /// assert!(f32::NAN.signum().is_nan());
1508    /// ```
1509    #[must_use = "method returns a new number and does not mutate the original value"]
1510    #[stable(feature = "rust1", since = "1.0.0")]
1511    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1512    #[inline]
1513    pub const fn signum(self) -> f32 {
1514        if self.is_nan() { Self::NAN } else { 1.0_f32.copysign(self) }
1515    }
1516
1517    /// Returns a number composed of the magnitude of `self` and the sign of
1518    /// `sign`.
1519    ///
1520    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1521    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1522    /// returned.
1523    ///
1524    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1525    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1526    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1527    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1528    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1529    /// info.
1530    ///
1531    /// # Examples
1532    ///
1533    /// ```
1534    /// let f = 3.5_f32;
1535    ///
1536    /// assert_eq!(f.copysign(0.42), 3.5_f32);
1537    /// assert_eq!(f.copysign(-0.42), -3.5_f32);
1538    /// assert_eq!((-f).copysign(0.42), 3.5_f32);
1539    /// assert_eq!((-f).copysign(-0.42), -3.5_f32);
1540    ///
1541    /// assert!(f32::NAN.copysign(1.0).is_nan());
1542    /// ```
1543    #[must_use = "method returns a new number and does not mutate the original value"]
1544    #[inline]
1545    #[stable(feature = "copysign", since = "1.35.0")]
1546    #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1547    pub const fn copysign(self, sign: f32) -> f32 {
1548        intrinsics::copysignf32(self, sign)
1549    }
1550
1551    /// Float addition that allows optimizations based on algebraic rules.
1552    ///
1553    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1554    #[must_use = "method returns a new number and does not mutate the original value"]
1555    #[unstable(feature = "float_algebraic", issue = "136469")]
1556    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1557    #[inline]
1558    #[cfg(not(feature = "ferrocene_certified"))]
1559    pub const fn algebraic_add(self, rhs: f32) -> f32 {
1560        intrinsics::fadd_algebraic(self, rhs)
1561    }
1562
1563    /// Float subtraction that allows optimizations based on algebraic rules.
1564    ///
1565    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1566    #[must_use = "method returns a new number and does not mutate the original value"]
1567    #[unstable(feature = "float_algebraic", issue = "136469")]
1568    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1569    #[inline]
1570    #[cfg(not(feature = "ferrocene_certified"))]
1571    pub const fn algebraic_sub(self, rhs: f32) -> f32 {
1572        intrinsics::fsub_algebraic(self, rhs)
1573    }
1574
1575    /// Float multiplication that allows optimizations based on algebraic rules.
1576    ///
1577    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1578    #[must_use = "method returns a new number and does not mutate the original value"]
1579    #[unstable(feature = "float_algebraic", issue = "136469")]
1580    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1581    #[inline]
1582    #[cfg(not(feature = "ferrocene_certified"))]
1583    pub const fn algebraic_mul(self, rhs: f32) -> f32 {
1584        intrinsics::fmul_algebraic(self, rhs)
1585    }
1586
1587    /// Float division that allows optimizations based on algebraic rules.
1588    ///
1589    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1590    #[must_use = "method returns a new number and does not mutate the original value"]
1591    #[unstable(feature = "float_algebraic", issue = "136469")]
1592    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1593    #[inline]
1594    #[cfg(not(feature = "ferrocene_certified"))]
1595    pub const fn algebraic_div(self, rhs: f32) -> f32 {
1596        intrinsics::fdiv_algebraic(self, rhs)
1597    }
1598
1599    /// Float remainder that allows optimizations based on algebraic rules.
1600    ///
1601    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1602    #[must_use = "method returns a new number and does not mutate the original value"]
1603    #[unstable(feature = "float_algebraic", issue = "136469")]
1604    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1605    #[inline]
1606    #[cfg(not(feature = "ferrocene_certified"))]
1607    pub const fn algebraic_rem(self, rhs: f32) -> f32 {
1608        intrinsics::frem_algebraic(self, rhs)
1609    }
1610}
1611
1612/// Experimental implementations of floating point functions in `core`.
1613///
1614/// _The standalone functions in this module are for testing only.
1615/// They will be stabilized as inherent methods._
1616#[unstable(feature = "core_float_math", issue = "137578")]
1617#[cfg(not(feature = "ferrocene_certified"))]
1618pub mod math {
1619    use crate::intrinsics;
1620    use crate::num::libm;
1621
1622    /// Experimental version of `floor` in `core`. See [`f32::floor`] for details.
1623    ///
1624    /// # Examples
1625    ///
1626    /// ```
1627    /// #![feature(core_float_math)]
1628    ///
1629    /// use core::f32;
1630    ///
1631    /// let f = 3.7_f32;
1632    /// let g = 3.0_f32;
1633    /// let h = -3.7_f32;
1634    ///
1635    /// assert_eq!(f32::math::floor(f), 3.0);
1636    /// assert_eq!(f32::math::floor(g), 3.0);
1637    /// assert_eq!(f32::math::floor(h), -4.0);
1638    /// ```
1639    ///
1640    /// _This standalone function is for testing only.
1641    /// It will be stabilized as an inherent method._
1642    ///
1643    /// [`f32::floor`]: ../../../std/primitive.f32.html#method.floor
1644    #[inline]
1645    #[unstable(feature = "core_float_math", issue = "137578")]
1646    #[must_use = "method returns a new number and does not mutate the original value"]
1647    pub const fn floor(x: f32) -> f32 {
1648        intrinsics::floorf32(x)
1649    }
1650
1651    /// Experimental version of `ceil` in `core`. See [`f32::ceil`] for details.
1652    ///
1653    /// # Examples
1654    ///
1655    /// ```
1656    /// #![feature(core_float_math)]
1657    ///
1658    /// use core::f32;
1659    ///
1660    /// let f = 3.01_f32;
1661    /// let g = 4.0_f32;
1662    ///
1663    /// assert_eq!(f32::math::ceil(f), 4.0);
1664    /// assert_eq!(f32::math::ceil(g), 4.0);
1665    /// ```
1666    ///
1667    /// _This standalone function is for testing only.
1668    /// It will be stabilized as an inherent method._
1669    ///
1670    /// [`f32::ceil`]: ../../../std/primitive.f32.html#method.ceil
1671    #[inline]
1672    #[doc(alias = "ceiling")]
1673    #[must_use = "method returns a new number and does not mutate the original value"]
1674    #[unstable(feature = "core_float_math", issue = "137578")]
1675    pub const fn ceil(x: f32) -> f32 {
1676        intrinsics::ceilf32(x)
1677    }
1678
1679    /// Experimental version of `round` in `core`. See [`f32::round`] for details.
1680    ///
1681    /// # Examples
1682    ///
1683    /// ```
1684    /// #![feature(core_float_math)]
1685    ///
1686    /// use core::f32;
1687    ///
1688    /// let f = 3.3_f32;
1689    /// let g = -3.3_f32;
1690    /// let h = -3.7_f32;
1691    /// let i = 3.5_f32;
1692    /// let j = 4.5_f32;
1693    ///
1694    /// assert_eq!(f32::math::round(f), 3.0);
1695    /// assert_eq!(f32::math::round(g), -3.0);
1696    /// assert_eq!(f32::math::round(h), -4.0);
1697    /// assert_eq!(f32::math::round(i), 4.0);
1698    /// assert_eq!(f32::math::round(j), 5.0);
1699    /// ```
1700    ///
1701    /// _This standalone function is for testing only.
1702    /// It will be stabilized as an inherent method._
1703    ///
1704    /// [`f32::round`]: ../../../std/primitive.f32.html#method.round
1705    #[inline]
1706    #[unstable(feature = "core_float_math", issue = "137578")]
1707    #[must_use = "method returns a new number and does not mutate the original value"]
1708    pub const fn round(x: f32) -> f32 {
1709        intrinsics::roundf32(x)
1710    }
1711
1712    /// Experimental version of `round_ties_even` in `core`. See [`f32::round_ties_even`] for
1713    /// details.
1714    ///
1715    /// # Examples
1716    ///
1717    /// ```
1718    /// #![feature(core_float_math)]
1719    ///
1720    /// use core::f32;
1721    ///
1722    /// let f = 3.3_f32;
1723    /// let g = -3.3_f32;
1724    /// let h = 3.5_f32;
1725    /// let i = 4.5_f32;
1726    ///
1727    /// assert_eq!(f32::math::round_ties_even(f), 3.0);
1728    /// assert_eq!(f32::math::round_ties_even(g), -3.0);
1729    /// assert_eq!(f32::math::round_ties_even(h), 4.0);
1730    /// assert_eq!(f32::math::round_ties_even(i), 4.0);
1731    /// ```
1732    ///
1733    /// _This standalone function is for testing only.
1734    /// It will be stabilized as an inherent method._
1735    ///
1736    /// [`f32::round_ties_even`]: ../../../std/primitive.f32.html#method.round_ties_even
1737    #[inline]
1738    #[unstable(feature = "core_float_math", issue = "137578")]
1739    #[must_use = "method returns a new number and does not mutate the original value"]
1740    pub const fn round_ties_even(x: f32) -> f32 {
1741        intrinsics::round_ties_even_f32(x)
1742    }
1743
1744    /// Experimental version of `trunc` in `core`. See [`f32::trunc`] for details.
1745    ///
1746    /// # Examples
1747    ///
1748    /// ```
1749    /// #![feature(core_float_math)]
1750    ///
1751    /// use core::f32;
1752    ///
1753    /// let f = 3.7_f32;
1754    /// let g = 3.0_f32;
1755    /// let h = -3.7_f32;
1756    ///
1757    /// assert_eq!(f32::math::trunc(f), 3.0);
1758    /// assert_eq!(f32::math::trunc(g), 3.0);
1759    /// assert_eq!(f32::math::trunc(h), -3.0);
1760    /// ```
1761    ///
1762    /// _This standalone function is for testing only.
1763    /// It will be stabilized as an inherent method._
1764    ///
1765    /// [`f32::trunc`]: ../../../std/primitive.f32.html#method.trunc
1766    #[inline]
1767    #[doc(alias = "truncate")]
1768    #[must_use = "method returns a new number and does not mutate the original value"]
1769    #[unstable(feature = "core_float_math", issue = "137578")]
1770    pub const fn trunc(x: f32) -> f32 {
1771        intrinsics::truncf32(x)
1772    }
1773
1774    /// Experimental version of `fract` in `core`. See [`f32::fract`] for details.
1775    ///
1776    /// # Examples
1777    ///
1778    /// ```
1779    /// #![feature(core_float_math)]
1780    ///
1781    /// use core::f32;
1782    ///
1783    /// let x = 3.6_f32;
1784    /// let y = -3.6_f32;
1785    /// let abs_difference_x = (f32::math::fract(x) - 0.6).abs();
1786    /// let abs_difference_y = (f32::math::fract(y) - (-0.6)).abs();
1787    ///
1788    /// assert!(abs_difference_x <= f32::EPSILON);
1789    /// assert!(abs_difference_y <= f32::EPSILON);
1790    /// ```
1791    ///
1792    /// _This standalone function is for testing only.
1793    /// It will be stabilized as an inherent method._
1794    ///
1795    /// [`f32::fract`]: ../../../std/primitive.f32.html#method.fract
1796    #[inline]
1797    #[unstable(feature = "core_float_math", issue = "137578")]
1798    #[must_use = "method returns a new number and does not mutate the original value"]
1799    pub const fn fract(x: f32) -> f32 {
1800        x - trunc(x)
1801    }
1802
1803    /// Experimental version of `mul_add` in `core`. See [`f32::mul_add`] for details.
1804    ///
1805    /// # Examples
1806    ///
1807    /// ```
1808    /// #![feature(core_float_math)]
1809    ///
1810    /// # // FIXME(#140515): mingw has an incorrect fma
1811    /// # // https://sourceforge.net/p/mingw-w64/bugs/848/
1812    /// # #[cfg(all(target_os = "windows", target_env = "gnu", not(target_abi = "llvm")))] {
1813    /// use core::f32;
1814    ///
1815    /// let m = 10.0_f32;
1816    /// let x = 4.0_f32;
1817    /// let b = 60.0_f32;
1818    ///
1819    /// assert_eq!(f32::math::mul_add(m, x, b), 100.0);
1820    /// assert_eq!(m * x + b, 100.0);
1821    ///
1822    /// let one_plus_eps = 1.0_f32 + f32::EPSILON;
1823    /// let one_minus_eps = 1.0_f32 - f32::EPSILON;
1824    /// let minus_one = -1.0_f32;
1825    ///
1826    /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1827    /// assert_eq!(
1828    ///     f32::math::mul_add(one_plus_eps, one_minus_eps, minus_one),
1829    ///     -f32::EPSILON * f32::EPSILON
1830    /// );
1831    /// // Different rounding with the non-fused multiply and add.
1832    /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1833    /// # }
1834    /// ```
1835    ///
1836    /// _This standalone function is for testing only.
1837    /// It will be stabilized as an inherent method._
1838    ///
1839    /// [`f32::mul_add`]: ../../../std/primitive.f32.html#method.mul_add
1840    #[inline]
1841    #[doc(alias = "fmaf", alias = "fusedMultiplyAdd")]
1842    #[must_use = "method returns a new number and does not mutate the original value"]
1843    #[unstable(feature = "core_float_math", issue = "137578")]
1844    #[rustc_const_unstable(feature = "const_mul_add", issue = "146724")]
1845    pub const fn mul_add(x: f32, y: f32, z: f32) -> f32 {
1846        intrinsics::fmaf32(x, y, z)
1847    }
1848
1849    /// Experimental version of `div_euclid` in `core`. See [`f32::div_euclid`] for details.
1850    ///
1851    /// # Examples
1852    ///
1853    /// ```
1854    /// #![feature(core_float_math)]
1855    ///
1856    /// use core::f32;
1857    ///
1858    /// let a: f32 = 7.0;
1859    /// let b = 4.0;
1860    /// assert_eq!(f32::math::div_euclid(a, b), 1.0); // 7.0 > 4.0 * 1.0
1861    /// assert_eq!(f32::math::div_euclid(-a, b), -2.0); // -7.0 >= 4.0 * -2.0
1862    /// assert_eq!(f32::math::div_euclid(a, -b), -1.0); // 7.0 >= -4.0 * -1.0
1863    /// assert_eq!(f32::math::div_euclid(-a, -b), 2.0); // -7.0 >= -4.0 * 2.0
1864    /// ```
1865    ///
1866    /// _This standalone function is for testing only.
1867    /// It will be stabilized as an inherent method._
1868    ///
1869    /// [`f32::div_euclid`]: ../../../std/primitive.f32.html#method.div_euclid
1870    #[inline]
1871    #[unstable(feature = "core_float_math", issue = "137578")]
1872    #[must_use = "method returns a new number and does not mutate the original value"]
1873    pub fn div_euclid(x: f32, rhs: f32) -> f32 {
1874        let q = trunc(x / rhs);
1875        if x % rhs < 0.0 {
1876            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1877        }
1878        q
1879    }
1880
1881    /// Experimental version of `rem_euclid` in `core`. See [`f32::rem_euclid`] for details.
1882    ///
1883    /// # Examples
1884    ///
1885    /// ```
1886    /// #![feature(core_float_math)]
1887    ///
1888    /// use core::f32;
1889    ///
1890    /// let a: f32 = 7.0;
1891    /// let b = 4.0;
1892    /// assert_eq!(f32::math::rem_euclid(a, b), 3.0);
1893    /// assert_eq!(f32::math::rem_euclid(-a, b), 1.0);
1894    /// assert_eq!(f32::math::rem_euclid(a, -b), 3.0);
1895    /// assert_eq!(f32::math::rem_euclid(-a, -b), 1.0);
1896    /// // limitation due to round-off error
1897    /// assert!(f32::math::rem_euclid(-f32::EPSILON, 3.0) != 0.0);
1898    /// ```
1899    ///
1900    /// _This standalone function is for testing only.
1901    /// It will be stabilized as an inherent method._
1902    ///
1903    /// [`f32::rem_euclid`]: ../../../std/primitive.f32.html#method.rem_euclid
1904    #[inline]
1905    #[doc(alias = "modulo", alias = "mod")]
1906    #[unstable(feature = "core_float_math", issue = "137578")]
1907    #[must_use = "method returns a new number and does not mutate the original value"]
1908    pub fn rem_euclid(x: f32, rhs: f32) -> f32 {
1909        let r = x % rhs;
1910        if r < 0.0 { r + rhs.abs() } else { r }
1911    }
1912
1913    /// Experimental version of `powi` in `core`. See [`f32::powi`] for details.
1914    ///
1915    /// # Examples
1916    ///
1917    /// ```
1918    /// #![feature(core_float_math)]
1919    ///
1920    /// use core::f32;
1921    ///
1922    /// let x = 2.0_f32;
1923    /// let abs_difference = (f32::math::powi(x, 2) - (x * x)).abs();
1924    /// assert!(abs_difference <= 1e-5);
1925    ///
1926    /// assert_eq!(f32::math::powi(f32::NAN, 0), 1.0);
1927    /// ```
1928    ///
1929    /// _This standalone function is for testing only.
1930    /// It will be stabilized as an inherent method._
1931    ///
1932    /// [`f32::powi`]: ../../../std/primitive.f32.html#method.powi
1933    #[inline]
1934    #[must_use = "method returns a new number and does not mutate the original value"]
1935    #[unstable(feature = "core_float_math", issue = "137578")]
1936    pub fn powi(x: f32, n: i32) -> f32 {
1937        intrinsics::powif32(x, n)
1938    }
1939
1940    /// Experimental version of `sqrt` in `core`. See [`f32::sqrt`] for details.
1941    ///
1942    /// # Examples
1943    ///
1944    /// ```
1945    /// #![feature(core_float_math)]
1946    ///
1947    /// use core::f32;
1948    ///
1949    /// let positive = 4.0_f32;
1950    /// let negative = -4.0_f32;
1951    /// let negative_zero = -0.0_f32;
1952    ///
1953    /// assert_eq!(f32::math::sqrt(positive), 2.0);
1954    /// assert!(f32::math::sqrt(negative).is_nan());
1955    /// assert_eq!(f32::math::sqrt(negative_zero), negative_zero);
1956    /// ```
1957    ///
1958    /// _This standalone function is for testing only.
1959    /// It will be stabilized as an inherent method._
1960    ///
1961    /// [`f32::sqrt`]: ../../../std/primitive.f32.html#method.sqrt
1962    #[inline]
1963    #[doc(alias = "squareRoot")]
1964    #[unstable(feature = "core_float_math", issue = "137578")]
1965    #[must_use = "method returns a new number and does not mutate the original value"]
1966    pub fn sqrt(x: f32) -> f32 {
1967        intrinsics::sqrtf32(x)
1968    }
1969
1970    /// Experimental version of `abs_sub` in `core`. See [`f32::abs_sub`] for details.
1971    ///
1972    /// # Examples
1973    ///
1974    /// ```
1975    /// #![feature(core_float_math)]
1976    ///
1977    /// use core::f32;
1978    ///
1979    /// let x = 3.0f32;
1980    /// let y = -3.0f32;
1981    ///
1982    /// let abs_difference_x = (f32::math::abs_sub(x, 1.0) - 2.0).abs();
1983    /// let abs_difference_y = (f32::math::abs_sub(y, 1.0) - 0.0).abs();
1984    ///
1985    /// assert!(abs_difference_x <= 1e-6);
1986    /// assert!(abs_difference_y <= 1e-6);
1987    /// ```
1988    ///
1989    /// _This standalone function is for testing only.
1990    /// It will be stabilized as an inherent method._
1991    ///
1992    /// [`f32::abs_sub`]: ../../../std/primitive.f32.html#method.abs_sub
1993    #[inline]
1994    #[stable(feature = "rust1", since = "1.0.0")]
1995    #[deprecated(
1996        since = "1.10.0",
1997        note = "you probably meant `(self - other).abs()`: \
1998            this operation is `(self - other).max(0.0)` \
1999            except that `abs_sub` also propagates NaNs (also \
2000            known as `fdimf` in C). If you truly need the positive \
2001            difference, consider using that expression or the C function \
2002            `fdimf`, depending on how you wish to handle NaN (please consider \
2003            filing an issue describing your use-case too)."
2004    )]
2005    #[must_use = "method returns a new number and does not mutate the original value"]
2006    pub fn abs_sub(x: f32, other: f32) -> f32 {
2007        libm::fdimf(x, other)
2008    }
2009
2010    /// Experimental version of `cbrt` in `core`. See [`f32::cbrt`] for details.
2011    ///
2012    /// # Unspecified precision
2013    ///
2014    /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
2015    /// can even differ within the same execution from one invocation to the next.
2016    /// This function currently corresponds to the `cbrtf` from libc on Unix
2017    /// and Windows. Note that this might change in the future.
2018    ///
2019    /// # Examples
2020    ///
2021    /// ```
2022    /// #![feature(core_float_math)]
2023    ///
2024    /// use core::f32;
2025    ///
2026    /// let x = 8.0f32;
2027    ///
2028    /// // x^(1/3) - 2 == 0
2029    /// let abs_difference = (f32::math::cbrt(x) - 2.0).abs();
2030    ///
2031    /// assert!(abs_difference <= 1e-6);
2032    /// ```
2033    ///
2034    /// _This standalone function is for testing only.
2035    /// It will be stabilized as an inherent method._
2036    ///
2037    /// [`f32::cbrt`]: ../../../std/primitive.f32.html#method.cbrt
2038    #[inline]
2039    #[must_use = "method returns a new number and does not mutate the original value"]
2040    #[unstable(feature = "core_float_math", issue = "137578")]
2041    pub fn cbrt(x: f32) -> f32 {
2042        libm::cbrtf(x)
2043    }
2044}