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