]> git.proxmox.com Git - rustc.git/blame - library/core/src/num/f32.rs
New upstream version 1.77.2+dfsg1
[rustc.git] / library / core / src / num / f32.rs
CommitLineData
f2b60f7d 1//! Constants for the `f32` single-precision floating point type.
ff7c6d11 2//!
6a06907d 3//! *[See also the `f32` primitive type][f32].*
94b46f34
XL
4//!
5//! Mathematically significant numbers are provided in the `consts` sub-module.
74b04a01 6//!
5869c6ff
XL
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.
1a4d82fc 11
85aaf69f 12#![stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 13
60c5eb7d 14use crate::convert::FloatToInt;
dc9dc135
XL
15#[cfg(not(test))]
16use crate::intrinsics;
48663c56
XL
17use crate::mem;
18use crate::num::FpCategory;
1a4d82fc 19
5bcae85e 20/// The radix or base of the internal representation of `f32`.
6a06907d 21/// Use [`f32::RADIX`] instead.
f9f354fc
XL
22///
23/// # Examples
24///
25/// ```rust
26/// // deprecated way
5869c6ff 27/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
28/// let r = std::f32::RADIX;
29///
30/// // intended way
31/// let r = f32::RADIX;
32/// ```
c34b1796 33#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 34#[deprecated(since = "TBD", note = "replaced by the `RADIX` associated constant on `f32`")]
74b04a01 35pub const RADIX: u32 = f32::RADIX;
1a4d82fc 36
5bcae85e 37/// Number of significant digits in base 2.
6a06907d 38/// Use [`f32::MANTISSA_DIGITS`] instead.
f9f354fc
XL
39///
40/// # Examples
41///
42/// ```rust
43/// // deprecated way
5869c6ff 44/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
45/// let d = std::f32::MANTISSA_DIGITS;
46///
47/// // intended way
48/// let d = f32::MANTISSA_DIGITS;
49/// ```
c34b1796 50#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 51#[deprecated(
5869c6ff 52 since = "TBD",
04454e1e 53 note = "replaced by the `MANTISSA_DIGITS` associated constant on `f32`"
5869c6ff 54)]
74b04a01 55pub const MANTISSA_DIGITS: u32 = f32::MANTISSA_DIGITS;
f9f354fc 56
5bcae85e 57/// Approximate number of significant digits in base 10.
6a06907d 58/// Use [`f32::DIGITS`] instead.
f9f354fc
XL
59///
60/// # Examples
61///
62/// ```rust
63/// // deprecated way
5869c6ff 64/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
65/// let d = std::f32::DIGITS;
66///
67/// // intended way
68/// let d = f32::DIGITS;
69/// ```
c34b1796 70#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 71#[deprecated(since = "TBD", note = "replaced by the `DIGITS` associated constant on `f32`")]
74b04a01 72pub const DIGITS: u32 = f32::DIGITS;
1a4d82fc 73
94b46f34 74/// [Machine epsilon] value for `f32`.
6a06907d 75/// Use [`f32::EPSILON`] instead.
94b46f34 76///
60c5eb7d 77/// This is the difference between `1.0` and the next larger representable number.
94b46f34
XL
78///
79/// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
f9f354fc
XL
80///
81/// # Examples
82///
83/// ```rust
84/// // deprecated way
5869c6ff 85/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
86/// let e = std::f32::EPSILON;
87///
88/// // intended way
89/// let e = f32::EPSILON;
90/// ```
85aaf69f 91#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 92#[deprecated(since = "TBD", note = "replaced by the `EPSILON` associated constant on `f32`")]
74b04a01 93pub const EPSILON: f32 = f32::EPSILON;
1a4d82fc 94
5bcae85e 95/// Smallest finite `f32` value.
6a06907d 96/// Use [`f32::MIN`] instead.
f9f354fc
XL
97///
98/// # Examples
99///
100/// ```rust
101/// // deprecated way
5869c6ff 102/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
103/// let min = std::f32::MIN;
104///
105/// // intended way
106/// let min = f32::MIN;
107/// ```
85aaf69f 108#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 109#[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on `f32`")]
74b04a01 110pub const MIN: f32 = f32::MIN;
f9f354fc 111
5bcae85e 112/// Smallest positive normal `f32` value.
6a06907d 113/// Use [`f32::MIN_POSITIVE`] instead.
f9f354fc
XL
114///
115/// # Examples
116///
117/// ```rust
118/// // deprecated way
5869c6ff 119/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
120/// let min = std::f32::MIN_POSITIVE;
121///
122/// // intended way
123/// let min = f32::MIN_POSITIVE;
124/// ```
85aaf69f 125#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 126#[deprecated(since = "TBD", note = "replaced by the `MIN_POSITIVE` associated constant on `f32`")]
74b04a01 127pub const MIN_POSITIVE: f32 = f32::MIN_POSITIVE;
f9f354fc 128
5bcae85e 129/// Largest finite `f32` value.
6a06907d 130/// Use [`f32::MAX`] instead.
f9f354fc
XL
131///
132/// # Examples
133///
134/// ```rust
135/// // deprecated way
5869c6ff 136/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
137/// let max = std::f32::MAX;
138///
139/// // intended way
140/// let max = f32::MAX;
141/// ```
85aaf69f 142#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 143#[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on `f32`")]
74b04a01 144pub const MAX: f32 = f32::MAX;
85aaf69f 145
5bcae85e 146/// One greater than the minimum possible normal power of 2 exponent.
6a06907d 147/// Use [`f32::MIN_EXP`] instead.
f9f354fc
XL
148///
149/// # Examples
150///
151/// ```rust
152/// // deprecated way
5869c6ff 153/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
154/// let min = std::f32::MIN_EXP;
155///
156/// // intended way
157/// let min = f32::MIN_EXP;
158/// ```
c34b1796 159#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 160#[deprecated(since = "TBD", note = "replaced by the `MIN_EXP` associated constant on `f32`")]
74b04a01 161pub const MIN_EXP: i32 = f32::MIN_EXP;
f9f354fc 162
5bcae85e 163/// Maximum possible power of 2 exponent.
6a06907d 164/// Use [`f32::MAX_EXP`] instead.
f9f354fc
XL
165///
166/// # Examples
167///
168/// ```rust
169/// // deprecated way
5869c6ff 170/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
171/// let max = std::f32::MAX_EXP;
172///
173/// // intended way
174/// let max = f32::MAX_EXP;
175/// ```
c34b1796 176#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 177#[deprecated(since = "TBD", note = "replaced by the `MAX_EXP` associated constant on `f32`")]
74b04a01 178pub const MAX_EXP: i32 = f32::MAX_EXP;
1a4d82fc 179
5bcae85e 180/// Minimum possible normal power of 10 exponent.
6a06907d 181/// Use [`f32::MIN_10_EXP`] instead.
f9f354fc
XL
182///
183/// # Examples
184///
185/// ```rust
186/// // deprecated way
5869c6ff 187/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
188/// let min = std::f32::MIN_10_EXP;
189///
190/// // intended way
191/// let min = f32::MIN_10_EXP;
192/// ```
c34b1796 193#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 194#[deprecated(since = "TBD", note = "replaced by the `MIN_10_EXP` associated constant on `f32`")]
74b04a01 195pub const MIN_10_EXP: i32 = f32::MIN_10_EXP;
f9f354fc 196
5bcae85e 197/// Maximum possible power of 10 exponent.
6a06907d 198/// Use [`f32::MAX_10_EXP`] instead.
f9f354fc
XL
199///
200/// # Examples
201///
202/// ```rust
203/// // deprecated way
5869c6ff 204/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
205/// let max = std::f32::MAX_10_EXP;
206///
207/// // intended way
208/// let max = f32::MAX_10_EXP;
209/// ```
c34b1796 210#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 211#[deprecated(since = "TBD", note = "replaced by the `MAX_10_EXP` associated constant on `f32`")]
74b04a01 212pub const MAX_10_EXP: i32 = f32::MAX_10_EXP;
1a4d82fc 213
5bcae85e 214/// Not a Number (NaN).
6a06907d 215/// Use [`f32::NAN`] instead.
f9f354fc
XL
216///
217/// # Examples
218///
219/// ```rust
220/// // deprecated way
5869c6ff 221/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
222/// let nan = std::f32::NAN;
223///
224/// // intended way
225/// let nan = f32::NAN;
226/// ```
85aaf69f 227#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 228#[deprecated(since = "TBD", note = "replaced by the `NAN` associated constant on `f32`")]
74b04a01 229pub const NAN: f32 = f32::NAN;
f9f354fc 230
5bcae85e 231/// Infinity (∞).
6a06907d 232/// Use [`f32::INFINITY`] instead.
f9f354fc
XL
233///
234/// # Examples
235///
236/// ```rust
237/// // deprecated way
5869c6ff 238/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
239/// let inf = std::f32::INFINITY;
240///
241/// // intended way
242/// let inf = f32::INFINITY;
243/// ```
85aaf69f 244#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 245#[deprecated(since = "TBD", note = "replaced by the `INFINITY` associated constant on `f32`")]
74b04a01 246pub const INFINITY: f32 = f32::INFINITY;
f9f354fc 247
dfeec247 248/// Negative infinity (−∞).
6a06907d 249/// Use [`f32::NEG_INFINITY`] instead.
f9f354fc
XL
250///
251/// # Examples
252///
253/// ```rust
254/// // deprecated way
5869c6ff 255/// # #[allow(deprecated, deprecated_in_future)]
f9f354fc
XL
256/// let ninf = std::f32::NEG_INFINITY;
257///
258/// // intended way
259/// let ninf = f32::NEG_INFINITY;
260/// ```
85aaf69f 261#[stable(feature = "rust1", since = "1.0.0")]
04454e1e 262#[deprecated(since = "TBD", note = "replaced by the `NEG_INFINITY` associated constant on `f32`")]
74b04a01 263pub const NEG_INFINITY: f32 = f32::NEG_INFINITY;
1a4d82fc 264
b039eaaf 265/// Basic mathematical constants.
c34b1796 266#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
267pub mod consts {
268 // FIXME: replace with mathematical constants from cmath.
269
5bcae85e 270 /// Archimedes' constant (π)
c34b1796 271 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
272 pub const PI: f32 = 3.14159265358979323846264338327950288_f32;
273
60c5eb7d
XL
274 /// The full circle constant (τ)
275 ///
276 /// Equal to 2π.
3dfed10e 277 #[stable(feature = "tau_constant", since = "1.47.0")]
60c5eb7d
XL
278 pub const TAU: f32 = 6.28318530717958647692528676655900577_f32;
279
781aab86
FG
280 /// The golden ratio (φ)
281 #[unstable(feature = "more_float_constants", issue = "103883")]
282 pub const PHI: f32 = 1.618033988749894848204586834365638118_f32;
283
284 /// The Euler-Mascheroni constant (γ)
285 #[unstable(feature = "more_float_constants", issue = "103883")]
286 pub const EGAMMA: f32 = 0.577215664901532860606512090082402431_f32;
287
5bcae85e 288 /// π/2
c34b1796 289 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
290 pub const FRAC_PI_2: f32 = 1.57079632679489661923132169163975144_f32;
291
5bcae85e 292 /// π/3
c34b1796 293 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
294 pub const FRAC_PI_3: f32 = 1.04719755119659774615421446109316763_f32;
295
5bcae85e 296 /// π/4
c34b1796 297 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
298 pub const FRAC_PI_4: f32 = 0.785398163397448309615660845819875721_f32;
299
5bcae85e 300 /// π/6
c34b1796 301 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
302 pub const FRAC_PI_6: f32 = 0.52359877559829887307710723054658381_f32;
303
5bcae85e 304 /// π/8
c34b1796 305 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
306 pub const FRAC_PI_8: f32 = 0.39269908169872415480783042290993786_f32;
307
5bcae85e 308 /// 1/π
c34b1796 309 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
310 pub const FRAC_1_PI: f32 = 0.318309886183790671537767526745028724_f32;
311
781aab86
FG
312 /// 1/sqrt(π)
313 #[unstable(feature = "more_float_constants", issue = "103883")]
314 pub const FRAC_1_SQRT_PI: f32 = 0.564189583547756286948079451560772586_f32;
315
5bcae85e 316 /// 2/π
c34b1796 317 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
318 pub const FRAC_2_PI: f32 = 0.636619772367581343075535053490057448_f32;
319
5bcae85e 320 /// 2/sqrt(π)
c34b1796
AL
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub const FRAC_2_SQRT_PI: f32 = 1.12837916709551257389615890312154517_f32;
323
5bcae85e 324 /// sqrt(2)
c34b1796
AL
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub const SQRT_2: f32 = 1.41421356237309504880168872420969808_f32;
327
5bcae85e 328 /// 1/sqrt(2)
c34b1796
AL
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub const FRAC_1_SQRT_2: f32 = 0.707106781186547524400844362104849039_f32;
331
781aab86
FG
332 /// sqrt(3)
333 #[unstable(feature = "more_float_constants", issue = "103883")]
334 pub const SQRT_3: f32 = 1.732050807568877293527446341505872367_f32;
335
336 /// 1/sqrt(3)
337 #[unstable(feature = "more_float_constants", issue = "103883")]
338 pub const FRAC_1_SQRT_3: f32 = 0.577350269189625764509148780501957456_f32;
339
5bcae85e 340 /// Euler's number (e)
c34b1796 341 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
342 pub const E: f32 = 2.71828182845904523536028747135266250_f32;
343
5bcae85e 344 /// log<sub>2</sub>(e)
c34b1796 345 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
346 pub const LOG2_E: f32 = 1.44269504088896340735992468100189214_f32;
347
94b46f34 348 /// log<sub>2</sub>(10)
74b04a01 349 #[stable(feature = "extra_log_consts", since = "1.43.0")]
94b46f34
XL
350 pub const LOG2_10: f32 = 3.32192809488736234787031942948939018_f32;
351
5bcae85e 352 /// log<sub>10</sub>(e)
c34b1796 353 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
354 pub const LOG10_E: f32 = 0.434294481903251827651128918916605082_f32;
355
94b46f34 356 /// log<sub>10</sub>(2)
74b04a01 357 #[stable(feature = "extra_log_consts", since = "1.43.0")]
94b46f34
XL
358 pub const LOG10_2: f32 = 0.301029995663981195213738894724493027_f32;
359
5bcae85e 360 /// ln(2)
c34b1796 361 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
362 pub const LN_2: f32 = 0.693147180559945309417232121458176568_f32;
363
5bcae85e 364 /// ln(10)
c34b1796 365 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
366 pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32;
367}
368
94b46f34
XL
369#[cfg(not(test))]
370impl f32 {
74b04a01
XL
371 /// The radix or base of the internal representation of `f32`.
372 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
373 pub const RADIX: u32 = 2;
374
375 /// Number of significant digits in base 2.
376 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
377 pub const MANTISSA_DIGITS: u32 = 24;
378
379 /// Approximate number of significant digits in base 10.
ed00b5ec
FG
380 ///
381 /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
382 /// significant digits can be converted to `f32` and back without loss.
383 ///
384 /// Equal to floor(log<sub>10</sub>&nbsp;2<sup>[`MANTISSA_DIGITS`]&nbsp;&minus;&nbsp;1</sup>).
385 ///
386 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
74b04a01
XL
387 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
388 pub const DIGITS: u32 = 6;
389
390 /// [Machine epsilon] value for `f32`.
391 ///
392 /// This is the difference between `1.0` and the next larger representable number.
393 ///
ed00b5ec
FG
394 /// Equal to 2<sup>1&nbsp;&minus;&nbsp;[`MANTISSA_DIGITS`]</sup>.
395 ///
74b04a01 396 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
ed00b5ec 397 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
74b04a01
XL
398 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
399 pub const EPSILON: f32 = 1.19209290e-07_f32;
400
401 /// Smallest finite `f32` value.
ed00b5ec
FG
402 ///
403 /// Equal to &minus;[`MAX`].
404 ///
405 /// [`MAX`]: f32::MAX
74b04a01
XL
406 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
407 pub const MIN: f32 = -3.40282347e+38_f32;
408 /// Smallest positive normal `f32` value.
ed00b5ec
FG
409 ///
410 /// Equal to 2<sup>[`MIN_EXP`]&nbsp;&minus;&nbsp;1</sup>.
411 ///
412 /// [`MIN_EXP`]: f32::MIN_EXP
74b04a01
XL
413 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
414 pub const MIN_POSITIVE: f32 = 1.17549435e-38_f32;
415 /// Largest finite `f32` value.
ed00b5ec
FG
416 ///
417 /// Equal to
418 /// (1&nbsp;&minus;&nbsp;2<sup>&minus;[`MANTISSA_DIGITS`]</sup>)&nbsp;2<sup>[`MAX_EXP`]</sup>.
419 ///
420 /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS
421 /// [`MAX_EXP`]: f32::MAX_EXP
74b04a01
XL
422 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
423 pub const MAX: f32 = 3.40282347e+38_f32;
424
425 /// One greater than the minimum possible normal power of 2 exponent.
ed00b5ec
FG
426 ///
427 /// If <i>x</i>&nbsp;=&nbsp;`MIN_EXP`, then normal numbers
428 /// ≥&nbsp;0.5&nbsp;×&nbsp;2<sup><i>x</i></sup>.
74b04a01
XL
429 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
430 pub const MIN_EXP: i32 = -125;
431 /// Maximum possible power of 2 exponent.
ed00b5ec
FG
432 ///
433 /// If <i>x</i>&nbsp;=&nbsp;`MAX_EXP`, then normal numbers
434 /// &lt;&nbsp;1&nbsp;×&nbsp;2<sup><i>x</i></sup>.
74b04a01
XL
435 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
436 pub const MAX_EXP: i32 = 128;
437
ed00b5ec
FG
438 /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
439 ///
440 /// Equal to ceil(log<sub>10</sub>&nbsp;[`MIN_POSITIVE`]).
441 ///
442 /// [`MIN_POSITIVE`]: f32::MIN_POSITIVE
74b04a01
XL
443 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
444 pub const MIN_10_EXP: i32 = -37;
ed00b5ec
FG
445 /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
446 ///
447 /// Equal to floor(log<sub>10</sub>&nbsp;[`MAX`]).
448 ///
449 /// [`MAX`]: f32::MAX
74b04a01
XL
450 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
451 pub const MAX_10_EXP: i32 = 38;
452
453 /// Not a Number (NaN).
04454e1e 454 ///
f2b60f7d 455 /// Note that IEEE 754 doesn't define just a single NaN value;
04454e1e
FG
456 /// a plethora of bit patterns are considered to be NaN.
457 /// Furthermore, the standard makes a difference
458 /// between a "signaling" and a "quiet" NaN,
459 /// and allows inspecting its "payload" (the unspecified bits in the bit pattern).
460 /// This constant isn't guaranteed to equal to any specific NaN bitpattern,
461 /// and the stability of its representation over Rust versions
462 /// and target platforms isn't guaranteed.
74b04a01 463 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
fe692bf9 464 #[rustc_diagnostic_item = "f32_nan"]
74b04a01
XL
465 pub const NAN: f32 = 0.0_f32 / 0.0_f32;
466 /// Infinity (∞).
467 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
468 pub const INFINITY: f32 = 1.0_f32 / 0.0_f32;
f9f354fc 469 /// Negative infinity (−∞).
74b04a01
XL
470 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
471 pub const NEG_INFINITY: f32 = -1.0_f32 / 0.0_f32;
472
04454e1e 473 /// Returns `true` if this value is NaN.
83c7162d
XL
474 ///
475 /// ```
83c7162d
XL
476 /// let nan = f32::NAN;
477 /// let f = 7.0_f32;
478 ///
479 /// assert!(nan.is_nan());
480 /// assert!(!f.is_nan());
481 /// ```
c295e0f8 482 #[must_use]
83c7162d 483 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 484 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 485 #[inline]
3dfed10e 486 pub const fn is_nan(self) -> bool {
94b46f34
XL
487 self != self
488 }
83c7162d 489
9c376795 490 // FIXME(#50145): `abs` is publicly unavailable in core due to
0731742a
XL
491 // concerns about portability, so this implementation is for
492 // private use internally.
493 #[inline]
3dfed10e 494 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
3c0e092e 495 pub(crate) const fn abs_private(self) -> f32 {
04454e1e
FG
496 // SAFETY: This transmutation is fine. Probably. For the reasons std is using it.
497 unsafe { mem::transmute::<u32, f32>(mem::transmute::<f32, u32>(self) & 0x7fff_ffff) }
0731742a
XL
498 }
499
9fa01778
XL
500 /// Returns `true` if this value is positive infinity or negative infinity, and
501 /// `false` otherwise.
83c7162d
XL
502 ///
503 /// ```
83c7162d
XL
504 /// let f = 7.0f32;
505 /// let inf = f32::INFINITY;
506 /// let neg_inf = f32::NEG_INFINITY;
507 /// let nan = f32::NAN;
508 ///
509 /// assert!(!f.is_infinite());
510 /// assert!(!nan.is_infinite());
511 ///
512 /// assert!(inf.is_infinite());
513 /// assert!(neg_inf.is_infinite());
514 /// ```
c295e0f8 515 #[must_use]
83c7162d 516 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 517 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 518 #[inline]
3dfed10e 519 pub const fn is_infinite(self) -> bool {
04454e1e
FG
520 // Getting clever with transmutation can result in incorrect answers on some FPUs
521 // FIXME: alter the Rust <-> Rust calling convention to prevent this problem.
522 // See https://github.com/rust-lang/rust/issues/72327
523 (self == f32::INFINITY) | (self == f32::NEG_INFINITY)
94b46f34 524 }
83c7162d 525
04454e1e 526 /// Returns `true` if this number is neither infinite nor NaN.
83c7162d
XL
527 ///
528 /// ```
83c7162d
XL
529 /// let f = 7.0f32;
530 /// let inf = f32::INFINITY;
531 /// let neg_inf = f32::NEG_INFINITY;
532 /// let nan = f32::NAN;
533 ///
534 /// assert!(f.is_finite());
535 ///
536 /// assert!(!nan.is_finite());
537 /// assert!(!inf.is_finite());
538 /// assert!(!neg_inf.is_finite());
539 /// ```
c295e0f8 540 #[must_use]
83c7162d 541 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 542 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 543 #[inline]
3dfed10e 544 pub const fn is_finite(self) -> bool {
0731742a
XL
545 // There's no need to handle NaN separately: if self is NaN,
546 // the comparison is not true, exactly as desired.
f9f354fc 547 self.abs_private() < Self::INFINITY
94b46f34 548 }
83c7162d 549
fc512014
XL
550 /// Returns `true` if the number is [subnormal].
551 ///
552 /// ```
fc512014
XL
553 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
554 /// let max = f32::MAX;
555 /// let lower_than_min = 1.0e-40_f32;
556 /// let zero = 0.0_f32;
557 ///
558 /// assert!(!min.is_subnormal());
559 /// assert!(!max.is_subnormal());
560 ///
561 /// assert!(!zero.is_subnormal());
562 /// assert!(!f32::NAN.is_subnormal());
563 /// assert!(!f32::INFINITY.is_subnormal());
564 /// // Values between `0` and `min` are Subnormal.
565 /// assert!(lower_than_min.is_subnormal());
566 /// ```
567 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
c295e0f8 568 #[must_use]
cdc7bbd5 569 #[stable(feature = "is_subnormal", since = "1.53.0")]
fc512014
XL
570 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
571 #[inline]
572 pub const fn is_subnormal(self) -> bool {
573 matches!(self.classify(), FpCategory::Subnormal)
574 }
575
83c7162d 576 /// Returns `true` if the number is neither zero, infinite,
04454e1e 577 /// [subnormal], or NaN.
83c7162d
XL
578 ///
579 /// ```
83c7162d
XL
580 /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
581 /// let max = f32::MAX;
582 /// let lower_than_min = 1.0e-40_f32;
583 /// let zero = 0.0_f32;
584 ///
585 /// assert!(min.is_normal());
586 /// assert!(max.is_normal());
587 ///
588 /// assert!(!zero.is_normal());
589 /// assert!(!f32::NAN.is_normal());
590 /// assert!(!f32::INFINITY.is_normal());
591 /// // Values between `0` and `min` are Subnormal.
592 /// assert!(!lower_than_min.is_normal());
593 /// ```
594 /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
c295e0f8 595 #[must_use]
83c7162d 596 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 597 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 598 #[inline]
3dfed10e
XL
599 pub const fn is_normal(self) -> bool {
600 matches!(self.classify(), FpCategory::Normal)
94b46f34 601 }
83c7162d
XL
602
603 /// Returns the floating point category of the number. If only one property
604 /// is going to be tested, it is generally faster to use the specific
605 /// predicate instead.
606 ///
607 /// ```
608 /// use std::num::FpCategory;
83c7162d
XL
609 ///
610 /// let num = 12.4_f32;
611 /// let inf = f32::INFINITY;
612 ///
613 /// assert_eq!(num.classify(), FpCategory::Normal);
614 /// assert_eq!(inf.classify(), FpCategory::Infinite);
615 /// ```
616 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e
XL
617 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
618 pub const fn classify(self) -> FpCategory {
04454e1e
FG
619 // A previous implementation tried to only use bitmask-based checks,
620 // using f32::to_bits to transmute the float to its bit repr and match on that.
621 // Unfortunately, floating point numbers can be much worse than that.
622 // This also needs to not result in recursive evaluations of f64::to_bits.
623 //
624 // On some processors, in some cases, LLVM will "helpfully" lower floating point ops,
625 // in spite of a request for them using f32 and f64, to things like x87 operations.
626 // These have an f64's mantissa, but can have a larger than normal exponent.
627 // FIXME(jubilee): Using x87 operations is never necessary in order to function
628 // on x86 processors for Rust-to-Rust calls, so this issue should not happen.
629 // Code generation should be adjusted to use non-C calling conventions, avoiding this.
630 //
631 if self.is_infinite() {
632 // Thus, a value may compare unequal to infinity, despite having a "full" exponent mask.
633 FpCategory::Infinite
634 } else if self.is_nan() {
635 // And it may not be NaN, as it can simply be an "overextended" finite value.
636 FpCategory::Nan
637 } else {
638 // However, std can't simply compare to zero to check for zero, either,
639 // as correctness requires avoiding equality tests that may be Subnormal == -0.0
640 // because it may be wrong under "denormals are zero" and "flush to zero" modes.
641 // Most of std's targets don't use those, but they are used for thumbv7neon.
642 // So, this does use bitpattern matching for the rest.
643
644 // SAFETY: f32 to u32 is fine. Usually.
645 // If classify has gotten this far, the value is definitely in one of these categories.
646 unsafe { f32::partial_classify(self) }
647 }
648 }
649
650 // This doesn't actually return a right answer for NaN on purpose,
651 // seeing as how it cannot correctly discern between a floating point NaN,
652 // and some normal floating point numbers truncated from an x87 FPU.
653 // FIXME(jubilee): This probably could at least answer things correctly for Infinity,
654 // like the f64 version does, but I need to run more checks on how things go on x86.
655 // I fear losing mantissa data that would have answered that differently.
656 //
657 // # Safety
658 // This requires making sure you call this function for values it answers correctly on,
659 // otherwise it returns a wrong answer. This is not important for memory safety per se,
660 // but getting floats correct is important for not accidentally leaking const eval
661 // runtime-deviating logic which may or may not be acceptable.
662 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
663 const unsafe fn partial_classify(self) -> FpCategory {
94b46f34
XL
664 const EXP_MASK: u32 = 0x7f800000;
665 const MAN_MASK: u32 = 0x007fffff;
666
04454e1e
FG
667 // SAFETY: The caller is not asking questions for which this will tell lies.
668 let b = unsafe { mem::transmute::<f32, u32>(self) };
669 match (b & MAN_MASK, b & EXP_MASK) {
94b46f34
XL
670 (0, 0) => FpCategory::Zero,
671 (_, 0) => FpCategory::Subnormal,
04454e1e
FG
672 _ => FpCategory::Normal,
673 }
674 }
675
676 // This operates on bits, and only bits, so it can ignore concerns about weird FPUs.
677 // FIXME(jubilee): In a just world, this would be the entire impl for classify,
678 // plus a transmute. We do not live in a just world, but we can make it more so.
679 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
680 const fn classify_bits(b: u32) -> FpCategory {
681 const EXP_MASK: u32 = 0x7f800000;
682 const MAN_MASK: u32 = 0x007fffff;
683
684 match (b & MAN_MASK, b & EXP_MASK) {
94b46f34
XL
685 (0, EXP_MASK) => FpCategory::Infinite,
686 (_, EXP_MASK) => FpCategory::Nan,
04454e1e
FG
687 (0, 0) => FpCategory::Zero,
688 (_, 0) => FpCategory::Subnormal,
94b46f34
XL
689 _ => FpCategory::Normal,
690 }
691 }
83c7162d 692
04454e1e 693 /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
f2b60f7d 694 /// positive sign bit and positive infinity. Note that IEEE 754 doesn't assign any
04454e1e
FG
695 /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
696 /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
697 /// `is_sign_positive` on a NaN might produce an unexpected result in some cases.
698 /// See [explanation of NaN as a special value](f32) for more info.
83c7162d
XL
699 ///
700 /// ```
701 /// let f = 7.0_f32;
702 /// let g = -7.0_f32;
703 ///
704 /// assert!(f.is_sign_positive());
705 /// assert!(!g.is_sign_positive());
706 /// ```
c295e0f8 707 #[must_use]
83c7162d 708 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 709 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 710 #[inline]
3dfed10e 711 pub const fn is_sign_positive(self) -> bool {
94b46f34
XL
712 !self.is_sign_negative()
713 }
83c7162d 714
04454e1e 715 /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
f2b60f7d 716 /// negative sign bit and negative infinity. Note that IEEE 754 doesn't assign any
04454e1e
FG
717 /// meaning to the sign bit in case of a NaN, and as Rust doesn't guarantee that
718 /// the bit pattern of NaNs are conserved over arithmetic operations, the result of
719 /// `is_sign_negative` on a NaN might produce an unexpected result in some cases.
720 /// See [explanation of NaN as a special value](f32) for more info.
83c7162d
XL
721 ///
722 /// ```
723 /// let f = 7.0f32;
724 /// let g = -7.0f32;
725 ///
726 /// assert!(!f.is_sign_negative());
727 /// assert!(g.is_sign_negative());
728 /// ```
c295e0f8 729 #[must_use]
83c7162d 730 #[stable(feature = "rust1", since = "1.0.0")]
3dfed10e 731 #[rustc_const_unstable(feature = "const_float_classify", issue = "72505")]
83c7162d 732 #[inline]
3dfed10e 733 pub const fn is_sign_negative(self) -> bool {
94b46f34
XL
734 // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
735 // applies to zeros and NaNs as well.
04454e1e
FG
736 // SAFETY: This is just transmuting to get the sign bit, it's fine.
737 unsafe { mem::transmute::<f32, u32>(self) & 0x8000_0000 != 0 }
94b46f34 738 }
83c7162d 739
f2b60f7d
FG
740 /// Returns the least number greater than `self`.
741 ///
742 /// Let `TINY` be the smallest representable positive `f32`. Then,
743 /// - if `self.is_nan()`, this returns `self`;
744 /// - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
745 /// - if `self` is `-TINY`, this returns -0.0;
746 /// - if `self` is -0.0 or +0.0, this returns `TINY`;
747 /// - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
748 /// - otherwise the unique least value greater than `self` is returned.
749 ///
750 /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
751 /// is finite `x == x.next_up().next_down()` also holds.
752 ///
753 /// ```rust
754 /// #![feature(float_next_up_down)]
755 /// // f32::EPSILON is the difference between 1.0 and the next number up.
756 /// assert_eq!(1.0f32.next_up(), 1.0 + f32::EPSILON);
757 /// // But not for most numbers.
758 /// assert!(0.1f32.next_up() < 0.1 + f32::EPSILON);
759 /// assert_eq!(16777216f32.next_up(), 16777218.0);
760 /// ```
761 ///
762 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
763 /// [`INFINITY`]: Self::INFINITY
764 /// [`MIN`]: Self::MIN
765 /// [`MAX`]: Self::MAX
766 #[unstable(feature = "float_next_up_down", issue = "91399")]
767 #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
768 pub const fn next_up(self) -> Self {
769 // We must use strictly integer arithmetic to prevent denormals from
770 // flushing to zero after an arithmetic operation on some platforms.
771 const TINY_BITS: u32 = 0x1; // Smallest positive f32.
772 const CLEAR_SIGN_MASK: u32 = 0x7fff_ffff;
773
774 let bits = self.to_bits();
775 if self.is_nan() || bits == Self::INFINITY.to_bits() {
776 return self;
777 }
778
779 let abs = bits & CLEAR_SIGN_MASK;
780 let next_bits = if abs == 0 {
781 TINY_BITS
782 } else if bits == abs {
783 bits + 1
784 } else {
785 bits - 1
786 };
787 Self::from_bits(next_bits)
788 }
789
790 /// Returns the greatest number less than `self`.
791 ///
792 /// Let `TINY` be the smallest representable positive `f32`. Then,
793 /// - if `self.is_nan()`, this returns `self`;
794 /// - if `self` is [`INFINITY`], this returns [`MAX`];
795 /// - if `self` is `TINY`, this returns 0.0;
796 /// - if `self` is -0.0 or +0.0, this returns `-TINY`;
797 /// - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
798 /// - otherwise the unique greatest value less than `self` is returned.
799 ///
800 /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
801 /// is finite `x == x.next_down().next_up()` also holds.
802 ///
803 /// ```rust
804 /// #![feature(float_next_up_down)]
805 /// let x = 1.0f32;
806 /// // Clamp value into range [0, 1).
807 /// let clamped = x.clamp(0.0, 1.0f32.next_down());
808 /// assert!(clamped < 1.0);
809 /// assert_eq!(clamped.next_up(), 1.0);
810 /// ```
811 ///
812 /// [`NEG_INFINITY`]: Self::NEG_INFINITY
813 /// [`INFINITY`]: Self::INFINITY
814 /// [`MIN`]: Self::MIN
815 /// [`MAX`]: Self::MAX
816 #[unstable(feature = "float_next_up_down", issue = "91399")]
817 #[rustc_const_unstable(feature = "float_next_up_down", issue = "91399")]
818 pub const fn next_down(self) -> Self {
819 // We must use strictly integer arithmetic to prevent denormals from
820 // flushing to zero after an arithmetic operation on some platforms.
821 const NEG_TINY_BITS: u32 = 0x8000_0001; // Smallest (in magnitude) negative f32.
822 const CLEAR_SIGN_MASK: u32 = 0x7fff_ffff;
823
824 let bits = self.to_bits();
825 if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
826 return self;
827 }
828
829 let abs = bits & CLEAR_SIGN_MASK;
830 let next_bits = if abs == 0 {
831 NEG_TINY_BITS
832 } else if bits == abs {
833 bits - 1
834 } else {
835 bits + 1
836 };
837 Self::from_bits(next_bits)
838 }
839
83c7162d
XL
840 /// Takes the reciprocal (inverse) of a number, `1/x`.
841 ///
842 /// ```
83c7162d 843 /// let x = 2.0_f32;
e1599b0c 844 /// let abs_difference = (x.recip() - (1.0 / x)).abs();
83c7162d
XL
845 ///
846 /// assert!(abs_difference <= f32::EPSILON);
847 /// ```
a2a8927a 848 #[must_use = "this returns the result of the operation, without modifying the original"]
83c7162d
XL
849 #[stable(feature = "rust1", since = "1.0.0")]
850 #[inline]
94b46f34
XL
851 pub fn recip(self) -> f32 {
852 1.0 / self
853 }
83c7162d
XL
854
855 /// Converts radians to degrees.
856 ///
857 /// ```
ba9703b0 858 /// let angle = std::f32::consts::PI;
83c7162d
XL
859 ///
860 /// let abs_difference = (angle.to_degrees() - 180.0).abs();
ed00b5ec 861 /// # #[cfg(any(not(target_arch = "x86"), target_feature = "sse2"))]
83c7162d
XL
862 /// assert!(abs_difference <= f32::EPSILON);
863 /// ```
c295e0f8
XL
864 #[must_use = "this returns the result of the operation, \
865 without modifying the original"]
dfeec247 866 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
83c7162d 867 #[inline]
94b46f34
XL
868 pub fn to_degrees(self) -> f32 {
869 // Use a constant for better precision.
870 const PIS_IN_180: f32 = 57.2957795130823208767981548141051703_f32;
871 self * PIS_IN_180
872 }
83c7162d
XL
873
874 /// Converts degrees to radians.
875 ///
876 /// ```
83c7162d
XL
877 /// let angle = 180.0f32;
878 ///
ba9703b0 879 /// let abs_difference = (angle.to_radians() - std::f32::consts::PI).abs();
83c7162d
XL
880 ///
881 /// assert!(abs_difference <= f32::EPSILON);
882 /// ```
c295e0f8
XL
883 #[must_use = "this returns the result of the operation, \
884 without modifying the original"]
dfeec247 885 #[stable(feature = "f32_deg_rad_conversions", since = "1.7.0")]
83c7162d 886 #[inline]
94b46f34
XL
887 pub fn to_radians(self) -> f32 {
888 let value: f32 = consts::PI;
889 self * (value / 180.0f32)
890 }
83c7162d 891
04454e1e 892 /// Returns the maximum of the two numbers, ignoring NaN.
83c7162d 893 ///
04454e1e 894 /// If one of the arguments is NaN, then the other argument is returned.
f2b60f7d 895 /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
04454e1e
FG
896 /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
897 /// This also matches the behavior of libm’s fmax.
3c0e092e 898 ///
83c7162d
XL
899 /// ```
900 /// let x = 1.0f32;
901 /// let y = 2.0f32;
902 ///
903 /// assert_eq!(x.max(y), y);
904 /// ```
a2a8927a 905 #[must_use = "this returns the result of the comparison, without modifying either input"]
83c7162d
XL
906 #[stable(feature = "rust1", since = "1.0.0")]
907 #[inline]
908 pub fn max(self, other: f32) -> f32 {
dc9dc135 909 intrinsics::maxnumf32(self, other)
83c7162d
XL
910 }
911
04454e1e 912 /// Returns the minimum of the two numbers, ignoring NaN.
83c7162d 913 ///
04454e1e 914 /// If one of the arguments is NaN, then the other argument is returned.
f2b60f7d 915 /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
04454e1e
FG
916 /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
917 /// This also matches the behavior of libm’s fmin.
3c0e092e 918 ///
83c7162d
XL
919 /// ```
920 /// let x = 1.0f32;
921 /// let y = 2.0f32;
922 ///
923 /// assert_eq!(x.min(y), x);
924 /// ```
a2a8927a 925 #[must_use = "this returns the result of the comparison, without modifying either input"]
83c7162d
XL
926 #[stable(feature = "rust1", since = "1.0.0")]
927 #[inline]
928 pub fn min(self, other: f32) -> f32 {
dc9dc135 929 intrinsics::minnumf32(self, other)
83c7162d
XL
930 }
931
04454e1e 932 /// Returns the maximum of the two numbers, propagating NaN.
3c0e092e
XL
933 ///
934 /// This returns NaN when *either* argument is NaN, as opposed to
935 /// [`f32::max`] which only returns NaN when *both* arguments are NaN.
936 ///
937 /// ```
938 /// #![feature(float_minimum_maximum)]
939 /// let x = 1.0f32;
940 /// let y = 2.0f32;
941 ///
942 /// assert_eq!(x.maximum(y), y);
943 /// assert!(x.maximum(f32::NAN).is_nan());
944 /// ```
945 ///
946 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
947 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
948 /// Note that this follows the semantics specified in IEEE 754-2019.
04454e1e
FG
949 ///
950 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
951 /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
a2a8927a 952 #[must_use = "this returns the result of the comparison, without modifying either input"]
3c0e092e
XL
953 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
954 #[inline]
955 pub fn maximum(self, other: f32) -> f32 {
956 if self > other {
957 self
958 } else if other > self {
959 other
960 } else if self == other {
961 if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
962 } else {
963 self + other
964 }
965 }
966
04454e1e 967 /// Returns the minimum of the two numbers, propagating NaN.
3c0e092e
XL
968 ///
969 /// This returns NaN when *either* argument is NaN, as opposed to
970 /// [`f32::min`] which only returns NaN when *both* arguments are NaN.
971 ///
972 /// ```
973 /// #![feature(float_minimum_maximum)]
974 /// let x = 1.0f32;
975 /// let y = 2.0f32;
976 ///
977 /// assert_eq!(x.minimum(y), x);
978 /// assert!(x.minimum(f32::NAN).is_nan());
979 /// ```
980 ///
981 /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
982 /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
983 /// Note that this follows the semantics specified in IEEE 754-2019.
04454e1e
FG
984 ///
985 /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
986 /// operand is conserved; see [explanation of NaN as a special value](f32) for more info.
a2a8927a 987 #[must_use = "this returns the result of the comparison, without modifying either input"]
3c0e092e
XL
988 #[unstable(feature = "float_minimum_maximum", issue = "91079")]
989 #[inline]
990 pub fn minimum(self, other: f32) -> f32 {
991 if self < other {
992 self
993 } else if other < self {
994 other
995 } else if self == other {
996 if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
997 } else {
781aab86 998 // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
3c0e092e
XL
999 self + other
1000 }
1001 }
1002
49aad941
FG
1003 /// Calculates the middle point of `self` and `rhs`.
1004 ///
1005 /// This returns NaN when *either* argument is NaN or if a combination of
1006 /// +inf and -inf is provided as arguments.
1007 ///
1008 /// # Examples
1009 ///
1010 /// ```
1011 /// #![feature(num_midpoint)]
1012 /// assert_eq!(1f32.midpoint(4.0), 2.5);
1013 /// assert_eq!((-5.5f32).midpoint(8.0), 1.25);
1014 /// ```
1015 #[unstable(feature = "num_midpoint", issue = "110840")]
1016 pub fn midpoint(self, other: f32) -> f32 {
1017 const LO: f32 = f32::MIN_POSITIVE * 2.;
1018 const HI: f32 = f32::MAX / 2.;
1019
1020 let (a, b) = (self, other);
1021 let abs_a = a.abs_private();
1022 let abs_b = b.abs_private();
1023
1024 if abs_a <= HI && abs_b <= HI {
1025 // Overflow is impossible
1026 (a + b) / 2.
1027 } else if abs_a < LO {
1028 // Not safe to halve a
1029 a + (b / 2.)
1030 } else if abs_b < LO {
1031 // Not safe to halve b
1032 (a / 2.) + b
1033 } else {
1034 // Not safe to halve a and b
1035 (a / 2.) + (b / 2.)
1036 }
1037 }
1038
60c5eb7d
XL
1039 /// Rounds toward zero and converts to any primitive integer type,
1040 /// assuming that the value is finite and fits in that type.
1041 ///
1042 /// ```
60c5eb7d 1043 /// let value = 4.6_f32;
ba9703b0 1044 /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
60c5eb7d
XL
1045 /// assert_eq!(rounded, 4);
1046 ///
1047 /// let value = -128.9_f32;
ba9703b0
XL
1048 /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1049 /// assert_eq!(rounded, i8::MIN);
60c5eb7d
XL
1050 /// ```
1051 ///
1052 /// # Safety
1053 ///
1054 /// The value must:
1055 ///
1056 /// * Not be `NaN`
1057 /// * Not be infinite
1058 /// * Be representable in the return type `Int`, after truncating off its fractional part
c295e0f8
XL
1059 #[must_use = "this returns the result of the operation, \
1060 without modifying the original"]
ba9703b0 1061 #[stable(feature = "float_approx_unchecked_to", since = "1.44.0")]
60c5eb7d 1062 #[inline]
ba9703b0 1063 pub unsafe fn to_int_unchecked<Int>(self) -> Int
dfeec247
XL
1064 where
1065 Self: FloatToInt<Int>,
1066 {
f035d41b
XL
1067 // SAFETY: the caller must uphold the safety contract for
1068 // `FloatToInt::to_int_unchecked`.
1069 unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
60c5eb7d
XL
1070 }
1071
83c7162d
XL
1072 /// Raw transmutation to `u32`.
1073 ///
1074 /// This is currently identical to `transmute::<f32, u32>(self)` on all platforms.
1075 ///
17df50a5
XL
1076 /// See [`from_bits`](Self::from_bits) for some discussion of the
1077 /// portability of this operation (there are almost no issues).
83c7162d
XL
1078 ///
1079 /// Note that this function is distinct from `as` casting, which attempts to
1080 /// preserve the *numeric* value, and not the bitwise value.
1081 ///
1082 /// # Examples
1083 ///
1084 /// ```
1085 /// assert_ne!((1f32).to_bits(), 1f32 as u32); // to_bits() is not casting!
1086 /// assert_eq!((12.5f32).to_bits(), 0x41480000);
1087 ///
1088 /// ```
c295e0f8
XL
1089 #[must_use = "this returns the result of the operation, \
1090 without modifying the original"]
83c7162d 1091 #[stable(feature = "float_bits_conv", since = "1.20.0")]
3dfed10e 1092 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
83c7162d 1093 #[inline]
3dfed10e 1094 pub const fn to_bits(self) -> u32 {
04454e1e
FG
1095 // SAFETY: `u32` is a plain old datatype so we can always transmute to it.
1096 // ...sorta.
1097 //
1098 // It turns out that at runtime, it is possible for a floating point number
1099 // to be subject to a floating point mode that alters nonzero subnormal numbers
1100 // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1101 // This is not a problem per se, but at least one tier2 platform for Rust
1102 // actually exhibits this behavior by default.
1103 //
1104 // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1105 // i.e. not soft-float, the way Rust does parameter passing can actually alter
1106 // a number that is "not infinity" to have the same exponent as infinity,
1107 // in a slightly unpredictable manner.
1108 //
1109 // And, of course evaluating to a NaN value is fairly nondeterministic.
1110 // More precisely: when NaN should be returned is knowable, but which NaN?
1111 // So far that's defined by a combination of LLVM and the CPU, not Rust.
1112 // This function, however, allows observing the bitstring of a NaN,
1113 // thus introspection on CTFE.
1114 //
1115 // In order to preserve, at least for the moment, const-to-runtime equivalence,
1116 // we reject any of these possible situations from happening.
1117 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1118 const fn ct_f32_to_u32(ct: f32) -> u32 {
1119 match ct.classify() {
1120 FpCategory::Nan => {
1121 panic!("const-eval error: cannot use f32::to_bits on a NaN")
1122 }
1123 FpCategory::Subnormal => {
1124 panic!("const-eval error: cannot use f32::to_bits on a subnormal number")
1125 }
1126 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1127 // SAFETY: We have a normal floating point number. Now we transmute, i.e. do a bitcopy.
1128 unsafe { mem::transmute::<f32, u32>(ct) }
1129 }
1130 }
1131 }
f2b60f7d
FG
1132
1133 #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1134 fn rt_f32_to_u32(x: f32) -> u32 {
1135 // SAFETY: `u32` is a plain old datatype so we can always... uh...
1136 // ...look, just pretend you forgot what you just read.
1137 // Stability concerns.
1138 unsafe { mem::transmute(x) }
1139 }
04454e1e
FG
1140 // SAFETY: We use internal implementations that either always work or fail at compile time.
1141 unsafe { intrinsics::const_eval_select((self,), ct_f32_to_u32, rt_f32_to_u32) }
83c7162d
XL
1142 }
1143
1144 /// Raw transmutation from `u32`.
1145 ///
1146 /// This is currently identical to `transmute::<u32, f32>(v)` on all platforms.
1147 /// It turns out this is incredibly portable, for two reasons:
1148 ///
1149 /// * Floats and Ints have the same endianness on all supported platforms.
f2b60f7d 1150 /// * IEEE 754 very precisely specifies the bit layout of floats.
83c7162d 1151 ///
f2b60f7d 1152 /// However there is one caveat: prior to the 2008 version of IEEE 754, how
83c7162d
XL
1153 /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1154 /// (notably x86 and ARM) picked the interpretation that was ultimately
1155 /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1156 /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1157 ///
1158 /// Rather than trying to preserve signaling-ness cross-platform, this
a1dfa0c6 1159 /// implementation favors preserving the exact bits. This means that
83c7162d
XL
1160 /// any payloads encoded in NaNs will be preserved even if the result of
1161 /// this method is sent over the network from an x86 machine to a MIPS one.
1162 ///
1163 /// If the results of this method are only manipulated by the same
1164 /// architecture that produced them, then there is no portability concern.
1165 ///
1166 /// If the input isn't NaN, then there is no portability concern.
1167 ///
1168 /// If you don't care about signalingness (very likely), then there is no
1169 /// portability concern.
1170 ///
1171 /// Note that this function is distinct from `as` casting, which attempts to
1172 /// preserve the *numeric* value, and not the bitwise value.
1173 ///
1174 /// # Examples
1175 ///
1176 /// ```
83c7162d 1177 /// let v = f32::from_bits(0x41480000);
416331ca 1178 /// assert_eq!(v, 12.5);
83c7162d
XL
1179 /// ```
1180 #[stable(feature = "float_bits_conv", since = "1.20.0")]
3dfed10e 1181 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
c295e0f8 1182 #[must_use]
83c7162d 1183 #[inline]
3dfed10e 1184 pub const fn from_bits(v: u32) -> Self {
94b46f34 1185 // It turns out the safety issues with sNaN were overblown! Hooray!
04454e1e
FG
1186 // SAFETY: `u32` is a plain old datatype so we can always transmute from it
1187 // ...sorta.
1188 //
1189 // It turns out that at runtime, it is possible for a floating point number
1190 // to be subject to floating point modes that alter nonzero subnormal numbers
1191 // to zero on reads and writes, aka "denormals are zero" and "flush to zero".
1192 // This is not a problem usually, but at least one tier2 platform for Rust
1193 // actually exhibits this behavior by default: thumbv7neon
1194 // aka "the Neon FPU in AArch32 state"
1195 //
1196 // In addition, on x86 targets with SSE or SSE2 disabled and the x87 FPU enabled,
1197 // i.e. not soft-float, the way Rust does parameter passing can actually alter
1198 // a number that is "not infinity" to have the same exponent as infinity,
1199 // in a slightly unpredictable manner.
1200 //
1201 // And, of course evaluating to a NaN value is fairly nondeterministic.
1202 // More precisely: when NaN should be returned is knowable, but which NaN?
1203 // So far that's defined by a combination of LLVM and the CPU, not Rust.
1204 // This function, however, allows observing the bitstring of a NaN,
1205 // thus introspection on CTFE.
1206 //
1207 // In order to preserve, at least for the moment, const-to-runtime equivalence,
1208 // reject any of these possible situations from happening.
1209 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
1210 const fn ct_u32_to_f32(ct: u32) -> f32 {
1211 match f32::classify_bits(ct) {
1212 FpCategory::Subnormal => {
1213 panic!("const-eval error: cannot use f32::from_bits on a subnormal number")
1214 }
1215 FpCategory::Nan => {
1216 panic!("const-eval error: cannot use f32::from_bits on NaN")
1217 }
1218 FpCategory::Infinite | FpCategory::Normal | FpCategory::Zero => {
1219 // SAFETY: It's not a frumious number
1220 unsafe { mem::transmute::<u32, f32>(ct) }
1221 }
1222 }
1223 }
f2b60f7d
FG
1224
1225 #[inline(always)] // See https://github.com/rust-lang/compiler-builtins/issues/491
1226 fn rt_u32_to_f32(x: u32) -> f32 {
1227 // SAFETY: `u32` is a plain old datatype so we can always... uh...
1228 // ...look, just pretend you forgot what you just read.
1229 // Stability concerns.
1230 unsafe { mem::transmute(x) }
1231 }
04454e1e
FG
1232 // SAFETY: We use internal implementations that either always work or fail at compile time.
1233 unsafe { intrinsics::const_eval_select((v,), ct_u32_to_f32, rt_u32_to_f32) }
83c7162d 1234 }
416331ca
XL
1235
1236 /// Return the memory representation of this floating point number as a byte array in
1237 /// big-endian (network) byte order.
1238 ///
04454e1e
FG
1239 /// See [`from_bits`](Self::from_bits) for some discussion of the
1240 /// portability of this operation (there are almost no issues).
1241 ///
416331ca
XL
1242 /// # Examples
1243 ///
1244 /// ```
416331ca
XL
1245 /// let bytes = 12.5f32.to_be_bytes();
1246 /// assert_eq!(bytes, [0x41, 0x48, 0x00, 0x00]);
1247 /// ```
c295e0f8
XL
1248 #[must_use = "this returns the result of the operation, \
1249 without modifying the original"]
e74abb32 1250 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 1251 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
416331ca 1252 #[inline]
3dfed10e 1253 pub const fn to_be_bytes(self) -> [u8; 4] {
416331ca
XL
1254 self.to_bits().to_be_bytes()
1255 }
1256
1257 /// Return the memory representation of this floating point number as a byte array in
1258 /// little-endian byte order.
1259 ///
04454e1e
FG
1260 /// See [`from_bits`](Self::from_bits) for some discussion of the
1261 /// portability of this operation (there are almost no issues).
1262 ///
416331ca
XL
1263 /// # Examples
1264 ///
1265 /// ```
416331ca
XL
1266 /// let bytes = 12.5f32.to_le_bytes();
1267 /// assert_eq!(bytes, [0x00, 0x00, 0x48, 0x41]);
1268 /// ```
c295e0f8
XL
1269 #[must_use = "this returns the result of the operation, \
1270 without modifying the original"]
e74abb32 1271 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 1272 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
416331ca 1273 #[inline]
3dfed10e 1274 pub const fn to_le_bytes(self) -> [u8; 4] {
416331ca
XL
1275 self.to_bits().to_le_bytes()
1276 }
1277
1278 /// Return the memory representation of this floating point number as a byte array in
1279 /// native byte order.
1280 ///
1281 /// As the target platform's native endianness is used, portable code
1282 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1283 ///
6a06907d
XL
1284 /// [`to_be_bytes`]: f32::to_be_bytes
1285 /// [`to_le_bytes`]: f32::to_le_bytes
416331ca 1286 ///
04454e1e
FG
1287 /// See [`from_bits`](Self::from_bits) for some discussion of the
1288 /// portability of this operation (there are almost no issues).
1289 ///
416331ca
XL
1290 /// # Examples
1291 ///
1292 /// ```
416331ca
XL
1293 /// let bytes = 12.5f32.to_ne_bytes();
1294 /// assert_eq!(
1295 /// bytes,
1296 /// if cfg!(target_endian = "big") {
1297 /// [0x41, 0x48, 0x00, 0x00]
1298 /// } else {
1299 /// [0x00, 0x00, 0x48, 0x41]
1300 /// }
1301 /// );
1302 /// ```
c295e0f8
XL
1303 #[must_use = "this returns the result of the operation, \
1304 without modifying the original"]
e74abb32 1305 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 1306 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
416331ca 1307 #[inline]
3dfed10e 1308 pub const fn to_ne_bytes(self) -> [u8; 4] {
416331ca
XL
1309 self.to_bits().to_ne_bytes()
1310 }
1311
1312 /// Create a floating point value from its representation as a byte array in big endian.
1313 ///
04454e1e
FG
1314 /// See [`from_bits`](Self::from_bits) for some discussion of the
1315 /// portability of this operation (there are almost no issues).
1316 ///
416331ca
XL
1317 /// # Examples
1318 ///
1319 /// ```
416331ca
XL
1320 /// let value = f32::from_be_bytes([0x41, 0x48, 0x00, 0x00]);
1321 /// assert_eq!(value, 12.5);
1322 /// ```
e74abb32 1323 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 1324 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
c295e0f8 1325 #[must_use]
416331ca 1326 #[inline]
3dfed10e 1327 pub const fn from_be_bytes(bytes: [u8; 4]) -> Self {
416331ca
XL
1328 Self::from_bits(u32::from_be_bytes(bytes))
1329 }
1330
1331 /// Create a floating point value from its representation as a byte array in little endian.
1332 ///
04454e1e
FG
1333 /// See [`from_bits`](Self::from_bits) for some discussion of the
1334 /// portability of this operation (there are almost no issues).
1335 ///
416331ca
XL
1336 /// # Examples
1337 ///
1338 /// ```
416331ca
XL
1339 /// let value = f32::from_le_bytes([0x00, 0x00, 0x48, 0x41]);
1340 /// assert_eq!(value, 12.5);
1341 /// ```
e74abb32 1342 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 1343 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
c295e0f8 1344 #[must_use]
416331ca 1345 #[inline]
3dfed10e 1346 pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
416331ca
XL
1347 Self::from_bits(u32::from_le_bytes(bytes))
1348 }
1349
1350 /// Create a floating point value from its representation as a byte array in native endian.
1351 ///
1352 /// As the target platform's native endianness is used, portable code
1353 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1354 /// appropriate instead.
1355 ///
6a06907d
XL
1356 /// [`from_be_bytes`]: f32::from_be_bytes
1357 /// [`from_le_bytes`]: f32::from_le_bytes
416331ca 1358 ///
04454e1e
FG
1359 /// See [`from_bits`](Self::from_bits) for some discussion of the
1360 /// portability of this operation (there are almost no issues).
1361 ///
416331ca
XL
1362 /// # Examples
1363 ///
1364 /// ```
416331ca
XL
1365 /// let value = f32::from_ne_bytes(if cfg!(target_endian = "big") {
1366 /// [0x41, 0x48, 0x00, 0x00]
1367 /// } else {
1368 /// [0x00, 0x00, 0x48, 0x41]
1369 /// });
1370 /// assert_eq!(value, 12.5);
1371 /// ```
e74abb32 1372 #[stable(feature = "float_to_from_bytes", since = "1.40.0")]
3dfed10e 1373 #[rustc_const_unstable(feature = "const_float_bits_conv", issue = "72447")]
c295e0f8 1374 #[must_use]
416331ca 1375 #[inline]
3dfed10e 1376 pub const fn from_ne_bytes(bytes: [u8; 4]) -> Self {
416331ca
XL
1377 Self::from_bits(u32::from_ne_bytes(bytes))
1378 }
f9f354fc 1379
5099ac24
FG
1380 /// Return the ordering between `self` and `other`.
1381 ///
f9f354fc
XL
1382 /// Unlike the standard partial comparison between floating point numbers,
1383 /// this comparison always produces an ordering in accordance to
5099ac24
FG
1384 /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1385 /// floating point standard. The values are ordered in the following sequence:
1386 ///
1387 /// - negative quiet NaN
1388 /// - negative signaling NaN
1389 /// - negative infinity
1390 /// - negative numbers
1391 /// - negative subnormal numbers
1392 /// - negative zero
1393 /// - positive zero
1394 /// - positive subnormal numbers
1395 /// - positive numbers
1396 /// - positive infinity
1397 /// - positive signaling NaN
1398 /// - positive quiet NaN.
1399 ///
1400 /// The ordering established by this function does not always agree with the
1401 /// [`PartialOrd`] and [`PartialEq`] implementations of `f32`. For example,
1402 /// they consider negative and positive zero equal, while `total_cmp`
1403 /// doesn't.
1404 ///
1405 /// The interpretation of the signaling NaN bit follows the definition in
1406 /// the IEEE 754 standard, which may not match the interpretation by some of
1407 /// the older, non-conformant (e.g. MIPS) hardware implementations.
29967ef6 1408 ///
f9f354fc 1409 /// # Example
5099ac24 1410 ///
f9f354fc 1411 /// ```
f9f354fc
XL
1412 /// struct GoodBoy {
1413 /// name: String,
1414 /// weight: f32,
1415 /// }
1416 ///
1417 /// let mut bois = vec![
1418 /// GoodBoy { name: "Pucci".to_owned(), weight: 0.1 },
1419 /// GoodBoy { name: "Woofer".to_owned(), weight: 99.0 },
1420 /// GoodBoy { name: "Yapper".to_owned(), weight: 10.0 },
1421 /// GoodBoy { name: "Chonk".to_owned(), weight: f32::INFINITY },
1422 /// GoodBoy { name: "Abs. Unit".to_owned(), weight: f32::NAN },
1423 /// GoodBoy { name: "Floaty".to_owned(), weight: -5.0 },
1424 /// ];
1425 ///
1426 /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
4b012472
FG
1427 ///
1428 /// // `f32::NAN` could be positive or negative, which will affect the sort order.
1429 /// if f32::NAN.is_sign_negative() {
1430 /// assert!(bois.into_iter().map(|b| b.weight)
1431 /// .zip([f32::NAN, -5.0, 0.1, 10.0, 99.0, f32::INFINITY].iter())
1432 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1433 /// } else {
1434 /// assert!(bois.into_iter().map(|b| b.weight)
1435 /// .zip([-5.0, 0.1, 10.0, 99.0, f32::INFINITY, f32::NAN].iter())
1436 /// .all(|(a, b)| a.to_bits() == b.to_bits()))
1437 /// }
f9f354fc 1438 /// ```
04454e1e 1439 #[stable(feature = "total_cmp", since = "1.62.0")]
3c0e092e 1440 #[must_use]
f9f354fc
XL
1441 #[inline]
1442 pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1443 let mut left = self.to_bits() as i32;
1444 let mut right = other.to_bits() as i32;
1445
1446 // In case of negatives, flip all the bits except the sign
1447 // to achieve a similar layout as two's complement integers
1448 //
1449 // Why does this work? IEEE 754 floats consist of three fields:
1450 // Sign bit, exponent and mantissa. The set of exponent and mantissa
1451 // fields as a whole have the property that their bitwise order is
1452 // equal to the numeric magnitude where the magnitude is defined.
1453 // The magnitude is not normally defined on NaN values, but
1454 // IEEE 754 totalOrder defines the NaN values also to follow the
1455 // bitwise order. This leads to order explained in the doc comment.
1456 // However, the representation of magnitude is the same for negative
1457 // and positive numbers – only the sign bit is different.
1458 // To easily compare the floats as signed integers, we need to
1459 // flip the exponent and mantissa bits in case of negative numbers.
1460 // We effectively convert the numbers to "two's complement" form.
1461 //
1462 // To do the flipping, we construct a mask and XOR against it.
1463 // We branchlessly calculate an "all-ones except for the sign bit"
1464 // mask from negative-signed values: right shifting sign-extends
1465 // the integer, so we "fill" the mask with sign bits, and then
1466 // convert to unsigned to push one more zero bit.
1467 // On positive values, the mask is all zeros, so it's a no-op.
1468 left ^= (((left >> 31) as u32) >> 1) as i32;
1469 right ^= (((right >> 31) as u32) >> 1) as i32;
1470
1471 left.cmp(&right)
1472 }
fc512014
XL
1473
1474 /// Restrict a value to a certain interval unless it is NaN.
1475 ///
1476 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1477 /// less than `min`. Otherwise this returns `self`.
1478 ///
1479 /// Note that this function returns NaN if the initial value was NaN as
1480 /// well.
1481 ///
1482 /// # Panics
1483 ///
1484 /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1485 ///
1486 /// # Examples
1487 ///
1488 /// ```
1489 /// assert!((-3.0f32).clamp(-2.0, 1.0) == -2.0);
1490 /// assert!((0.0f32).clamp(-2.0, 1.0) == 0.0);
1491 /// assert!((2.0f32).clamp(-2.0, 1.0) == 1.0);
1492 /// assert!((f32::NAN).clamp(-2.0, 1.0).is_nan());
1493 /// ```
1494 #[must_use = "method returns a new number and does not mutate the original value"]
1495 #[stable(feature = "clamp", since = "1.50.0")]
1496 #[inline]
f2b60f7d 1497 pub fn clamp(mut self, min: f32, max: f32) -> f32 {
353b0b11 1498 assert!(min <= max, "min > max, or either was NaN. min = {min:?}, max = {max:?}");
f2b60f7d
FG
1499 if self < min {
1500 self = min;
fc512014 1501 }
f2b60f7d
FG
1502 if self > max {
1503 self = max;
fc512014 1504 }
f2b60f7d 1505 self
fc512014 1506 }
83c7162d 1507}