Skip to main content

core/num/
f16.rs

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