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