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