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