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