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