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