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