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