Skip to main content

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