core/num/
f16.rs

1//! Constants for the `f16` half-precision floating point type.
2//!
3//! *[See also the `f16` primitive type][f16].*
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 `f16` type.
11
12#![unstable(feature = "f16", issue = "116909")]
13
14use crate::convert::FloatToInt;
15use crate::num::FpCategory;
16use crate::panic::const_assert;
17use crate::{intrinsics, mem};
18
19/// Basic mathematical constants.
20#[unstable(feature = "f16", issue = "116909")]
21pub mod consts {
22    // FIXME: replace with mathematical constants from cmath.
23
24    /// Archimedes' constant (π)
25    #[unstable(feature = "f16", issue = "116909")]
26    pub const PI: f16 = 3.14159265358979323846264338327950288_f16;
27
28    /// The full circle constant (τ)
29    ///
30    /// Equal to 2π.
31    #[unstable(feature = "f16", issue = "116909")]
32    pub const TAU: f16 = 6.28318530717958647692528676655900577_f16;
33
34    /// The golden ratio (φ)
35    #[unstable(feature = "f16", issue = "116909")]
36    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
37    pub const PHI: f16 = 1.618033988749894848204586834365638118_f16;
38
39    /// The Euler-Mascheroni constant (γ)
40    #[unstable(feature = "f16", issue = "116909")]
41    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
42    pub const EGAMMA: f16 = 0.577215664901532860606512090082402431_f16;
43
44    /// π/2
45    #[unstable(feature = "f16", issue = "116909")]
46    pub const FRAC_PI_2: f16 = 1.57079632679489661923132169163975144_f16;
47
48    /// π/3
49    #[unstable(feature = "f16", issue = "116909")]
50    pub const FRAC_PI_3: f16 = 1.04719755119659774615421446109316763_f16;
51
52    /// π/4
53    #[unstable(feature = "f16", issue = "116909")]
54    pub const FRAC_PI_4: f16 = 0.785398163397448309615660845819875721_f16;
55
56    /// π/6
57    #[unstable(feature = "f16", issue = "116909")]
58    pub const FRAC_PI_6: f16 = 0.52359877559829887307710723054658381_f16;
59
60    /// π/8
61    #[unstable(feature = "f16", issue = "116909")]
62    pub const FRAC_PI_8: f16 = 0.39269908169872415480783042290993786_f16;
63
64    /// 1/π
65    #[unstable(feature = "f16", issue = "116909")]
66    pub const FRAC_1_PI: f16 = 0.318309886183790671537767526745028724_f16;
67
68    /// 1/sqrt(π)
69    #[unstable(feature = "f16", issue = "116909")]
70    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
71    pub const FRAC_1_SQRT_PI: f16 = 0.564189583547756286948079451560772586_f16;
72
73    /// 1/sqrt(2π)
74    #[doc(alias = "FRAC_1_SQRT_TAU")]
75    #[unstable(feature = "f16", issue = "116909")]
76    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
77    pub const FRAC_1_SQRT_2PI: f16 = 0.398942280401432677939946059934381868_f16;
78
79    /// 2/π
80    #[unstable(feature = "f16", issue = "116909")]
81    pub const FRAC_2_PI: f16 = 0.636619772367581343075535053490057448_f16;
82
83    /// 2/sqrt(π)
84    #[unstable(feature = "f16", issue = "116909")]
85    pub const FRAC_2_SQRT_PI: f16 = 1.12837916709551257389615890312154517_f16;
86
87    /// sqrt(2)
88    #[unstable(feature = "f16", issue = "116909")]
89    pub const SQRT_2: f16 = 1.41421356237309504880168872420969808_f16;
90
91    /// 1/sqrt(2)
92    #[unstable(feature = "f16", issue = "116909")]
93    pub const FRAC_1_SQRT_2: f16 = 0.707106781186547524400844362104849039_f16;
94
95    /// sqrt(3)
96    #[unstable(feature = "f16", issue = "116909")]
97    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
98    pub const SQRT_3: f16 = 1.732050807568877293527446341505872367_f16;
99
100    /// 1/sqrt(3)
101    #[unstable(feature = "f16", issue = "116909")]
102    // Also, #[unstable(feature = "more_float_constants", issue = "103883")]
103    pub const FRAC_1_SQRT_3: f16 = 0.577350269189625764509148780501957456_f16;
104
105    /// Euler's number (e)
106    #[unstable(feature = "f16", issue = "116909")]
107    pub const E: f16 = 2.71828182845904523536028747135266250_f16;
108
109    /// log<sub>2</sub>(10)
110    #[unstable(feature = "f16", issue = "116909")]
111    pub const LOG2_10: f16 = 3.32192809488736234787031942948939018_f16;
112
113    /// log<sub>2</sub>(e)
114    #[unstable(feature = "f16", issue = "116909")]
115    pub const LOG2_E: f16 = 1.44269504088896340735992468100189214_f16;
116
117    /// log<sub>10</sub>(2)
118    #[unstable(feature = "f16", issue = "116909")]
119    pub const LOG10_2: f16 = 0.301029995663981195213738894724493027_f16;
120
121    /// log<sub>10</sub>(e)
122    #[unstable(feature = "f16", issue = "116909")]
123    pub const LOG10_E: f16 = 0.434294481903251827651128918916605082_f16;
124
125    /// ln(2)
126    #[unstable(feature = "f16", issue = "116909")]
127    pub const LN_2: f16 = 0.693147180559945309417232121458176568_f16;
128
129    /// ln(10)
130    #[unstable(feature = "f16", issue = "116909")]
131    pub const LN_10: f16 = 2.30258509299404568401799145468436421_f16;
132}
133
134impl f16 {
135    // FIXME(f16_f128): almost all methods in this `impl` are missing examples and a const
136    // implementation. Add these once we can run code on all platforms and have f16/f128 in CTFE.
137
138    /// The radix or base of the internal representation of `f16`.
139    #[unstable(feature = "f16", issue = "116909")]
140    pub const RADIX: u32 = 2;
141
142    /// Number of significant digits in base 2.
143    ///
144    /// Note that the size of the mantissa in the bitwise representation is one
145    /// smaller than this since the leading 1 is not stored explicitly.
146    #[unstable(feature = "f16", issue = "116909")]
147    pub const MANTISSA_DIGITS: u32 = 11;
148
149    /// Approximate number of significant digits in base 10.
150    ///
151    /// This is the maximum <i>x</i> such that any decimal number with <i>x</i>
152    /// significant digits can be converted to `f16` and back without loss.
153    ///
154    /// Equal to floor(log<sub>10</sub>&nbsp;2<sup>[`MANTISSA_DIGITS`]&nbsp;&minus;&nbsp;1</sup>).
155    ///
156    /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
157    #[unstable(feature = "f16", issue = "116909")]
158    pub const DIGITS: u32 = 3;
159
160    /// [Machine epsilon] value for `f16`.
161    ///
162    /// This is the difference between `1.0` and the next larger representable number.
163    ///
164    /// Equal to 2<sup>1&nbsp;&minus;&nbsp;[`MANTISSA_DIGITS`]</sup>.
165    ///
166    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
167    /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
168    #[unstable(feature = "f16", issue = "116909")]
169    pub const EPSILON: f16 = 9.7656e-4_f16;
170
171    /// Smallest finite `f16` value.
172    ///
173    /// Equal to &minus;[`MAX`].
174    ///
175    /// [`MAX`]: f16::MAX
176    #[unstable(feature = "f16", issue = "116909")]
177    pub const MIN: f16 = -6.5504e+4_f16;
178    /// Smallest positive normal `f16` value.
179    ///
180    /// Equal to 2<sup>[`MIN_EXP`]&nbsp;&minus;&nbsp;1</sup>.
181    ///
182    /// [`MIN_EXP`]: f16::MIN_EXP
183    #[unstable(feature = "f16", issue = "116909")]
184    pub const MIN_POSITIVE: f16 = 6.1035e-5_f16;
185    /// Largest finite `f16` value.
186    ///
187    /// Equal to
188    /// (1&nbsp;&minus;&nbsp;2<sup>&minus;[`MANTISSA_DIGITS`]</sup>)&nbsp;2<sup>[`MAX_EXP`]</sup>.
189    ///
190    /// [`MANTISSA_DIGITS`]: f16::MANTISSA_DIGITS
191    /// [`MAX_EXP`]: f16::MAX_EXP
192    #[unstable(feature = "f16", issue = "116909")]
193    pub const MAX: f16 = 6.5504e+4_f16;
194
195    /// One greater than the minimum possible *normal* power of 2 exponent
196    /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
197    ///
198    /// This corresponds to the exact minimum possible *normal* power of 2 exponent
199    /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
200    /// In other words, all normal numbers representable by this type are
201    /// greater than or equal to 0.5&nbsp;×&nbsp;2<sup><i>MIN_EXP</i></sup>.
202    #[unstable(feature = "f16", issue = "116909")]
203    pub const MIN_EXP: i32 = -13;
204    /// One greater than the maximum possible power of 2 exponent
205    /// for a significand bounded by 1 ≤ x < 2 (i.e. the IEEE definition).
206    ///
207    /// This corresponds to the exact maximum possible power of 2 exponent
208    /// for a significand bounded by 0.5 ≤ x < 1 (i.e. the C definition).
209    /// In other words, all numbers representable by this type are
210    /// strictly less than 2<sup><i>MAX_EXP</i></sup>.
211    #[unstable(feature = "f16", issue = "116909")]
212    pub const MAX_EXP: i32 = 16;
213
214    /// Minimum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
215    ///
216    /// Equal to ceil(log<sub>10</sub>&nbsp;[`MIN_POSITIVE`]).
217    ///
218    /// [`MIN_POSITIVE`]: f16::MIN_POSITIVE
219    #[unstable(feature = "f16", issue = "116909")]
220    pub const MIN_10_EXP: i32 = -4;
221    /// Maximum <i>x</i> for which 10<sup><i>x</i></sup> is normal.
222    ///
223    /// Equal to floor(log<sub>10</sub>&nbsp;[`MAX`]).
224    ///
225    /// [`MAX`]: f16::MAX
226    #[unstable(feature = "f16", issue = "116909")]
227    pub const MAX_10_EXP: i32 = 4;
228
229    /// Not a Number (NaN).
230    ///
231    /// Note that IEEE 754 doesn't define just a single NaN value; a plethora of bit patterns are
232    /// considered to be NaN. Furthermore, the standard makes a difference between a "signaling" and
233    /// a "quiet" NaN, and allows inspecting its "payload" (the unspecified bits in the bit pattern)
234    /// and its sign. See the [specification of NaN bit patterns](f32#nan-bit-patterns) for more
235    /// info.
236    ///
237    /// This constant is guaranteed to be a quiet NaN (on targets that follow the Rust assumptions
238    /// that the quiet/signaling bit being set to 1 indicates a quiet NaN). Beyond that, nothing is
239    /// guaranteed about the specific bit pattern chosen here: both payload and sign are arbitrary.
240    /// The concrete bit pattern may change across Rust versions and target platforms.
241    #[allow(clippy::eq_op)]
242    #[rustc_diagnostic_item = "f16_nan"]
243    #[unstable(feature = "f16", issue = "116909")]
244    pub const NAN: f16 = 0.0_f16 / 0.0_f16;
245
246    /// Infinity (∞).
247    #[unstable(feature = "f16", issue = "116909")]
248    pub const INFINITY: f16 = 1.0_f16 / 0.0_f16;
249
250    /// Negative infinity (−∞).
251    #[unstable(feature = "f16", issue = "116909")]
252    pub const NEG_INFINITY: f16 = -1.0_f16 / 0.0_f16;
253
254    /// Sign bit
255    pub(crate) const SIGN_MASK: u16 = 0x8000;
256
257    /// Exponent mask
258    pub(crate) const EXP_MASK: u16 = 0x7c00;
259
260    /// Mantissa mask
261    pub(crate) const MAN_MASK: u16 = 0x03ff;
262
263    /// Minimum representable positive value (min subnormal)
264    const TINY_BITS: u16 = 0x1;
265
266    /// Minimum representable negative value (min negative subnormal)
267    const NEG_TINY_BITS: u16 = Self::TINY_BITS | Self::SIGN_MASK;
268
269    /// Returns `true` if this value is NaN.
270    ///
271    /// ```
272    /// #![feature(f16)]
273    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
274    ///
275    /// let nan = f16::NAN;
276    /// let f = 7.0_f16;
277    ///
278    /// assert!(nan.is_nan());
279    /// assert!(!f.is_nan());
280    /// # }
281    /// ```
282    #[inline]
283    #[must_use]
284    #[unstable(feature = "f16", issue = "116909")]
285    #[allow(clippy::eq_op)] // > if you intended to check if the operand is NaN, use `.is_nan()` instead :)
286    pub const fn is_nan(self) -> bool {
287        self != self
288    }
289
290    /// Returns `true` if this value is positive infinity or negative infinity, and
291    /// `false` otherwise.
292    ///
293    /// ```
294    /// #![feature(f16)]
295    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
296    ///
297    /// let f = 7.0f16;
298    /// let inf = f16::INFINITY;
299    /// let neg_inf = f16::NEG_INFINITY;
300    /// let nan = f16::NAN;
301    ///
302    /// assert!(!f.is_infinite());
303    /// assert!(!nan.is_infinite());
304    ///
305    /// assert!(inf.is_infinite());
306    /// assert!(neg_inf.is_infinite());
307    /// # }
308    /// ```
309    #[inline]
310    #[must_use]
311    #[unstable(feature = "f16", issue = "116909")]
312    pub const fn is_infinite(self) -> bool {
313        (self == f16::INFINITY) | (self == f16::NEG_INFINITY)
314    }
315
316    /// Returns `true` if this number is neither infinite nor NaN.
317    ///
318    /// ```
319    /// #![feature(f16)]
320    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
321    ///
322    /// let f = 7.0f16;
323    /// let inf: f16 = f16::INFINITY;
324    /// let neg_inf: f16 = f16::NEG_INFINITY;
325    /// let nan: f16 = f16::NAN;
326    ///
327    /// assert!(f.is_finite());
328    ///
329    /// assert!(!nan.is_finite());
330    /// assert!(!inf.is_finite());
331    /// assert!(!neg_inf.is_finite());
332    /// # }
333    /// ```
334    #[inline]
335    #[must_use]
336    #[unstable(feature = "f16", issue = "116909")]
337    #[rustc_const_unstable(feature = "f16", issue = "116909")]
338    pub const fn is_finite(self) -> bool {
339        // There's no need to handle NaN separately: if self is NaN,
340        // the comparison is not true, exactly as desired.
341        self.abs() < Self::INFINITY
342    }
343
344    /// Returns `true` if the number is [subnormal].
345    ///
346    /// ```
347    /// #![feature(f16)]
348    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
349    ///
350    /// let min = f16::MIN_POSITIVE; // 6.1035e-5
351    /// let max = f16::MAX;
352    /// let lower_than_min = 1.0e-7_f16;
353    /// let zero = 0.0_f16;
354    ///
355    /// assert!(!min.is_subnormal());
356    /// assert!(!max.is_subnormal());
357    ///
358    /// assert!(!zero.is_subnormal());
359    /// assert!(!f16::NAN.is_subnormal());
360    /// assert!(!f16::INFINITY.is_subnormal());
361    /// // Values between `0` and `min` are Subnormal.
362    /// assert!(lower_than_min.is_subnormal());
363    /// # }
364    /// ```
365    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
366    #[inline]
367    #[must_use]
368    #[unstable(feature = "f16", issue = "116909")]
369    pub const fn is_subnormal(self) -> bool {
370        matches!(self.classify(), FpCategory::Subnormal)
371    }
372
373    /// Returns `true` if the number is neither zero, infinite, [subnormal], or NaN.
374    ///
375    /// ```
376    /// #![feature(f16)]
377    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
378    ///
379    /// let min = f16::MIN_POSITIVE; // 6.1035e-5
380    /// let max = f16::MAX;
381    /// let lower_than_min = 1.0e-7_f16;
382    /// let zero = 0.0_f16;
383    ///
384    /// assert!(min.is_normal());
385    /// assert!(max.is_normal());
386    ///
387    /// assert!(!zero.is_normal());
388    /// assert!(!f16::NAN.is_normal());
389    /// assert!(!f16::INFINITY.is_normal());
390    /// // Values between `0` and `min` are Subnormal.
391    /// assert!(!lower_than_min.is_normal());
392    /// # }
393    /// ```
394    /// [subnormal]: https://en.wikipedia.org/wiki/Denormal_number
395    #[inline]
396    #[must_use]
397    #[unstable(feature = "f16", issue = "116909")]
398    pub const fn is_normal(self) -> bool {
399        matches!(self.classify(), FpCategory::Normal)
400    }
401
402    /// Returns the floating point category of the number. If only one property
403    /// is going to be tested, it is generally faster to use the specific
404    /// predicate instead.
405    ///
406    /// ```
407    /// #![feature(f16)]
408    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
409    ///
410    /// use std::num::FpCategory;
411    ///
412    /// let num = 12.4_f16;
413    /// let inf = f16::INFINITY;
414    ///
415    /// assert_eq!(num.classify(), FpCategory::Normal);
416    /// assert_eq!(inf.classify(), FpCategory::Infinite);
417    /// # }
418    /// ```
419    #[inline]
420    #[unstable(feature = "f16", issue = "116909")]
421    pub const fn classify(self) -> FpCategory {
422        let b = self.to_bits();
423        match (b & Self::MAN_MASK, b & Self::EXP_MASK) {
424            (0, Self::EXP_MASK) => FpCategory::Infinite,
425            (_, Self::EXP_MASK) => FpCategory::Nan,
426            (0, 0) => FpCategory::Zero,
427            (_, 0) => FpCategory::Subnormal,
428            _ => FpCategory::Normal,
429        }
430    }
431
432    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
433    /// positive sign bit and positive infinity.
434    ///
435    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
436    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
437    /// conserved over arithmetic operations, the result of `is_sign_positive` on
438    /// a NaN might produce an unexpected or non-portable result. See the [specification
439    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
440    /// if you need fully portable behavior (will return `false` for all NaNs).
441    ///
442    /// ```
443    /// #![feature(f16)]
444    /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
445    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
446    ///
447    /// let f = 7.0_f16;
448    /// let g = -7.0_f16;
449    ///
450    /// assert!(f.is_sign_positive());
451    /// assert!(!g.is_sign_positive());
452    /// # }
453    /// ```
454    #[inline]
455    #[must_use]
456    #[unstable(feature = "f16", issue = "116909")]
457    pub const fn is_sign_positive(self) -> bool {
458        !self.is_sign_negative()
459    }
460
461    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
462    /// negative sign bit and negative infinity.
463    ///
464    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
465    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
466    /// conserved over arithmetic operations, the result of `is_sign_negative` on
467    /// a NaN might produce an unexpected or non-portable result. See the [specification
468    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
469    /// if you need fully portable behavior (will return `false` for all NaNs).
470    ///
471    /// ```
472    /// #![feature(f16)]
473    /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
474    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
475    ///
476    /// let f = 7.0_f16;
477    /// let g = -7.0_f16;
478    ///
479    /// assert!(!f.is_sign_negative());
480    /// assert!(g.is_sign_negative());
481    /// # }
482    /// ```
483    #[inline]
484    #[must_use]
485    #[unstable(feature = "f16", issue = "116909")]
486    pub const fn is_sign_negative(self) -> bool {
487        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
488        // applies to zeros and NaNs as well.
489        // SAFETY: This is just transmuting to get the sign bit, it's fine.
490        (self.to_bits() & (1 << 15)) != 0
491    }
492
493    /// Returns the least number greater than `self`.
494    ///
495    /// Let `TINY` be the smallest representable positive `f16`. Then,
496    ///  - if `self.is_nan()`, this returns `self`;
497    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
498    ///  - if `self` is `-TINY`, this returns -0.0;
499    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
500    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
501    ///  - otherwise the unique least value greater than `self` is returned.
502    ///
503    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
504    /// is finite `x == x.next_up().next_down()` also holds.
505    ///
506    /// ```rust
507    /// #![feature(f16)]
508    /// # // FIXME(f16_f128): ABI issues on MSVC
509    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
510    ///
511    /// // f16::EPSILON is the difference between 1.0 and the next number up.
512    /// assert_eq!(1.0f16.next_up(), 1.0 + f16::EPSILON);
513    /// // But not for most numbers.
514    /// assert!(0.1f16.next_up() < 0.1 + f16::EPSILON);
515    /// assert_eq!(4356f16.next_up(), 4360.0);
516    /// # }
517    /// ```
518    ///
519    /// This operation corresponds to IEEE-754 `nextUp`.
520    ///
521    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
522    /// [`INFINITY`]: Self::INFINITY
523    /// [`MIN`]: Self::MIN
524    /// [`MAX`]: Self::MAX
525    #[inline]
526    #[doc(alias = "nextUp")]
527    #[unstable(feature = "f16", issue = "116909")]
528    pub const fn next_up(self) -> Self {
529        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
530        // denormals to zero. This is in general unsound and unsupported, but here
531        // we do our best to still produce the correct result on such targets.
532        let bits = self.to_bits();
533        if self.is_nan() || bits == Self::INFINITY.to_bits() {
534            return self;
535        }
536
537        let abs = bits & !Self::SIGN_MASK;
538        let next_bits = if abs == 0 {
539            Self::TINY_BITS
540        } else if bits == abs {
541            bits + 1
542        } else {
543            bits - 1
544        };
545        Self::from_bits(next_bits)
546    }
547
548    /// Returns the greatest number less than `self`.
549    ///
550    /// Let `TINY` be the smallest representable positive `f16`. Then,
551    ///  - if `self.is_nan()`, this returns `self`;
552    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
553    ///  - if `self` is `TINY`, this returns 0.0;
554    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
555    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
556    ///  - otherwise the unique greatest value less than `self` is returned.
557    ///
558    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
559    /// is finite `x == x.next_down().next_up()` also holds.
560    ///
561    /// ```rust
562    /// #![feature(f16)]
563    /// # // FIXME(f16_f128): ABI issues on MSVC
564    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
565    ///
566    /// let x = 1.0f16;
567    /// // Clamp value into range [0, 1).
568    /// let clamped = x.clamp(0.0, 1.0f16.next_down());
569    /// assert!(clamped < 1.0);
570    /// assert_eq!(clamped.next_up(), 1.0);
571    /// # }
572    /// ```
573    ///
574    /// This operation corresponds to IEEE-754 `nextDown`.
575    ///
576    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
577    /// [`INFINITY`]: Self::INFINITY
578    /// [`MIN`]: Self::MIN
579    /// [`MAX`]: Self::MAX
580    #[inline]
581    #[doc(alias = "nextDown")]
582    #[unstable(feature = "f16", issue = "116909")]
583    pub const fn next_down(self) -> Self {
584        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
585        // denormals to zero. This is in general unsound and unsupported, but here
586        // we do our best to still produce the correct result on such targets.
587        let bits = self.to_bits();
588        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
589            return self;
590        }
591
592        let abs = bits & !Self::SIGN_MASK;
593        let next_bits = if abs == 0 {
594            Self::NEG_TINY_BITS
595        } else if bits == abs {
596            bits - 1
597        } else {
598            bits + 1
599        };
600        Self::from_bits(next_bits)
601    }
602
603    /// Takes the reciprocal (inverse) of a number, `1/x`.
604    ///
605    /// ```
606    /// #![feature(f16)]
607    /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
608    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
609    ///
610    /// let x = 2.0_f16;
611    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
612    ///
613    /// assert!(abs_difference <= f16::EPSILON);
614    /// # }
615    /// ```
616    #[inline]
617    #[unstable(feature = "f16", issue = "116909")]
618    #[must_use = "this returns the result of the operation, without modifying the original"]
619    pub const fn recip(self) -> Self {
620        1.0 / self
621    }
622
623    /// Converts radians to degrees.
624    ///
625    /// ```
626    /// #![feature(f16)]
627    /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
628    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
629    ///
630    /// let angle = std::f16::consts::PI;
631    ///
632    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
633    /// assert!(abs_difference <= 0.5);
634    /// # }
635    /// ```
636    #[inline]
637    #[unstable(feature = "f16", issue = "116909")]
638    #[must_use = "this returns the result of the operation, without modifying the original"]
639    pub const fn to_degrees(self) -> Self {
640        // Use a literal for better precision.
641        const PIS_IN_180: f16 = 57.2957795130823208767981548141051703_f16;
642        self * PIS_IN_180
643    }
644
645    /// Converts degrees to radians.
646    ///
647    /// ```
648    /// #![feature(f16)]
649    /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
650    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
651    ///
652    /// let angle = 180.0f16;
653    ///
654    /// let abs_difference = (angle.to_radians() - std::f16::consts::PI).abs();
655    ///
656    /// assert!(abs_difference <= 0.01);
657    /// # }
658    /// ```
659    #[inline]
660    #[unstable(feature = "f16", issue = "116909")]
661    #[must_use = "this returns the result of the operation, without modifying the original"]
662    pub const fn to_radians(self) -> f16 {
663        // Use a literal for better precision.
664        const RADS_PER_DEG: f16 = 0.017453292519943295769236907684886_f16;
665        self * RADS_PER_DEG
666    }
667
668    /// Returns the maximum of the two numbers, ignoring NaN.
669    ///
670    /// If one of the arguments is NaN, then the other argument is returned.
671    /// This follows the IEEE 754-2008 semantics for maxNum, except for handling of signaling NaNs;
672    /// this function handles all NaNs the same way and avoids maxNum's problems with associativity.
673    /// This also matches the behavior of libm’s fmax. In particular, if the inputs compare equal
674    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
675    ///
676    /// ```
677    /// #![feature(f16)]
678    /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
679    ///
680    /// let x = 1.0f16;
681    /// let y = 2.0f16;
682    ///
683    /// assert_eq!(x.max(y), y);
684    /// # }
685    /// ```
686    #[inline]
687    #[unstable(feature = "f16", issue = "116909")]
688    #[rustc_const_unstable(feature = "f16", issue = "116909")]
689    #[must_use = "this returns the result of the comparison, without modifying either input"]
690    pub const fn max(self, other: f16) -> f16 {
691        intrinsics::maxnumf16(self, other)
692    }
693
694    /// Returns the minimum of the two numbers, ignoring NaN.
695    ///
696    /// If one of the arguments is NaN, then the other argument is returned.
697    /// This follows the IEEE 754-2008 semantics for minNum, except for handling of signaling NaNs;
698    /// this function handles all NaNs the same way and avoids minNum's problems with associativity.
699    /// This also matches the behavior of libm’s fmin. In particular, if the inputs compare equal
700    /// (such as for the case of `+0.0` and `-0.0`), either input may be returned non-deterministically.
701    ///
702    /// ```
703    /// #![feature(f16)]
704    /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
705    ///
706    /// let x = 1.0f16;
707    /// let y = 2.0f16;
708    ///
709    /// assert_eq!(x.min(y), x);
710    /// # }
711    /// ```
712    #[inline]
713    #[unstable(feature = "f16", issue = "116909")]
714    #[rustc_const_unstable(feature = "f16", issue = "116909")]
715    #[must_use = "this returns the result of the comparison, without modifying either input"]
716    pub const fn min(self, other: f16) -> f16 {
717        intrinsics::minnumf16(self, other)
718    }
719
720    /// Returns the maximum of the two numbers, propagating NaN.
721    ///
722    /// This returns NaN when *either* argument is NaN, as opposed to
723    /// [`f16::max`] which only returns NaN when *both* arguments are NaN.
724    ///
725    /// ```
726    /// #![feature(f16)]
727    /// #![feature(float_minimum_maximum)]
728    /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
729    ///
730    /// let x = 1.0f16;
731    /// let y = 2.0f16;
732    ///
733    /// assert_eq!(x.maximum(y), y);
734    /// assert!(x.maximum(f16::NAN).is_nan());
735    /// # }
736    /// ```
737    ///
738    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the greater
739    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
740    /// Note that this follows the semantics specified in IEEE 754-2019.
741    ///
742    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
743    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
744    #[inline]
745    #[unstable(feature = "f16", issue = "116909")]
746    // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
747    #[must_use = "this returns the result of the comparison, without modifying either input"]
748    pub const fn maximum(self, other: f16) -> f16 {
749        if self > other {
750            self
751        } else if other > self {
752            other
753        } else if self == other {
754            if self.is_sign_positive() && other.is_sign_negative() { self } else { other }
755        } else {
756            self + other
757        }
758    }
759
760    /// Returns the minimum of the two numbers, propagating NaN.
761    ///
762    /// This returns NaN when *either* argument is NaN, as opposed to
763    /// [`f16::min`] which only returns NaN when *both* arguments are NaN.
764    ///
765    /// ```
766    /// #![feature(f16)]
767    /// #![feature(float_minimum_maximum)]
768    /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
769    ///
770    /// let x = 1.0f16;
771    /// let y = 2.0f16;
772    ///
773    /// assert_eq!(x.minimum(y), x);
774    /// assert!(x.minimum(f16::NAN).is_nan());
775    /// # }
776    /// ```
777    ///
778    /// If one of the arguments is NaN, then NaN is returned. Otherwise this returns the lesser
779    /// of the two numbers. For this operation, -0.0 is considered to be less than +0.0.
780    /// Note that this follows the semantics specified in IEEE 754-2019.
781    ///
782    /// Also note that "propagation" of NaNs here doesn't necessarily mean that the bitpattern of a NaN
783    /// operand is conserved; see the [specification of NaN bit patterns](f32#nan-bit-patterns) for more info.
784    #[inline]
785    #[unstable(feature = "f16", issue = "116909")]
786    // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
787    #[must_use = "this returns the result of the comparison, without modifying either input"]
788    pub const fn minimum(self, other: f16) -> f16 {
789        if self < other {
790            self
791        } else if other < self {
792            other
793        } else if self == other {
794            if self.is_sign_negative() && other.is_sign_positive() { self } else { other }
795        } else {
796            // At least one input is NaN. Use `+` to perform NaN propagation and quieting.
797            self + other
798        }
799    }
800
801    /// Calculates the midpoint (average) between `self` and `rhs`.
802    ///
803    /// This returns NaN when *either* argument is NaN or if a combination of
804    /// +inf and -inf is provided as arguments.
805    ///
806    /// # Examples
807    ///
808    /// ```
809    /// #![feature(f16)]
810    /// # #[cfg(target_arch = "aarch64")] { // FIXME(f16_F128): rust-lang/rust#123885
811    ///
812    /// assert_eq!(1f16.midpoint(4.0), 2.5);
813    /// assert_eq!((-5.5f16).midpoint(8.0), 1.25);
814    /// # }
815    /// ```
816    #[inline]
817    #[doc(alias = "average")]
818    #[unstable(feature = "f16", issue = "116909")]
819    #[rustc_const_unstable(feature = "f16", issue = "116909")]
820    pub const fn midpoint(self, other: f16) -> f16 {
821        const LO: f16 = f16::MIN_POSITIVE * 2.;
822        const HI: f16 = f16::MAX / 2.;
823
824        let (a, b) = (self, other);
825        let abs_a = a.abs();
826        let abs_b = b.abs();
827
828        if abs_a <= HI && abs_b <= HI {
829            // Overflow is impossible
830            (a + b) / 2.
831        } else if abs_a < LO {
832            // Not safe to halve `a` (would underflow)
833            a + (b / 2.)
834        } else if abs_b < LO {
835            // Not safe to halve `b` (would underflow)
836            (a / 2.) + b
837        } else {
838            // Safe to halve `a` and `b`
839            (a / 2.) + (b / 2.)
840        }
841    }
842
843    /// Rounds toward zero and converts to any primitive integer type,
844    /// assuming that the value is finite and fits in that type.
845    ///
846    /// ```
847    /// #![feature(f16)]
848    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
849    ///
850    /// let value = 4.6_f16;
851    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
852    /// assert_eq!(rounded, 4);
853    ///
854    /// let value = -128.9_f16;
855    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
856    /// assert_eq!(rounded, i8::MIN);
857    /// # }
858    /// ```
859    ///
860    /// # Safety
861    ///
862    /// The value must:
863    ///
864    /// * Not be `NaN`
865    /// * Not be infinite
866    /// * Be representable in the return type `Int`, after truncating off its fractional part
867    #[inline]
868    #[unstable(feature = "f16", issue = "116909")]
869    #[must_use = "this returns the result of the operation, without modifying the original"]
870    pub unsafe fn to_int_unchecked<Int>(self) -> Int
871    where
872        Self: FloatToInt<Int>,
873    {
874        // SAFETY: the caller must uphold the safety contract for
875        // `FloatToInt::to_int_unchecked`.
876        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
877    }
878
879    /// Raw transmutation to `u16`.
880    ///
881    /// This is currently identical to `transmute::<f16, u16>(self)` on all platforms.
882    ///
883    /// See [`from_bits`](#method.from_bits) for some discussion of the
884    /// portability of this operation (there are almost no issues).
885    ///
886    /// Note that this function is distinct from `as` casting, which attempts to
887    /// preserve the *numeric* value, and not the bitwise value.
888    ///
889    /// ```
890    /// #![feature(f16)]
891    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
892    ///
893    /// # // FIXME(f16_f128): enable this once const casting works
894    /// # // assert_ne!((1f16).to_bits(), 1f16 as u128); // to_bits() is not casting!
895    /// assert_eq!((12.5f16).to_bits(), 0x4a40);
896    /// # }
897    /// ```
898    #[inline]
899    #[unstable(feature = "f16", issue = "116909")]
900    #[must_use = "this returns the result of the operation, without modifying the original"]
901    #[cfg_attr(not(bootstrap), allow(unnecessary_transmutes))]
902    pub const fn to_bits(self) -> u16 {
903        // SAFETY: `u16` is a plain old datatype so we can always transmute to it.
904        unsafe { mem::transmute(self) }
905    }
906
907    /// Raw transmutation from `u16`.
908    ///
909    /// This is currently identical to `transmute::<u16, f16>(v)` on all platforms.
910    /// It turns out this is incredibly portable, for two reasons:
911    ///
912    /// * Floats and Ints have the same endianness on all supported platforms.
913    /// * IEEE 754 very precisely specifies the bit layout of floats.
914    ///
915    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
916    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
917    /// (notably x86 and ARM) picked the interpretation that was ultimately
918    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
919    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
920    ///
921    /// Rather than trying to preserve signaling-ness cross-platform, this
922    /// implementation favors preserving the exact bits. This means that
923    /// any payloads encoded in NaNs will be preserved even if the result of
924    /// this method is sent over the network from an x86 machine to a MIPS one.
925    ///
926    /// If the results of this method are only manipulated by the same
927    /// architecture that produced them, then there is no portability concern.
928    ///
929    /// If the input isn't NaN, then there is no portability concern.
930    ///
931    /// If you don't care about signalingness (very likely), then there is no
932    /// portability concern.
933    ///
934    /// Note that this function is distinct from `as` casting, which attempts to
935    /// preserve the *numeric* value, and not the bitwise value.
936    ///
937    /// ```
938    /// #![feature(f16)]
939    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
940    ///
941    /// let v = f16::from_bits(0x4a40);
942    /// assert_eq!(v, 12.5);
943    /// # }
944    /// ```
945    #[inline]
946    #[must_use]
947    #[unstable(feature = "f16", issue = "116909")]
948    #[cfg_attr(not(bootstrap), allow(unnecessary_transmutes))]
949    pub const fn from_bits(v: u16) -> Self {
950        // It turns out the safety issues with sNaN were overblown! Hooray!
951        // SAFETY: `u16` is a plain old datatype so we can always transmute from it.
952        unsafe { mem::transmute(v) }
953    }
954
955    /// Returns the memory representation of this floating point number as a byte array in
956    /// big-endian (network) byte order.
957    ///
958    /// See [`from_bits`](Self::from_bits) for some discussion of the
959    /// portability of this operation (there are almost no issues).
960    ///
961    /// # Examples
962    ///
963    /// ```
964    /// #![feature(f16)]
965    /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
966    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
967    ///
968    /// let bytes = 12.5f16.to_be_bytes();
969    /// assert_eq!(bytes, [0x4a, 0x40]);
970    /// # }
971    /// ```
972    #[inline]
973    #[unstable(feature = "f16", issue = "116909")]
974    #[must_use = "this returns the result of the operation, without modifying the original"]
975    pub const fn to_be_bytes(self) -> [u8; 2] {
976        self.to_bits().to_be_bytes()
977    }
978
979    /// Returns the memory representation of this floating point number as a byte array in
980    /// little-endian byte order.
981    ///
982    /// See [`from_bits`](Self::from_bits) for some discussion of the
983    /// portability of this operation (there are almost no issues).
984    ///
985    /// # Examples
986    ///
987    /// ```
988    /// #![feature(f16)]
989    /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
990    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
991    ///
992    /// let bytes = 12.5f16.to_le_bytes();
993    /// assert_eq!(bytes, [0x40, 0x4a]);
994    /// # }
995    /// ```
996    #[inline]
997    #[unstable(feature = "f16", issue = "116909")]
998    #[must_use = "this returns the result of the operation, without modifying the original"]
999    pub const fn to_le_bytes(self) -> [u8; 2] {
1000        self.to_bits().to_le_bytes()
1001    }
1002
1003    /// Returns the memory representation of this floating point number as a byte array in
1004    /// native byte order.
1005    ///
1006    /// As the target platform's native endianness is used, portable code
1007    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1008    ///
1009    /// [`to_be_bytes`]: f16::to_be_bytes
1010    /// [`to_le_bytes`]: f16::to_le_bytes
1011    ///
1012    /// See [`from_bits`](Self::from_bits) for some discussion of the
1013    /// portability of this operation (there are almost no issues).
1014    ///
1015    /// # Examples
1016    ///
1017    /// ```
1018    /// #![feature(f16)]
1019    /// # // FIXME(f16_f128): LLVM crashes on s390x, llvm/llvm-project#50374
1020    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1021    ///
1022    /// let bytes = 12.5f16.to_ne_bytes();
1023    /// assert_eq!(
1024    ///     bytes,
1025    ///     if cfg!(target_endian = "big") {
1026    ///         [0x4a, 0x40]
1027    ///     } else {
1028    ///         [0x40, 0x4a]
1029    ///     }
1030    /// );
1031    /// # }
1032    /// ```
1033    #[inline]
1034    #[unstable(feature = "f16", issue = "116909")]
1035    #[must_use = "this returns the result of the operation, without modifying the original"]
1036    pub const fn to_ne_bytes(self) -> [u8; 2] {
1037        self.to_bits().to_ne_bytes()
1038    }
1039
1040    /// Creates a floating point value from its representation as a byte array in big endian.
1041    ///
1042    /// See [`from_bits`](Self::from_bits) for some discussion of the
1043    /// portability of this operation (there are almost no issues).
1044    ///
1045    /// # Examples
1046    ///
1047    /// ```
1048    /// #![feature(f16)]
1049    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1050    ///
1051    /// let value = f16::from_be_bytes([0x4a, 0x40]);
1052    /// assert_eq!(value, 12.5);
1053    /// # }
1054    /// ```
1055    #[inline]
1056    #[must_use]
1057    #[unstable(feature = "f16", issue = "116909")]
1058    pub const fn from_be_bytes(bytes: [u8; 2]) -> Self {
1059        Self::from_bits(u16::from_be_bytes(bytes))
1060    }
1061
1062    /// Creates a floating point value from its representation as a byte array in little endian.
1063    ///
1064    /// See [`from_bits`](Self::from_bits) for some discussion of the
1065    /// portability of this operation (there are almost no issues).
1066    ///
1067    /// # Examples
1068    ///
1069    /// ```
1070    /// #![feature(f16)]
1071    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1072    ///
1073    /// let value = f16::from_le_bytes([0x40, 0x4a]);
1074    /// assert_eq!(value, 12.5);
1075    /// # }
1076    /// ```
1077    #[inline]
1078    #[must_use]
1079    #[unstable(feature = "f16", issue = "116909")]
1080    pub const fn from_le_bytes(bytes: [u8; 2]) -> Self {
1081        Self::from_bits(u16::from_le_bytes(bytes))
1082    }
1083
1084    /// Creates a floating point value from its representation as a byte array in native endian.
1085    ///
1086    /// As the target platform's native endianness is used, portable code
1087    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1088    /// appropriate instead.
1089    ///
1090    /// [`from_be_bytes`]: f16::from_be_bytes
1091    /// [`from_le_bytes`]: f16::from_le_bytes
1092    ///
1093    /// See [`from_bits`](Self::from_bits) for some discussion of the
1094    /// portability of this operation (there are almost no issues).
1095    ///
1096    /// # Examples
1097    ///
1098    /// ```
1099    /// #![feature(f16)]
1100    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1101    ///
1102    /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") {
1103    ///     [0x4a, 0x40]
1104    /// } else {
1105    ///     [0x40, 0x4a]
1106    /// });
1107    /// assert_eq!(value, 12.5);
1108    /// # }
1109    /// ```
1110    #[inline]
1111    #[must_use]
1112    #[unstable(feature = "f16", issue = "116909")]
1113    pub const fn from_ne_bytes(bytes: [u8; 2]) -> Self {
1114        Self::from_bits(u16::from_ne_bytes(bytes))
1115    }
1116
1117    /// Returns the ordering between `self` and `other`.
1118    ///
1119    /// Unlike the standard partial comparison between floating point numbers,
1120    /// this comparison always produces an ordering in accordance to
1121    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1122    /// floating point standard. The values are ordered in the following sequence:
1123    ///
1124    /// - negative quiet NaN
1125    /// - negative signaling NaN
1126    /// - negative infinity
1127    /// - negative numbers
1128    /// - negative subnormal numbers
1129    /// - negative zero
1130    /// - positive zero
1131    /// - positive subnormal numbers
1132    /// - positive numbers
1133    /// - positive infinity
1134    /// - positive signaling NaN
1135    /// - positive quiet NaN.
1136    ///
1137    /// The ordering established by this function does not always agree with the
1138    /// [`PartialOrd`] and [`PartialEq`] implementations of `f16`. For example,
1139    /// they consider negative and positive zero equal, while `total_cmp`
1140    /// doesn't.
1141    ///
1142    /// The interpretation of the signaling NaN bit follows the definition in
1143    /// the IEEE 754 standard, which may not match the interpretation by some of
1144    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1145    ///
1146    /// # Example
1147    ///
1148    /// ```
1149    /// #![feature(f16)]
1150    /// # // FIXME(f16_f128): extendhfsf2, truncsfhf2, __gnu_h2f_ieee, __gnu_f2h_ieee missing for many platforms
1151    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1152    ///
1153    /// struct GoodBoy {
1154    ///     name: &'static str,
1155    ///     weight: f16,
1156    /// }
1157    ///
1158    /// let mut bois = vec![
1159    ///     GoodBoy { name: "Pucci", weight: 0.1 },
1160    ///     GoodBoy { name: "Woofer", weight: 99.0 },
1161    ///     GoodBoy { name: "Yapper", weight: 10.0 },
1162    ///     GoodBoy { name: "Chonk", weight: f16::INFINITY },
1163    ///     GoodBoy { name: "Abs. Unit", weight: f16::NAN },
1164    ///     GoodBoy { name: "Floaty", weight: -5.0 },
1165    /// ];
1166    ///
1167    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1168    ///
1169    /// // `f16::NAN` could be positive or negative, which will affect the sort order.
1170    /// if f16::NAN.is_sign_negative() {
1171    ///     bois.into_iter().map(|b| b.weight)
1172    ///         .zip([f16::NAN, -5.0, 0.1, 10.0, 99.0, f16::INFINITY].iter())
1173    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1174    /// } else {
1175    ///     bois.into_iter().map(|b| b.weight)
1176    ///         .zip([-5.0, 0.1, 10.0, 99.0, f16::INFINITY, f16::NAN].iter())
1177    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1178    /// }
1179    /// # }
1180    /// ```
1181    #[inline]
1182    #[must_use]
1183    #[unstable(feature = "f16", issue = "116909")]
1184    pub fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1185        let mut left = self.to_bits() as i16;
1186        let mut right = other.to_bits() as i16;
1187
1188        // In case of negatives, flip all the bits except the sign
1189        // to achieve a similar layout as two's complement integers
1190        //
1191        // Why does this work? IEEE 754 floats consist of three fields:
1192        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1193        // fields as a whole have the property that their bitwise order is
1194        // equal to the numeric magnitude where the magnitude is defined.
1195        // The magnitude is not normally defined on NaN values, but
1196        // IEEE 754 totalOrder defines the NaN values also to follow the
1197        // bitwise order. This leads to order explained in the doc comment.
1198        // However, the representation of magnitude is the same for negative
1199        // and positive numbers – only the sign bit is different.
1200        // To easily compare the floats as signed integers, we need to
1201        // flip the exponent and mantissa bits in case of negative numbers.
1202        // We effectively convert the numbers to "two's complement" form.
1203        //
1204        // To do the flipping, we construct a mask and XOR against it.
1205        // We branchlessly calculate an "all-ones except for the sign bit"
1206        // mask from negative-signed values: right shifting sign-extends
1207        // the integer, so we "fill" the mask with sign bits, and then
1208        // convert to unsigned to push one more zero bit.
1209        // On positive values, the mask is all zeros, so it's a no-op.
1210        left ^= (((left >> 15) as u16) >> 1) as i16;
1211        right ^= (((right >> 15) as u16) >> 1) as i16;
1212
1213        left.cmp(&right)
1214    }
1215
1216    /// Restrict a value to a certain interval unless it is NaN.
1217    ///
1218    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1219    /// less than `min`. Otherwise this returns `self`.
1220    ///
1221    /// Note that this function returns NaN if the initial value was NaN as
1222    /// well.
1223    ///
1224    /// # Panics
1225    ///
1226    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1227    ///
1228    /// # Examples
1229    ///
1230    /// ```
1231    /// #![feature(f16)]
1232    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1233    ///
1234    /// assert!((-3.0f16).clamp(-2.0, 1.0) == -2.0);
1235    /// assert!((0.0f16).clamp(-2.0, 1.0) == 0.0);
1236    /// assert!((2.0f16).clamp(-2.0, 1.0) == 1.0);
1237    /// assert!((f16::NAN).clamp(-2.0, 1.0).is_nan());
1238    /// # }
1239    /// ```
1240    #[inline]
1241    #[unstable(feature = "f16", issue = "116909")]
1242    #[must_use = "method returns a new number and does not mutate the original value"]
1243    pub const fn clamp(mut self, min: f16, max: f16) -> f16 {
1244        const_assert!(
1245            min <= max,
1246            "min > max, or either was NaN",
1247            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1248            min: f16,
1249            max: f16,
1250        );
1251
1252        if self < min {
1253            self = min;
1254        }
1255        if self > max {
1256            self = max;
1257        }
1258        self
1259    }
1260
1261    /// Computes the absolute value of `self`.
1262    ///
1263    /// This function always returns the precise result.
1264    ///
1265    /// # Examples
1266    ///
1267    /// ```
1268    /// #![feature(f16)]
1269    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1270    ///
1271    /// let x = 3.5_f16;
1272    /// let y = -3.5_f16;
1273    ///
1274    /// assert_eq!(x.abs(), x);
1275    /// assert_eq!(y.abs(), -y);
1276    ///
1277    /// assert!(f16::NAN.abs().is_nan());
1278    /// # }
1279    /// ```
1280    #[inline]
1281    #[unstable(feature = "f16", issue = "116909")]
1282    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1283    #[must_use = "method returns a new number and does not mutate the original value"]
1284    pub const fn abs(self) -> Self {
1285        // FIXME(f16_f128): replace with `intrinsics::fabsf16` when available
1286        Self::from_bits(self.to_bits() & !(1 << 15))
1287    }
1288
1289    /// Returns a number that represents the sign of `self`.
1290    ///
1291    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1292    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1293    /// - NaN if the number is NaN
1294    ///
1295    /// # Examples
1296    ///
1297    /// ```
1298    /// #![feature(f16)]
1299    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1300    ///
1301    /// let f = 3.5_f16;
1302    ///
1303    /// assert_eq!(f.signum(), 1.0);
1304    /// assert_eq!(f16::NEG_INFINITY.signum(), -1.0);
1305    ///
1306    /// assert!(f16::NAN.signum().is_nan());
1307    /// # }
1308    /// ```
1309    #[inline]
1310    #[unstable(feature = "f16", issue = "116909")]
1311    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1312    #[must_use = "method returns a new number and does not mutate the original value"]
1313    pub const fn signum(self) -> f16 {
1314        if self.is_nan() { Self::NAN } else { 1.0_f16.copysign(self) }
1315    }
1316
1317    /// Returns a number composed of the magnitude of `self` and the sign of
1318    /// `sign`.
1319    ///
1320    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1321    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1322    /// returned.
1323    ///
1324    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1325    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1326    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1327    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1328    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1329    /// info.
1330    ///
1331    /// # Examples
1332    ///
1333    /// ```
1334    /// #![feature(f16)]
1335    /// # #[cfg(all(target_arch = "x86_64", target_os = "linux"))] {
1336    ///
1337    /// let f = 3.5_f16;
1338    ///
1339    /// assert_eq!(f.copysign(0.42), 3.5_f16);
1340    /// assert_eq!(f.copysign(-0.42), -3.5_f16);
1341    /// assert_eq!((-f).copysign(0.42), 3.5_f16);
1342    /// assert_eq!((-f).copysign(-0.42), -3.5_f16);
1343    ///
1344    /// assert!(f16::NAN.copysign(1.0).is_nan());
1345    /// # }
1346    /// ```
1347    #[inline]
1348    #[unstable(feature = "f16", issue = "116909")]
1349    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1350    #[must_use = "method returns a new number and does not mutate the original value"]
1351    pub const fn copysign(self, sign: f16) -> f16 {
1352        // SAFETY: this is actually a safe intrinsic
1353        unsafe { intrinsics::copysignf16(self, sign) }
1354    }
1355
1356    /// Float addition that allows optimizations based on algebraic rules.
1357    ///
1358    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1359    #[must_use = "method returns a new number and does not mutate the original value"]
1360    #[unstable(feature = "float_algebraic", issue = "136469")]
1361    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1362    #[inline]
1363    pub const fn algebraic_add(self, rhs: f16) -> f16 {
1364        intrinsics::fadd_algebraic(self, rhs)
1365    }
1366
1367    /// Float subtraction that allows optimizations based on algebraic rules.
1368    ///
1369    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1370    #[must_use = "method returns a new number and does not mutate the original value"]
1371    #[unstable(feature = "float_algebraic", issue = "136469")]
1372    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1373    #[inline]
1374    pub const fn algebraic_sub(self, rhs: f16) -> f16 {
1375        intrinsics::fsub_algebraic(self, rhs)
1376    }
1377
1378    /// Float multiplication that allows optimizations based on algebraic rules.
1379    ///
1380    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1381    #[must_use = "method returns a new number and does not mutate the original value"]
1382    #[unstable(feature = "float_algebraic", issue = "136469")]
1383    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1384    #[inline]
1385    pub const fn algebraic_mul(self, rhs: f16) -> f16 {
1386        intrinsics::fmul_algebraic(self, rhs)
1387    }
1388
1389    /// Float division that allows optimizations based on algebraic rules.
1390    ///
1391    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1392    #[must_use = "method returns a new number and does not mutate the original value"]
1393    #[unstable(feature = "float_algebraic", issue = "136469")]
1394    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1395    #[inline]
1396    pub const fn algebraic_div(self, rhs: f16) -> f16 {
1397        intrinsics::fdiv_algebraic(self, rhs)
1398    }
1399
1400    /// Float remainder that allows optimizations based on algebraic rules.
1401    ///
1402    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1403    #[must_use = "method returns a new number and does not mutate the original value"]
1404    #[unstable(feature = "float_algebraic", issue = "136469")]
1405    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1406    #[inline]
1407    pub const fn algebraic_rem(self, rhs: f16) -> f16 {
1408        intrinsics::frem_algebraic(self, rhs)
1409    }
1410}