Skip to main content

core/num/
f16.rs

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