Skip to main content

core/num/
f16.rs

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