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_f32(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_f32(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 #[inline]
888 pub const fn maximum(self, other: f32) -> f32 {
889 intrinsics::maximumf32(self, other)
890 }
891
892 /// Returns the minimum of the two numbers, propagating NaN.
893 ///
894 /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
895 /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
896 /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
897 /// non-NaN inputs.
898 ///
899 /// This is in contrast to [`f32::min`] which only returns NaN when *both* arguments are NaN,
900 /// and which does not reliably order `-0.0` and `+0.0`.
901 ///
902 /// This follows the IEEE 754-2019 semantics for `minimum`.
903 ///
904 /// ```
905 /// #![feature(float_minimum_maximum)]
906 /// let x = 1.0f32;
907 /// let y = 2.0f32;
908 ///
909 /// assert_eq!(x.minimum(y), x);
910 /// assert!(x.minimum(f32::NAN).is_nan());
911 /// ```
912 #[must_use = "this returns the result of the comparison, without modifying either input"]
913 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
914 #[inline]
915 pub const fn minimum(self, other: f32) -> f32 {
916 intrinsics::minimumf32(self, other)
917 }
918
919 /// Calculates the midpoint (average) between `self` and `rhs`.
920 ///
921 /// This returns NaN when *either* argument is NaN or if a combination of
922 /// +inf and -inf is provided as arguments.
923 ///
924 /// # Examples
925 ///
926 /// ```
927 /// assert_eq!(1f32.midpoint(4.0), 2.5);
928 /// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
929 /// ```
930 #[inline]
931 #[doc(alias = "average")]
932 #[stable(feature = "num_midpoint", since = "1.85.0")]
933 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
934 #[must_use = "this returns the result of the operation, \
935 without modifying the original"]
936 pub const fn midpoint(self, other: f32) -> f32 {
937 cfg_select! {
938 // Allow faster implementation that have known good 64-bit float
939 // implementations. Falling back to the branchy code on targets that don't
940 // have 64-bit hardware floats or buggy implementations.
941 // https://github.com/rust-lang/rust/pull/121062#issuecomment-2123408114
942 any(
943 target_arch = "x86_64",
944 target_arch = "aarch64",
945 all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "d"),
946 all(target_arch = "loongarch64", target_feature = "d"),
947 all(target_arch = "arm", target_feature = "vfp2"),
948 target_arch = "wasm32",
949 target_arch = "wasm64",
950 ) => ((self as f64 + other as f64) * 0.5) as f32,
951 _ => {
952 const HI: f32 = f32::MAX * 0.5;
953
954 let (a, b) = (self, other);
955 let abs_a = a.abs();
956 let abs_b = b.abs();
957
958 if abs_a <= HI && abs_b <= HI {
959 // Overflow is impossible
960 (a + b) * 0.5
961 } else {
962 (a * 0.5) + (b * 0.5)
963 }
964 }
965 }
966 }
967
968 /// Rounds toward zero and converts to any primitive integer type,
969 /// assuming that the value is finite and fits in that type.
970 ///
971 /// ```
972 /// let value = 4.6_f32;
973 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
974 /// assert_eq!(rounded, 4);
975 ///
976 /// let value = -128.9_f32;
977 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
978 /// assert_eq!(rounded, i8::MIN);
979 /// ```
980 ///
981 /// # Safety
982 ///
983 /// The value must:
984 ///
985 /// * Not be `NaN`
986 /// * Not be infinite
987 /// * Be representable in the return type `Int`, after truncating off its fractional part
988 #[must_use = "this returns the result of the operation, \
989 without modifying the original"]
990 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
991 #[inline]
992 pub unsafe fn to_int_unchecked<Int>(self) -> Int
993 where
994 Self: FloatToInt<Int>,
995 {
996 // SAFETY: the caller must uphold the safety contract for
997 // `FloatToInt::to_int_unchecked`.
998 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
999 }
1000
1001 /// Converts to the target float type, rounding as defined in IEEE 754.
1002 ///
1003 /// This is equivalent to `self as Flt`. Narrowing to a smaller type can
1004 /// produce an infinity.
1005 ///
1006 /// ```
1007 /// #![feature(float_conversions)]
1008 ///
1009 /// let x = 1.5_f32;
1010 /// assert_eq!(x.cast::<f64>(), 1.5_f64);
1011 /// ```
1012 #[unstable(feature = "float_conversions", issue = "159913")]
1013 #[must_use = "this returns the result of the operation, \
1014 without modifying the original"]
1015 #[inline]
1016 pub fn cast<Flt>(self) -> Flt
1017 where
1018 Self: FloatToFloat<Flt>,
1019 {
1020 FloatToFloat::<Flt>::cast(self)
1021 }
1022
1023 /// Rounds toward zero and converts to any primitive integer type, saturating
1024 /// at the type's boundaries and mapping `NaN` to zero.
1025 ///
1026 /// This is equivalent to `self as Int`.
1027 ///
1028 /// ```
1029 /// #![feature(float_conversions)]
1030 ///
1031 /// assert_eq!(255.5_f32.to_int_saturating::<u8>(), 255);
1032 /// assert_eq!(300.0_f32.to_int_saturating::<u8>(), 255);
1033 /// assert_eq!((-1.0_f32).to_int_saturating::<u8>(), 0);
1034 /// assert_eq!(f32::NAN.to_int_saturating::<u8>(), 0);
1035 /// ```
1036 #[unstable(feature = "float_conversions", issue = "159913")]
1037 #[must_use = "this returns the result of the operation, \
1038 without modifying the original"]
1039 #[inline]
1040 pub fn to_int_saturating<Int>(self) -> Int
1041 where
1042 Self: FloatToInt<Int>,
1043 {
1044 FloatToInt::<Int>::to_int_saturating(self)
1045 }
1046
1047 /// Rounds toward zero and converts to any primitive integer type, returning
1048 /// `None` if the value is `NaN`, infinite, or does not fit in the target type.
1049 ///
1050 /// ```
1051 /// #![feature(float_conversions)]
1052 ///
1053 /// assert_eq!(255.5_f32.to_int_checked::<u8>(), Some(255));
1054 /// assert_eq!(256.0_f32.to_int_checked::<u8>(), None);
1055 /// assert_eq!(f32::NAN.to_int_checked::<u8>(), None);
1056 /// ```
1057 #[unstable(feature = "float_conversions", issue = "159913")]
1058 #[must_use = "this returns the result of the operation, \
1059 without modifying the original"]
1060 #[inline]
1061 pub fn to_int_checked<Int>(self) -> Option<Int>
1062 where
1063 Self: FloatToInt<Int>,
1064 {
1065 FloatToInt::<Int>::to_int_checked(self)
1066 }
1067
1068 /// Rounds toward zero and converts to any primitive integer type.
1069 ///
1070 /// This is equivalent to `self.to_int_checked().unwrap()`.
1071 ///
1072 /// # Panics
1073 ///
1074 /// Panics if the value is `NaN`, infinite, or does not fit in the target type.
1075 ///
1076 /// ```
1077 /// #![feature(float_conversions)]
1078 ///
1079 /// assert_eq!(255.5_f32.to_int_strict::<u8>(), 255);
1080 /// ```
1081 #[unstable(feature = "float_conversions", issue = "159913")]
1082 #[must_use = "this returns the result of the operation, \
1083 without modifying the original"]
1084 #[inline]
1085 #[track_caller]
1086 pub fn to_int_strict<Int>(self) -> Int
1087 where
1088 Self: FloatToInt<Int>,
1089 {
1090 self.to_int_checked::<Int>()
1091 .expect("the value cannot be represented in the target integer type")
1092 }
1093
1094 /// Raw transmutation to `u32`.
1095 ///
1096 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
1097 ///
1098 /// See [`from_bits`](Self::from_bits) for some discussion of the
1099 /// portability of this operation (there are almost no issues).
1100 ///
1101 /// Note that this function is distinct from `as` casting, which attempts to
1102 /// preserve the *numeric* value, and not the bitwise value.
1103 ///
1104 /// # Examples
1105 ///
1106 /// ```
1107 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
1108 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
1109 ///
1110 /// ```
1111 #[must_use = "this returns the result of the operation, \
1112 without modifying the original"]
1113 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1114 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1115 #[inline]
1116 #[allow(unnecessary_transmutes)]
1117 pub const fn to_bits(self) -> u32 {
1118 // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1119 unsafe { mem::transmute(self) }
1120 }
1121
1122 /// Raw transmutation from `u32`.
1123 ///
1124 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1125 /// It turns out this is incredibly portable, for two reasons:
1126 ///
1127 /// * Floats and Ints have the same endianness on all supported platforms.
1128 /// * IEEE 754 very precisely specifies the bit layout of floats.
1129 ///
1130 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1131 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1132 /// (notably x86 and ARM) picked the interpretation that was ultimately
1133 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1134 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1135 ///
1136 /// Rather than trying to preserve signaling-ness cross-platform, this
1137 /// implementation favors preserving the exact bits. This means that
1138 /// any payloads encoded in NaNs will be preserved even if the result of
1139 /// this method is sent over the network from an x86 machine to a MIPS one.
1140 ///
1141 /// If the results of this method are only manipulated by the same
1142 /// architecture that produced them, then there is no portability concern.
1143 ///
1144 /// If the input isn't NaN, then there is no portability concern.
1145 ///
1146 /// If you don't care about signalingness (very likely), then there is no
1147 /// portability concern.
1148 ///
1149 /// Note that this function is distinct from `as` casting, which attempts to
1150 /// preserve the *numeric* value, and not the bitwise value.
1151 ///
1152 /// # Examples
1153 ///
1154 /// ```
1155 /// let v = f32::from_bits(0x41480000);
1156 /// assert_eq!(v, 12.5);
1157 /// ```
1158 #[stable(feature = "float_bits_conv", since = "1.20.0")]
1159 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1160 #[must_use]
1161 #[inline]
1162 #[allow(unnecessary_transmutes)]
1163 pub const fn from_bits(v: u32) -> Self {
1164 // It turns out the safety issues with sNaN were overblown! Hooray!
1165 // SAFETY: `u32` is a plain old datatype so we can always transmute from it.
1166 unsafe { mem::transmute(v) }
1167 }
1168
1169 /// Returns the memory representation of this floating point number as a byte array in
1170 /// big-endian (network) byte order.
1171 ///
1172 /// See [`from_bits`](Self::from_bits) for some discussion of the
1173 /// portability of this operation (there are almost no issues).
1174 ///
1175 /// # Examples
1176 ///
1177 /// ```
1178 /// let bytes = 12.5f32.to_be_bytes();
1179 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1180 /// ```
1181 #[must_use = "this returns the result of the operation, \
1182 without modifying the original"]
1183 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1184 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1185 #[inline]
1186 pub const fn to_be_bytes(self) -> [u8; 4] {
1187 self.to_bits().to_be_bytes()
1188 }
1189
1190 /// Returns the memory representation of this floating point number as a byte array in
1191 /// little-endian byte order.
1192 ///
1193 /// See [`from_bits`](Self::from_bits) for some discussion of the
1194 /// portability of this operation (there are almost no issues).
1195 ///
1196 /// # Examples
1197 ///
1198 /// ```
1199 /// let bytes = 12.5f32.to_le_bytes();
1200 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1201 /// ```
1202 #[must_use = "this returns the result of the operation, \
1203 without modifying the original"]
1204 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1205 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1206 #[inline]
1207 pub const fn to_le_bytes(self) -> [u8; 4] {
1208 self.to_bits().to_le_bytes()
1209 }
1210
1211 /// Returns the memory representation of this floating point number as a byte array in
1212 /// native byte order.
1213 ///
1214 /// As the target platform's native endianness is used, portable code
1215 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1216 ///
1217 /// [`to_be_bytes`]: f32::to_be_bytes
1218 /// [`to_le_bytes`]: f32::to_le_bytes
1219 ///
1220 /// See [`from_bits`](Self::from_bits) for some discussion of the
1221 /// portability of this operation (there are almost no issues).
1222 ///
1223 /// # Examples
1224 ///
1225 /// ```
1226 /// let bytes = 12.5f32.to_ne_bytes();
1227 /// assert_eq!(
1228 /// bytes,
1229 /// if cfg!(target_endian = "big") {
1230 /// [0x41, 0x48, 0x00, 0x00]
1231 /// } else {
1232 /// [0x00, 0x00, 0x48, 0x41]
1233 /// }
1234 /// );
1235 /// ```
1236 #[must_use = "this returns the result of the operation, \
1237 without modifying the original"]
1238 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1239 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1240 #[inline]
1241 pub const fn to_ne_bytes(self) -> [u8; 4] {
1242 self.to_bits().to_ne_bytes()
1243 }
1244
1245 /// Creates a floating point value from its representation as a byte array in big endian.
1246 ///
1247 /// See [`from_bits`](Self::from_bits) for some discussion of the
1248 /// portability of this operation (there are almost no issues).
1249 ///
1250 /// # Examples
1251 ///
1252 /// ```
1253 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1254 /// assert_eq!(value, 12.5);
1255 /// ```
1256 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1257 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1258 #[must_use]
1259 #[inline]
1260 pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
1261 Self::from_bits(u32::from_be_bytes(bytes))
1262 }
1263
1264 /// Creates a floating point value from its representation as a byte array in little endian.
1265 ///
1266 /// See [`from_bits`](Self::from_bits) for some discussion of the
1267 /// portability of this operation (there are almost no issues).
1268 ///
1269 /// # Examples
1270 ///
1271 /// ```
1272 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1273 /// assert_eq!(value, 12.5);
1274 /// ```
1275 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1276 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1277 #[must_use]
1278 #[inline]
1279 pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
1280 Self::from_bits(u32::from_le_bytes(bytes))
1281 }
1282
1283 /// Creates a floating point value from its representation as a byte array in native endian.
1284 ///
1285 /// As the target platform's native endianness is used, portable code
1286 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1287 /// appropriate instead.
1288 ///
1289 /// [`from_be_bytes`]: f32::from_be_bytes
1290 /// [`from_le_bytes`]: f32::from_le_bytes
1291 ///
1292 /// See [`from_bits`](Self::from_bits) for some discussion of the
1293 /// portability of this operation (there are almost no issues).
1294 ///
1295 /// # Examples
1296 ///
1297 /// ```
1298 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1299 /// [0x41, 0x48, 0x00, 0x00]
1300 /// } else {
1301 /// [0x00, 0x00, 0x48, 0x41]
1302 /// });
1303 /// assert_eq!(value, 12.5);
1304 /// ```
1305 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
1306 #[rustc_const_stable(feature = "const_float_bits_conv", since = "1.83.0")]
1307 #[must_use]
1308 #[inline]
1309 pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
1310 Self::from_bits(u32::from_ne_bytes(bytes))
1311 }
1312
1313 /// Returns the ordering between `self` and `other`.
1314 ///
1315 /// Unlike the standard partial comparison between floating point numbers,
1316 /// this comparison always produces an ordering in accordance to
1317 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1318 /// floating point standard. The values are ordered in the following sequence:
1319 ///
1320 /// - negative quiet NaN
1321 /// - negative signaling NaN
1322 /// - negative infinity
1323 /// - negative numbers
1324 /// - negative subnormal numbers
1325 /// - negative zero
1326 /// - positive zero
1327 /// - positive subnormal numbers
1328 /// - positive numbers
1329 /// - positive infinity
1330 /// - positive signaling NaN
1331 /// - positive quiet NaN.
1332 ///
1333 /// The ordering established by this function does not always agree with the
1334 /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1335 /// they consider negative and positive zero equal, while `total_cmp`
1336 /// doesn't.
1337 ///
1338 /// The interpretation of the signaling NaN bit follows the definition in
1339 /// the IEEE 754 standard, which may not match the interpretation by some of
1340 /// the older, non-conformant (e.g. MIPS) hardware implementations.
1341 ///
1342 /// # Example
1343 ///
1344 /// ```
1345 /// struct GoodBoy {
1346 /// name: String,
1347 /// weight: f32,
1348 /// }
1349 ///
1350 /// let mut bois = vec![
1351 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1352 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1353 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1354 /// GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1355 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1356 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1357 /// ];
1358 ///
1359 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1360 ///
1361 /// // `f32::NAN` could be positive or negative, which will affect the sort order.
1362 /// if f32::NAN.is_sign_negative() {
1363 /// assert!(bois.into_iter().map(|b| b.weight)
1364 /// .zip([f32::NAN, -5.0, 0.1, 10.0, 99.0, f32::INFINITY].iter())
1365 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1366 /// } else {
1367 /// assert!(bois.into_iter().map(|b| b.weight)
1368 /// .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1369 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1370 /// }
1371 /// ```
1372 #[stable(feature = "total_cmp", since = "1.62.0")]
1373 #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1374 #[must_use]
1375 #[inline]
1376 pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1377 let mut left = self.to_bits() as i32;
1378 let mut right = other.to_bits() as i32;
1379
1380 // In case of negatives, flip all the bits except the sign
1381 // to achieve a similar layout as two's complement integers
1382 //
1383 // Why does this work? IEEE 754 floats consist of three fields:
1384 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1385 // fields as a whole have the property that their bitwise order is
1386 // equal to the numeric magnitude where the magnitude is defined.
1387 // The magnitude is not normally defined on NaN values, but
1388 // IEEE 754 totalOrder defines the NaN values also to follow the
1389 // bitwise order. This leads to order explained in the doc comment.
1390 // However, the representation of magnitude is the same for negative
1391 // and positive numbers – only the sign bit is different.
1392 // To easily compare the floats as signed integers, we need to
1393 // flip the exponent and mantissa bits in case of negative numbers.
1394 // We effectively convert the numbers to "two's complement" form.
1395 //
1396 // To do the flipping, we construct a mask and XOR against it.
1397 // We branchlessly calculate an "all-ones except for the sign bit"
1398 // mask from negative-signed values: right shifting sign-extends
1399 // the integer, so we "fill" the mask with sign bits, and then
1400 // convert to unsigned to push one more zero bit.
1401 // On positive values, the mask is all zeros, so it's a no-op.
1402 left ^= (((left >> 31) as u32) >> 1) as i32;
1403 right ^= (((right >> 31) as u32) >> 1) as i32;
1404
1405 left.cmp(&right)
1406 }
1407
1408 /// Restrict a value to a certain interval unless it is NaN.
1409 ///
1410 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1411 /// less than `min`. Otherwise this returns `self`.
1412 ///
1413 /// Note that this function returns NaN if the initial value was NaN as
1414 /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1415 /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1416 ///
1417 /// # Panics
1418 ///
1419 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1420 ///
1421 /// # Examples
1422 ///
1423 /// ```
1424 /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1425 /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1426 /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1427 /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1428 ///
1429 /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1430 /// assert!((0.0f32).clamp(-0.0, -0.0) == 0.0);
1431 /// assert!((1.0f32).clamp(-0.0, 0.0) == 0.0);
1432 /// // This is definitely a negative zero.
1433 /// assert!((-1.0f32).clamp(-0.0, 1.0).is_sign_negative());
1434 /// ```
1435 #[must_use = "method returns a new number and does not mutate the original value"]
1436 #[stable(feature = "clamp", since = "1.50.0")]
1437 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1438 #[inline]
1439 #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "Nan is also invalid")]
1440 pub const fn clamp(mut self, min: f32, max: f32) -> f32 {
1441 const_assert!(
1442 min <= max,
1443 "min > max, or either was NaN",
1444 "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1445 min: f32,
1446 max: f32,
1447 );
1448
1449 if self < min {
1450 self = min;
1451 }
1452 if self > max {
1453 self = max;
1454 }
1455 self
1456 }
1457
1458 /// Clamps this number to a symmetric range centered around zero.
1459 ///
1460 /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1461 ///
1462 /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1463 /// explicit about the intent.
1464 ///
1465 /// # Panics
1466 ///
1467 /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1468 ///
1469 /// # Examples
1470 ///
1471 /// ```
1472 /// #![feature(clamp_magnitude)]
1473 /// assert_eq!(5.0f32.clamp_magnitude(3.0), 3.0);
1474 /// assert_eq!((-5.0f32).clamp_magnitude(3.0), -3.0);
1475 /// assert_eq!(2.0f32.clamp_magnitude(3.0), 2.0);
1476 /// assert_eq!((-2.0f32).clamp_magnitude(3.0), -2.0);
1477 /// ```
1478 #[inline]
1479 #[unstable(feature = "clamp_magnitude", issue = "148519")]
1480 #[must_use = "method returns a new number and does not mutate the original value"]
1481 #[expect(clippy::neg_cmp_op_on_partial_ord, reason = "NaN is also invalid")]
1482 pub const fn clamp_magnitude(self, limit: f32) -> f32 {
1483 assert!(limit >= 0.0, "limit must be non-negative and not NaN");
1484 let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1485 self.clamp(-limit, limit)
1486 }
1487
1488 /// Restrict a value to a certain range, unless it is NaN.
1489 ///
1490 /// This is largely equal to `max`, `min`, or `clamp`, depending on whether the range is
1491 /// `min..`, `..=max`, or `min..=max`, respectively. However, unlike `max` and `min`, it will
1492 /// panic if any bound is NaN.
1493 ///
1494 /// Note that this function returns NaN if the initial value was NaN as
1495 /// well.
1496 ///
1497 /// Exclusive ranges are not permitted.
1498 ///
1499 /// # Panics
1500 ///
1501 /// Panics on `min..=max` if `min > max`, or if any bound is NaN.
1502 ///
1503 /// # Examples
1504 ///
1505 /// ```
1506 /// #![feature(clamp_to)]
1507 /// assert_eq!((-3.0f32).clamp_to(-2.0..=1.0), -2.0);
1508 /// assert_eq!(0.0f32.clamp_to(-2.0..=1.0), 0.0);
1509 /// assert_eq!(2.0f32.clamp_to(..=1.0), 1.0);
1510 /// assert_eq!(5.0f32.clamp_to(7.0..), 7.0);
1511 /// assert!(f32::NAN.clamp_to(1.0..=2.0).is_nan());
1512 /// ```
1513 #[must_use]
1514 #[inline]
1515 #[unstable(feature = "clamp_to", issue = "147781")]
1516 pub fn clamp_to<R>(self, range: R) -> Self
1517 where
1518 R: crate::cmp::ClampBounds<Self>,
1519 {
1520 range.clamp(self)
1521 }
1522
1523 /// Computes the absolute value of `self`.
1524 ///
1525 /// This function always returns the precise result.
1526 ///
1527 /// # Examples
1528 ///
1529 /// ```
1530 /// let x = 3.5_f32;
1531 /// let y = -3.5_f32;
1532 ///
1533 /// assert_eq!(x.abs(), x);
1534 /// assert_eq!(y.abs(), -y);
1535 ///
1536 /// assert!(f32::NAN.abs().is_nan());
1537 /// ```
1538 #[must_use = "method returns a new number and does not mutate the original value"]
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1541 #[inline]
1542 pub const fn abs(self) -> f32 {
1543 intrinsics::fabs(self)
1544 }
1545
1546 /// Returns a number that represents the sign of `self`.
1547 ///
1548 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1549 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1550 /// - NaN if the number is NaN
1551 ///
1552 /// # Examples
1553 ///
1554 /// ```
1555 /// let f = 3.5_f32;
1556 ///
1557 /// assert_eq!(f.signum(), 1.0);
1558 /// assert_eq!(f32::NEG_INFINITY.signum(), -1.0);
1559 ///
1560 /// assert!(f32::NAN.signum().is_nan());
1561 /// ```
1562 #[must_use = "method returns a new number and does not mutate the original value"]
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1565 #[inline]
1566 pub const fn signum(self) -> f32 {
1567 if self.is_nan() { Self::NAN } else { 1.0_f32.copysign(self) }
1568 }
1569
1570 /// Returns a number composed of the magnitude of `self` and the sign of
1571 /// `sign`.
1572 ///
1573 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1574 /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1575 /// returned.
1576 ///
1577 /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1578 /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1579 /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1580 /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1581 /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1582 /// info.
1583 ///
1584 /// # Examples
1585 ///
1586 /// ```
1587 /// let f = 3.5_f32;
1588 ///
1589 /// assert_eq!(f.copysign(0.42), 3.5_f32);
1590 /// assert_eq!(f.copysign(-0.42), -3.5_f32);
1591 /// assert_eq!((-f).copysign(0.42), 3.5_f32);
1592 /// assert_eq!((-f).copysign(-0.42), -3.5_f32);
1593 ///
1594 /// assert!(f32::NAN.copysign(1.0).is_nan());
1595 /// ```
1596 #[must_use = "method returns a new number and does not mutate the original value"]
1597 #[inline]
1598 #[stable(feature = "copysign", since = "1.35.0")]
1599 #[rustc_const_stable(feature = "const_float_methods", since = "1.85.0")]
1600 pub const fn copysign(self, sign: f32) -> f32 {
1601 intrinsics::copysignf32(self, sign)
1602 }
1603
1604 /// Float addition 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 #[stable(feature = "float_algebraic", since = "1.98.0")]
1609 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1610 #[inline]
1611 pub const fn algebraic_add(self, rhs: f32) -> f32 {
1612 intrinsics::fadd_algebraic(self, rhs)
1613 }
1614
1615 /// Float subtraction that allows optimizations based on algebraic rules.
1616 ///
1617 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1618 #[must_use = "method returns a new number and does not mutate the original value"]
1619 #[stable(feature = "float_algebraic", since = "1.98.0")]
1620 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1621 #[inline]
1622 pub const fn algebraic_sub(self, rhs: f32) -> f32 {
1623 intrinsics::fsub_algebraic(self, rhs)
1624 }
1625
1626 /// Float multiplication that allows optimizations based on algebraic rules.
1627 ///
1628 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1629 #[must_use = "method returns a new number and does not mutate the original value"]
1630 #[stable(feature = "float_algebraic", since = "1.98.0")]
1631 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1632 #[inline]
1633 pub const fn algebraic_mul(self, rhs: f32) -> f32 {
1634 intrinsics::fmul_algebraic(self, rhs)
1635 }
1636
1637 /// Float division that allows optimizations based on algebraic rules.
1638 ///
1639 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1640 #[must_use = "method returns a new number and does not mutate the original value"]
1641 #[stable(feature = "float_algebraic", since = "1.98.0")]
1642 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1643 #[inline]
1644 pub const fn algebraic_div(self, rhs: f32) -> f32 {
1645 intrinsics::fdiv_algebraic(self, rhs)
1646 }
1647
1648 /// Float remainder that allows optimizations based on algebraic rules.
1649 ///
1650 /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1651 #[must_use = "method returns a new number and does not mutate the original value"]
1652 #[stable(feature = "float_algebraic", since = "1.98.0")]
1653 #[rustc_const_stable(feature = "float_algebraic", since = "1.98.0")]
1654 #[inline]
1655 pub const fn algebraic_rem(self, rhs: f32) -> f32 {
1656 intrinsics::frem_algebraic(self, rhs)
1657 }
1658
1659 /// Computes `(self * a) + b` with nondeterministic rounding.
1660 ///
1661 /// This is similar to [`mul_add`], but the intermediate result may be
1662 /// rounded differently depending on the implementation. The operation is
1663 /// either executed as a single fused multiply-add instruction, or as
1664 /// separate multiply and add instructions.
1665 ///
1666 /// The choice of which one is used is unspecified and non-deterministic:
1667 /// it may vary by target, optimization level, and surrounding code, and
1668 /// even two invocations of this operation with the same inputs may
1669 /// produce different results.
1670 ///
1671 /// # Precision
1672 ///
1673 /// The result of this operation is not guaranteed: it is either the result
1674 /// of [`mul_add`] (one rounding of the infinite-precision result) or of
1675 /// `self * a + b` (two roundings, with an intermediate rounding of the
1676 /// product).
1677 ///
1678 /// # Examples
1679 ///
1680 /// ```
1681 /// #![feature(float_mul_add_relaxed)]
1682 ///
1683 /// // When the fused and unfused operations round differently, either
1684 /// // result may be returned:
1685 /// // - 5.2154064e-10 is the fused result (one rounding)
1686 /// // - 9.313226e-10 is the unfused result (two roundings)
1687 /// let r = 0.1_f32.mul_add_relaxed(0.1_f32, -0.01_f32);
1688 /// assert!(r == 5.2154064e-10 || r == 9.313226e-10);
1689 /// ```
1690 ///
1691 /// [`mul_add`]: ../std/primitive.f32.html#method.mul_add
1692 #[must_use = "method returns a new number and does not mutate the original value"]
1693 #[doc(alias = "fmuladd")]
1694 #[unstable(feature = "float_mul_add_relaxed", issue = "151770")]
1695 #[inline]
1696 pub const fn mul_add_relaxed(self, a: f32, b: f32) -> f32 {
1697 intrinsics::fmuladd(self, a, b)
1698 }
1699
1700 /// Returns `self` if the value is not NaN, otherwise returns `replacement`
1701 /// if `self` is NaN.
1702 ///
1703 /// # Examples
1704 ///
1705 /// ```
1706 /// #![feature(float_nan_to)]
1707 ///
1708 /// let n = f32::NAN;
1709 /// let x = 2.0f32;
1710 /// let y = f32::INFINITY;
1711 ///
1712 /// assert_eq!(n.nan_to(0.0f32), 0.0f32);
1713 /// assert_eq!(x.nan_to(0.0f32), 2.0f32);
1714 /// assert_eq!(y.nan_to(0.0f32), f32::INFINITY);
1715 /// ```
1716 #[must_use = "method returns a new float and does not mutate the original value"]
1717 #[unstable(feature = "float_nan_to", issue = "161248")]
1718 #[rustc_const_unstable(feature = "float_nan_to", issue = "161248")]
1719 #[inline]
1720 pub const fn nan_to(self, replacement: f32) -> f32 {
1721 if self.is_nan() { replacement } else { self }
1722 }
1723}
1724
1725/// Experimental implementations of floating point functions in `core`.
1726///
1727/// _The standalone functions in this module are for testing only.
1728/// They will be stabilized as inherent methods._
1729#[unstable(feature = "core_float_math", issue = "137578")]
1730pub mod math {
1731 use crate::intrinsics;
1732 use crate::num::imp::libm;
1733
1734 /// Experimental version of `floor` in `core`. See [`f32::floor`] for details.
1735 ///
1736 /// # Examples
1737 ///
1738 /// ```
1739 /// #![feature(core_float_math)]
1740 ///
1741 /// use core::f32;
1742 ///
1743 /// let f = 3.7_f32;
1744 /// let g = 3.0_f32;
1745 /// let h = -3.7_f32;
1746 ///
1747 /// assert_eq!(f32::math::floor(f), 3.0);
1748 /// assert_eq!(f32::math::floor(g), 3.0);
1749 /// assert_eq!(f32::math::floor(h), -4.0);
1750 /// ```
1751 ///
1752 /// _This standalone function is for testing only.
1753 /// It will be stabilized as an inherent method._
1754 ///
1755 /// [`f32::floor`]: ../../../std/primitive.f32.html#method.floor
1756 #[inline]
1757 #[unstable(feature = "core_float_math", issue = "137578")]
1758 #[must_use = "method returns a new number and does not mutate the original value"]
1759 pub const fn floor(x: f32) -> f32 {
1760 intrinsics::floor(x)
1761 }
1762
1763 /// Experimental version of `ceil` in `core`. See [`f32::ceil`] for details.
1764 ///
1765 /// # Examples
1766 ///
1767 /// ```
1768 /// #![feature(core_float_math)]
1769 ///
1770 /// use core::f32;
1771 ///
1772 /// let f = 3.01_f32;
1773 /// let g = 4.0_f32;
1774 ///
1775 /// assert_eq!(f32::math::ceil(f), 4.0);
1776 /// assert_eq!(f32::math::ceil(g), 4.0);
1777 /// ```
1778 ///
1779 /// _This standalone function is for testing only.
1780 /// It will be stabilized as an inherent method._
1781 ///
1782 /// [`f32::ceil`]: ../../../std/primitive.f32.html#method.ceil
1783 #[inline]
1784 #[doc(alias = "ceiling")]
1785 #[must_use = "method returns a new number and does not mutate the original value"]
1786 #[unstable(feature = "core_float_math", issue = "137578")]
1787 pub const fn ceil(x: f32) -> f32 {
1788 intrinsics::ceil(x)
1789 }
1790
1791 /// Experimental version of `round` in `core`. See [`f32::round`] for details.
1792 ///
1793 /// # Examples
1794 ///
1795 /// ```
1796 /// #![feature(core_float_math)]
1797 ///
1798 /// use core::f32;
1799 ///
1800 /// let f = 3.3_f32;
1801 /// let g = -3.3_f32;
1802 /// let h = -3.7_f32;
1803 /// let i = 3.5_f32;
1804 /// let j = 4.5_f32;
1805 ///
1806 /// assert_eq!(f32::math::round(f), 3.0);
1807 /// assert_eq!(f32::math::round(g), -3.0);
1808 /// assert_eq!(f32::math::round(h), -4.0);
1809 /// assert_eq!(f32::math::round(i), 4.0);
1810 /// assert_eq!(f32::math::round(j), 5.0);
1811 /// ```
1812 ///
1813 /// _This standalone function is for testing only.
1814 /// It will be stabilized as an inherent method._
1815 ///
1816 /// [`f32::round`]: ../../../std/primitive.f32.html#method.round
1817 #[inline]
1818 #[unstable(feature = "core_float_math", issue = "137578")]
1819 #[must_use = "method returns a new number and does not mutate the original value"]
1820 pub const fn round(x: f32) -> f32 {
1821 intrinsics::round(x)
1822 }
1823
1824 /// Experimental version of `round_ties_even` in `core`. See [`f32::round_ties_even`] for
1825 /// details.
1826 ///
1827 /// # Examples
1828 ///
1829 /// ```
1830 /// #![feature(core_float_math)]
1831 ///
1832 /// use core::f32;
1833 ///
1834 /// let f = 3.3_f32;
1835 /// let g = -3.3_f32;
1836 /// let h = 3.5_f32;
1837 /// let i = 4.5_f32;
1838 ///
1839 /// assert_eq!(f32::math::round_ties_even(f), 3.0);
1840 /// assert_eq!(f32::math::round_ties_even(g), -3.0);
1841 /// assert_eq!(f32::math::round_ties_even(h), 4.0);
1842 /// assert_eq!(f32::math::round_ties_even(i), 4.0);
1843 /// ```
1844 ///
1845 /// _This standalone function is for testing only.
1846 /// It will be stabilized as an inherent method._
1847 ///
1848 /// [`f32::round_ties_even`]: ../../../std/primitive.f32.html#method.round_ties_even
1849 #[inline]
1850 #[unstable(feature = "core_float_math", issue = "137578")]
1851 #[must_use = "method returns a new number and does not mutate the original value"]
1852 pub const fn round_ties_even(x: f32) -> f32 {
1853 intrinsics::round_ties_even(x)
1854 }
1855
1856 /// Experimental version of `trunc` in `core`. See [`f32::trunc`] for details.
1857 ///
1858 /// # Examples
1859 ///
1860 /// ```
1861 /// #![feature(core_float_math)]
1862 ///
1863 /// use core::f32;
1864 ///
1865 /// let f = 3.7_f32;
1866 /// let g = 3.0_f32;
1867 /// let h = -3.7_f32;
1868 ///
1869 /// assert_eq!(f32::math::trunc(f), 3.0);
1870 /// assert_eq!(f32::math::trunc(g), 3.0);
1871 /// assert_eq!(f32::math::trunc(h), -3.0);
1872 /// ```
1873 ///
1874 /// _This standalone function is for testing only.
1875 /// It will be stabilized as an inherent method._
1876 ///
1877 /// [`f32::trunc`]: ../../../std/primitive.f32.html#method.trunc
1878 #[inline]
1879 #[doc(alias = "truncate")]
1880 #[must_use = "method returns a new number and does not mutate the original value"]
1881 #[unstable(feature = "core_float_math", issue = "137578")]
1882 pub const fn trunc(x: f32) -> f32 {
1883 intrinsics::trunc(x)
1884 }
1885
1886 /// Experimental version of `fract` in `core`. See [`f32::fract`] for details.
1887 ///
1888 /// # Examples
1889 ///
1890 /// ```
1891 /// #![feature(core_float_math)]
1892 ///
1893 /// use core::f32;
1894 ///
1895 /// let x = 3.6_f32;
1896 /// let y = -3.6_f32;
1897 /// let abs_difference_x = (f32::math::fract(x) - 0.6).abs();
1898 /// let abs_difference_y = (f32::math::fract(y) - (-0.6)).abs();
1899 ///
1900 /// assert!(abs_difference_x <= f32::EPSILON);
1901 /// assert!(abs_difference_y <= f32::EPSILON);
1902 /// ```
1903 ///
1904 /// _This standalone function is for testing only.
1905 /// It will be stabilized as an inherent method._
1906 ///
1907 /// [`f32::fract`]: ../../../std/primitive.f32.html#method.fract
1908 #[inline]
1909 #[unstable(feature = "core_float_math", issue = "137578")]
1910 #[must_use = "method returns a new number and does not mutate the original value"]
1911 pub const fn fract(x: f32) -> f32 {
1912 x - trunc(x)
1913 }
1914
1915 /// Experimental version of `mul_add` in `core`. See [`f32::mul_add`] for details.
1916 ///
1917 /// # Examples
1918 ///
1919 /// ```
1920 /// # #![allow(unused_features)]
1921 /// #![feature(core_float_math)]
1922 ///
1923 /// # // FIXME(#140515): mingw has an incorrect fma
1924 /// # // https://sourceforge.net/p/mingw-w64/bugs/848/
1925 /// # #[cfg(all(target_os = "windows", target_env = "gnu", not(target_abi = "llvm")))] {
1926 /// use core::f32;
1927 ///
1928 /// let m = 10.0_f32;
1929 /// let x = 4.0_f32;
1930 /// let b = 60.0_f32;
1931 ///
1932 /// assert_eq!(f32::math::mul_add(m, x, b), 100.0);
1933 /// assert_eq!(m * x + b, 100.0);
1934 ///
1935 /// let one_plus_eps = 1.0_f32 + f32::EPSILON;
1936 /// let one_minus_eps = 1.0_f32 - f32::EPSILON;
1937 /// let minus_one = -1.0_f32;
1938 ///
1939 /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1940 /// assert_eq!(
1941 /// f32::math::mul_add(one_plus_eps, one_minus_eps, minus_one),
1942 /// -f32::EPSILON * f32::EPSILON
1943 /// );
1944 /// // Different rounding with the non-fused multiply and add.
1945 /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1946 /// # }
1947 /// ```
1948 ///
1949 /// _This standalone function is for testing only.
1950 /// It will be stabilized as an inherent method._
1951 ///
1952 /// [`f32::mul_add`]: ../../../std/primitive.f32.html#method.mul_add
1953 #[inline]
1954 #[doc(alias = "fmaf", alias = "fusedMultiplyAdd")]
1955 #[must_use = "method returns a new number and does not mutate the original value"]
1956 #[unstable(feature = "core_float_math", issue = "137578")]
1957 pub const fn mul_add(x: f32, y: f32, z: f32) -> f32 {
1958 intrinsics::fma(x, y, z)
1959 }
1960
1961 /// Experimental version of `div_euclid` in `core`. See [`f32::div_euclid`] for details.
1962 ///
1963 /// # Examples
1964 ///
1965 /// ```
1966 /// #![feature(core_float_math)]
1967 ///
1968 /// use core::f32;
1969 ///
1970 /// let a: f32 = 7.0;
1971 /// let b = 4.0;
1972 /// assert_eq!(f32::math::div_euclid(a, b), 1.0); // 7.0 > 4.0 * 1.0
1973 /// assert_eq!(f32::math::div_euclid(-a, b), -2.0); // -7.0 >= 4.0 * -2.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 /// ```
1977 ///
1978 /// _This standalone function is for testing only.
1979 /// It will be stabilized as an inherent method._
1980 ///
1981 /// [`f32::div_euclid`]: ../../../std/primitive.f32.html#method.div_euclid
1982 #[inline]
1983 #[unstable(feature = "core_float_math", issue = "137578")]
1984 #[must_use = "method returns a new number and does not mutate the original value"]
1985 pub fn div_euclid(x: f32, rhs: f32) -> f32 {
1986 let q = trunc(x / rhs);
1987 if x % rhs < 0.0 {
1988 return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1989 }
1990 q
1991 }
1992
1993 /// Experimental version of `rem_euclid` in `core`. See [`f32::rem_euclid`] for details.
1994 ///
1995 /// # Examples
1996 ///
1997 /// ```
1998 /// #![feature(core_float_math)]
1999 ///
2000 /// use core::f32;
2001 ///
2002 /// let a: f32 = 7.0;
2003 /// let b = 4.0;
2004 /// assert_eq!(f32::math::rem_euclid(a, b), 3.0);
2005 /// assert_eq!(f32::math::rem_euclid(-a, b), 1.0);
2006 /// assert_eq!(f32::math::rem_euclid(a, -b), 3.0);
2007 /// assert_eq!(f32::math::rem_euclid(-a, -b), 1.0);
2008 /// // limitation due to round-off error
2009 /// assert!(f32::math::rem_euclid(-f32::EPSILON, 3.0) != 0.0);
2010 /// ```
2011 ///
2012 /// _This standalone function is for testing only.
2013 /// It will be stabilized as an inherent method._
2014 ///
2015 /// [`f32::rem_euclid`]: ../../../std/primitive.f32.html#method.rem_euclid
2016 #[inline]
2017 #[doc(alias = "modulo", alias = "mod")]
2018 #[unstable(feature = "core_float_math", issue = "137578")]
2019 #[must_use = "method returns a new number and does not mutate the original value"]
2020 pub fn rem_euclid(x: f32, rhs: f32) -> f32 {
2021 let r = x % rhs;
2022 if r < 0.0 { r + rhs.abs() } else { r }
2023 }
2024
2025 /// Experimental version of `powi` in `core`. See [`f32::powi`] for details.
2026 ///
2027 /// # Examples
2028 ///
2029 /// ```
2030 /// #![feature(core_float_math)]
2031 ///
2032 /// use core::f32;
2033 ///
2034 /// let x = 2.0_f32;
2035 /// let abs_difference = (f32::math::powi(x, 2) - (x * x)).abs();
2036 /// assert!(abs_difference <= 1e-5);
2037 ///
2038 /// assert_eq!(f32::math::powi(f32::NAN, 0), 1.0);
2039 /// ```
2040 ///
2041 /// _This standalone function is for testing only.
2042 /// It will be stabilized as an inherent method._
2043 ///
2044 /// [`f32::powi`]: ../../../std/primitive.f32.html#method.powi
2045 #[inline]
2046 #[must_use = "method returns a new number and does not mutate the original value"]
2047 #[unstable(feature = "core_float_math", issue = "137578")]
2048 pub fn powi(x: f32, n: i32) -> f32 {
2049 intrinsics::powi(x, n)
2050 }
2051
2052 /// Experimental version of `sqrt` in `core`. See [`f32::sqrt`] for details.
2053 ///
2054 /// # Examples
2055 ///
2056 /// ```
2057 /// #![feature(core_float_math)]
2058 ///
2059 /// use core::f32;
2060 ///
2061 /// let positive = 4.0_f32;
2062 /// let negative = -4.0_f32;
2063 /// let negative_zero = -0.0_f32;
2064 ///
2065 /// assert_eq!(f32::math::sqrt(positive), 2.0);
2066 /// assert!(f32::math::sqrt(negative).is_nan());
2067 /// assert_eq!(f32::math::sqrt(negative_zero), negative_zero);
2068 /// ```
2069 ///
2070 /// _This standalone function is for testing only.
2071 /// It will be stabilized as an inherent method._
2072 ///
2073 /// [`f32::sqrt`]: ../../../std/primitive.f32.html#method.sqrt
2074 #[inline]
2075 #[doc(alias = "squareRoot")]
2076 #[unstable(feature = "core_float_math", issue = "137578")]
2077 #[must_use = "method returns a new number and does not mutate the original value"]
2078 pub fn sqrt(x: f32) -> f32 {
2079 intrinsics::sqrt(x)
2080 }
2081
2082 /// Experimental version of `abs_sub` in `core`. See [`f32::abs_sub`] for details.
2083 ///
2084 /// # Examples
2085 ///
2086 /// ```
2087 /// #![feature(core_float_math)]
2088 ///
2089 /// use core::f32;
2090 ///
2091 /// let x = 3.0f32;
2092 /// let y = -3.0f32;
2093 ///
2094 /// let abs_difference_x = (f32::math::abs_sub(x, 1.0) - 2.0).abs();
2095 /// let abs_difference_y = (f32::math::abs_sub(y, 1.0) - 0.0).abs();
2096 ///
2097 /// assert!(abs_difference_x <= 1e-6);
2098 /// assert!(abs_difference_y <= 1e-6);
2099 /// ```
2100 ///
2101 /// _This standalone function is for testing only.
2102 /// It will be stabilized as an inherent method._
2103 ///
2104 /// [`f32::abs_sub`]: ../../../std/primitive.f32.html#method.abs_sub
2105 #[inline]
2106 #[stable(feature = "rust1", since = "1.0.0")]
2107 #[deprecated(
2108 since = "1.10.0",
2109 note = "you probably meant `(self - other).abs()`: \
2110 this operation is `(self - other).max(0.0)` \
2111 except that `abs_sub` also propagates NaNs (also \
2112 known as `fdimf` in C). If you truly need the positive \
2113 difference, consider using that expression or the C function \
2114 `fdimf`, depending on how you wish to handle NaN (please consider \
2115 filing an issue describing your use-case too)."
2116 )]
2117 #[must_use = "method returns a new number and does not mutate the original value"]
2118 pub fn abs_sub(x: f32, other: f32) -> f32 {
2119 libm::fdimf(x, other)
2120 }
2121
2122 /// Experimental version of `cbrt` in `core`. See [`f32::cbrt`] for details.
2123 ///
2124 /// # Unspecified precision
2125 ///
2126 /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and
2127 /// can even differ within the same execution from one invocation to the next.
2128 /// This function currently corresponds to the `cbrtf` from libc on Unix
2129 /// and Windows. Note that this might change in the future.
2130 ///
2131 /// # Examples
2132 ///
2133 /// ```
2134 /// #![feature(core_float_math)]
2135 ///
2136 /// use core::f32;
2137 ///
2138 /// let x = 8.0f32;
2139 ///
2140 /// // x^(1/3) - 2 == 0
2141 /// let abs_difference = (f32::math::cbrt(x) - 2.0).abs();
2142 ///
2143 /// assert!(abs_difference <= 1e-6);
2144 /// ```
2145 ///
2146 /// _This standalone function is for testing only.
2147 /// It will be stabilized as an inherent method._
2148 ///
2149 /// [`f32::cbrt`]: ../../../std/primitive.f32.html#method.cbrt
2150 #[inline]
2151 #[must_use = "method returns a new number and does not mutate the original value"]
2152 #[unstable(feature = "core_float_math", issue = "137578")]
2153 pub fn cbrt(x: f32) -> f32 {
2154 libm::cbrtf(x)
2155 }
2156}