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