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