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