Skip to main content

core/num/
f32.rs

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