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