Skip to main content

core/num/
f16.rs

1//! Constants for the `f16` half-precision floating point type.
2//!
3//! *[See also the `f16` primitive type][f16].*
4//!
5//! Mathematically significant numbers are provided in the `consts` sub-module.
6//!
7//! For the constants defined directly in this module
8//! (as distinct from those defined in the `consts` sub-module),
9//! new code should instead use the associated constants
10//! defined directly on the `f16` type.
11
12#![unstable(feature = "f16", issue = "116909")]
13
14use crate::convert::FloatToInt;
15use crate::num::FpCategory;
16#[cfg(not(test))]
17use crate::num::imp::libm;
18use crate::panic::const_assert;
19use crate::{intrinsics, mem};
20
21/// Basic mathematical constants.
22#[unstable(feature = "f16", issue = "116909")]
23#[rustc_diagnostic_item = "f16_consts_mod"]
24pub mod consts {
25    // FIXME: replace with mathematical constants from cmath.
26
27    /// Archimedes' constant (π)
28    #[unstable(feature = "f16", issue = "116909")]
29    pub const PI: f16 = 3.14159265358979323846264338327950288_f16;
30
31    /// The full circle constant (τ)
32    ///
33    /// Equal to 2π.
34    #[unstable(feature = "f16", issue = "116909")]
35    pub const TAU: f16 = 6.28318530717958647692528676655900577_f16;
36
37    /// The golden ratio (φ)
38    #[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    #[ferrocene::prevalidated]
569    #[inline]
570    #[unstable(feature = "f16", issue = "116909")]
571    #[must_use]
572    pub const fn classify(self) -> FpCategory {
573        let b = self.to_bits();
574        match (b & Self::MANTISSA_MASK, b & Self::EXPONENT_MASK) {
575            (0, Self::EXPONENT_MASK) => FpCategory::Infinite,
576            (_, Self::EXPONENT_MASK) => FpCategory::Nan,
577            (0, 0) => FpCategory::Zero,
578            (_, 0) => FpCategory::Subnormal,
579            _ => FpCategory::Normal,
580        }
581    }
582
583    /// Returns `true` if `self` has a positive sign, including `+0.0`, NaNs with
584    /// positive sign bit and positive infinity.
585    ///
586    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
587    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
588    /// conserved over arithmetic operations, the result of `is_sign_positive` on
589    /// a NaN might produce an unexpected or non-portable result. See the [specification
590    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == 1.0`
591    /// if you need fully portable behavior (will return `false` for all NaNs).
592    ///
593    /// ```
594    /// #![feature(f16)]
595    /// # #[cfg(target_has_reliable_f16)] {
596    ///
597    /// let f = 7.0_f16;
598    /// let g = -7.0_f16;
599    ///
600    /// assert!(f.is_sign_positive());
601    /// assert!(!g.is_sign_positive());
602    /// # }
603    /// ```
604    #[inline]
605    #[must_use]
606    #[unstable(feature = "f16", issue = "116909")]
607    pub const fn is_sign_positive(self) -> bool {
608        !self.is_sign_negative()
609    }
610
611    /// Returns `true` if `self` has a negative sign, including `-0.0`, NaNs with
612    /// negative sign bit and negative infinity.
613    ///
614    /// Note that IEEE 754 doesn't assign any meaning to the sign bit in case of
615    /// a NaN, and as Rust doesn't guarantee that the bit pattern of NaNs are
616    /// conserved over arithmetic operations, the result of `is_sign_negative` on
617    /// a NaN might produce an unexpected or non-portable result. See the [specification
618    /// of NaN bit patterns](f32#nan-bit-patterns) for more info. Use `self.signum() == -1.0`
619    /// if you need fully portable behavior (will return `false` for all NaNs).
620    ///
621    /// ```
622    /// #![feature(f16)]
623    /// # #[cfg(target_has_reliable_f16)] {
624    ///
625    /// let f = 7.0_f16;
626    /// let g = -7.0_f16;
627    ///
628    /// assert!(!f.is_sign_negative());
629    /// assert!(g.is_sign_negative());
630    /// # }
631    /// ```
632    #[inline]
633    #[must_use]
634    #[unstable(feature = "f16", issue = "116909")]
635    pub const fn is_sign_negative(self) -> bool {
636        // IEEE754 says: isSignMinus(x) is true if and only if x has negative sign. isSignMinus
637        // applies to zeros and NaNs as well.
638        // SAFETY: This is just transmuting to get the sign bit, it's fine.
639        (self.to_bits() & (1 << 15)) != 0
640    }
641
642    /// Returns the least number greater than `self`.
643    ///
644    /// Let `TINY` be the smallest representable positive `f16`. Then,
645    ///  - if `self.is_nan()`, this returns `self`;
646    ///  - if `self` is [`NEG_INFINITY`], this returns [`MIN`];
647    ///  - if `self` is `-TINY`, this returns -0.0;
648    ///  - if `self` is -0.0 or +0.0, this returns `TINY`;
649    ///  - if `self` is [`MAX`] or [`INFINITY`], this returns [`INFINITY`];
650    ///  - otherwise the unique least value greater than `self` is returned.
651    ///
652    /// The identity `x.next_up() == -(-x).next_down()` holds for all non-NaN `x`. When `x`
653    /// is finite `x == x.next_up().next_down()` also holds.
654    ///
655    /// ```rust
656    /// #![feature(f16)]
657    /// # #[cfg(target_has_reliable_f16)] {
658    ///
659    /// // f16::EPSILON is the difference between 1.0 and the next number up.
660    /// assert_eq!(1.0f16.next_up(), 1.0 + f16::EPSILON);
661    /// // But not for most numbers.
662    /// assert!(0.1f16.next_up() < 0.1 + f16::EPSILON);
663    /// assert_eq!(4356f16.next_up(), 4360.0);
664    /// # }
665    /// ```
666    ///
667    /// This operation corresponds to IEEE-754 `nextUp`.
668    ///
669    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
670    /// [`INFINITY`]: Self::INFINITY
671    /// [`MIN`]: Self::MIN
672    /// [`MAX`]: Self::MAX
673    #[inline]
674    #[doc(alias = "nextUp")]
675    #[unstable(feature = "f16", issue = "116909")]
676    #[must_use = "method returns a new number and does not mutate the original value"]
677    pub const fn next_up(self) -> Self {
678        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
679        // denormals to zero. This is in general unsound and unsupported, but here
680        // we do our best to still produce the correct result on such targets.
681        let bits = self.to_bits();
682        if self.is_nan() || bits == Self::INFINITY.to_bits() {
683            return self;
684        }
685
686        let abs = bits & !Self::SIGN_MASK;
687        let next_bits = if abs == 0 {
688            Self::TINY_BITS
689        } else if bits == abs {
690            bits + 1
691        } else {
692            bits - 1
693        };
694        Self::from_bits(next_bits)
695    }
696
697    /// Returns the greatest number less than `self`.
698    ///
699    /// Let `TINY` be the smallest representable positive `f16`. Then,
700    ///  - if `self.is_nan()`, this returns `self`;
701    ///  - if `self` is [`INFINITY`], this returns [`MAX`];
702    ///  - if `self` is `TINY`, this returns 0.0;
703    ///  - if `self` is -0.0 or +0.0, this returns `-TINY`;
704    ///  - if `self` is [`MIN`] or [`NEG_INFINITY`], this returns [`NEG_INFINITY`];
705    ///  - otherwise the unique greatest value less than `self` is returned.
706    ///
707    /// The identity `x.next_down() == -(-x).next_up()` holds for all non-NaN `x`. When `x`
708    /// is finite `x == x.next_down().next_up()` also holds.
709    ///
710    /// ```rust
711    /// #![feature(f16)]
712    /// # #[cfg(target_has_reliable_f16)] {
713    ///
714    /// let x = 1.0f16;
715    /// // Clamp value into range [0, 1).
716    /// let clamped = x.clamp(0.0, 1.0f16.next_down());
717    /// assert!(clamped < 1.0);
718    /// assert_eq!(clamped.next_up(), 1.0);
719    /// # }
720    /// ```
721    ///
722    /// This operation corresponds to IEEE-754 `nextDown`.
723    ///
724    /// [`NEG_INFINITY`]: Self::NEG_INFINITY
725    /// [`INFINITY`]: Self::INFINITY
726    /// [`MIN`]: Self::MIN
727    /// [`MAX`]: Self::MAX
728    #[inline]
729    #[doc(alias = "nextDown")]
730    #[unstable(feature = "f16", issue = "116909")]
731    #[must_use = "method returns a new number and does not mutate the original value"]
732    pub const fn next_down(self) -> Self {
733        // Some targets violate Rust's assumption of IEEE semantics, e.g. by flushing
734        // denormals to zero. This is in general unsound and unsupported, but here
735        // we do our best to still produce the correct result on such targets.
736        let bits = self.to_bits();
737        if self.is_nan() || bits == Self::NEG_INFINITY.to_bits() {
738            return self;
739        }
740
741        let abs = bits & !Self::SIGN_MASK;
742        let next_bits = if abs == 0 {
743            Self::NEG_TINY_BITS
744        } else if bits == abs {
745            bits - 1
746        } else {
747            bits + 1
748        };
749        Self::from_bits(next_bits)
750    }
751
752    /// Takes the reciprocal (inverse) of a number, `1/x`.
753    ///
754    /// ```
755    /// #![feature(f16)]
756    /// # #[cfg(target_has_reliable_f16)] {
757    ///
758    /// let x = 2.0_f16;
759    /// let abs_difference = (x.recip() - (1.0 / x)).abs();
760    ///
761    /// assert!(abs_difference <= f16::EPSILON);
762    /// # }
763    /// ```
764    #[inline]
765    #[unstable(feature = "f16", issue = "116909")]
766    #[must_use = "this returns the result of the operation, without modifying the original"]
767    pub const fn recip(self) -> Self {
768        1.0 / self
769    }
770
771    /// Converts radians to degrees.
772    ///
773    /// # Unspecified precision
774    ///
775    /// The precision of this function is non-deterministic. This means it varies by platform,
776    /// Rust version, and can even differ within the same execution from one invocation to the next.
777    ///
778    /// # Examples
779    ///
780    /// ```
781    /// #![feature(f16)]
782    /// # #[cfg(target_has_reliable_f16)] {
783    ///
784    /// let angle = std::f16::consts::PI;
785    ///
786    /// let abs_difference = (angle.to_degrees() - 180.0).abs();
787    /// assert!(abs_difference <= 0.5);
788    /// # }
789    /// ```
790    #[inline]
791    #[unstable(feature = "f16", issue = "116909")]
792    #[must_use = "this returns the result of the operation, without modifying the original"]
793    pub const fn to_degrees(self) -> Self {
794        // Use a literal to avoid double rounding, consts::PI is already rounded,
795        // and dividing would round again.
796        const PIS_IN_180: f16 = 57.2957795130823208767981548141051703_f16;
797        self * PIS_IN_180
798    }
799
800    /// Converts degrees to radians.
801    ///
802    /// # Unspecified precision
803    ///
804    /// The precision of this function is non-deterministic. This means it varies by platform,
805    /// Rust version, and can even differ within the same execution from one invocation to the next.
806    ///
807    /// # Examples
808    ///
809    /// ```
810    /// #![feature(f16)]
811    /// # #[cfg(target_has_reliable_f16)] {
812    ///
813    /// let angle = 180.0f16;
814    ///
815    /// let abs_difference = (angle.to_radians() - std::f16::consts::PI).abs();
816    ///
817    /// assert!(abs_difference <= 0.01);
818    /// # }
819    /// ```
820    #[inline]
821    #[unstable(feature = "f16", issue = "116909")]
822    #[must_use = "this returns the result of the operation, without modifying the original"]
823    pub const fn to_radians(self) -> f16 {
824        // Use a literal to avoid double rounding, consts::PI is already rounded,
825        // and dividing would round again.
826        const RADS_PER_DEG: f16 = 0.017453292519943295769236907684886_f16;
827        self * RADS_PER_DEG
828    }
829
830    /// Returns the maximum of the two numbers, ignoring NaN.
831    ///
832    /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
833    /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
834    /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
835    /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
836    /// non-deterministically.
837    ///
838    /// The handling of NaNs follows the IEEE 754-2019 semantics for `maximumNumber`, treating all
839    /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
840    /// follows the IEEE 754-2008 semantics for `maxNum`.
841    ///
842    /// ```
843    /// #![feature(f16)]
844    /// # #[cfg(target_has_reliable_f16)] {
845    ///
846    /// let x = 1.0f16;
847    /// let y = 2.0f16;
848    ///
849    /// assert_eq!(x.max(y), y);
850    /// assert_eq!(x.max(f16::NAN), x);
851    /// # }
852    /// ```
853    #[inline]
854    #[unstable(feature = "f16", issue = "116909")]
855    #[rustc_const_unstable(feature = "f16", issue = "116909")]
856    #[must_use = "this returns the result of the comparison, without modifying either input"]
857    pub const fn max(self, other: f16) -> f16 {
858        intrinsics::maximum_number_nsz_f16(self, other)
859    }
860
861    /// Returns the minimum of the two numbers, ignoring NaN.
862    ///
863    /// If exactly one of the arguments is NaN (quiet or signaling), then the other argument is
864    /// returned. If both arguments are NaN, the return value is NaN, with the bit pattern picked
865    /// using the usual [rules for arithmetic operations](f32#nan-bit-patterns). If the inputs
866    /// compare equal (such as for the case of `+0.0` and `-0.0`), either input may be returned
867    /// non-deterministically.
868    ///
869    /// The handling of NaNs follows the IEEE 754-2019 semantics for `minimumNumber`, treating all
870    /// NaNs the same way to ensure the operation is associative. The handling of signed zeros
871    /// follows the IEEE 754-2008 semantics for `minNum`.
872    ///
873    /// ```
874    /// #![feature(f16)]
875    /// # #[cfg(target_has_reliable_f16)] {
876    ///
877    /// let x = 1.0f16;
878    /// let y = 2.0f16;
879    ///
880    /// assert_eq!(x.min(y), x);
881    /// assert_eq!(x.min(f16::NAN), x);
882    /// # }
883    /// ```
884    #[inline]
885    #[unstable(feature = "f16", issue = "116909")]
886    #[rustc_const_unstable(feature = "f16", issue = "116909")]
887    #[must_use = "this returns the result of the comparison, without modifying either input"]
888    pub const fn min(self, other: f16) -> f16 {
889        intrinsics::minimum_number_nsz_f16(self, other)
890    }
891
892    /// Returns the maximum of the two numbers, propagating NaN.
893    ///
894    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
895    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
896    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
897    /// non-NaN inputs.
898    ///
899    /// This is in contrast to [`f16::max`] which only returns NaN when *both* arguments are NaN,
900    /// and which does not reliably order `-0.0` and `+0.0`.
901    ///
902    /// This follows the IEEE 754-2019 semantics for `maximum`.
903    ///
904    /// ```
905    /// #![feature(f16)]
906    /// #![feature(float_minimum_maximum)]
907    /// # #[cfg(target_has_reliable_f16)] {
908    ///
909    /// let x = 1.0f16;
910    /// let y = 2.0f16;
911    ///
912    /// assert_eq!(x.maximum(y), y);
913    /// assert!(x.maximum(f16::NAN).is_nan());
914    /// # }
915    /// ```
916    #[inline]
917    #[unstable(feature = "f16", issue = "116909")]
918    // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
919    #[must_use = "this returns the result of the comparison, without modifying either input"]
920    pub const fn maximum(self, other: f16) -> f16 {
921        intrinsics::maximumf16(self, other)
922    }
923
924    /// Returns the minimum of the two numbers, propagating NaN.
925    ///
926    /// If at least one of the arguments is NaN, the return value is NaN, with the bit pattern
927    /// picked using the usual [rules for arithmetic operations](f32#nan-bit-patterns). Furthermore,
928    /// `-0.0` is considered to be less than `+0.0`, making this function fully deterministic for
929    /// non-NaN inputs.
930    ///
931    /// This is in contrast to [`f16::min`] which only returns NaN when *both* arguments are NaN,
932    /// and which does not reliably order `-0.0` and `+0.0`.
933    ///
934    /// This follows the IEEE 754-2019 semantics for `minimum`.
935    ///
936    /// ```
937    /// #![feature(f16)]
938    /// #![feature(float_minimum_maximum)]
939    /// # #[cfg(target_has_reliable_f16)] {
940    ///
941    /// let x = 1.0f16;
942    /// let y = 2.0f16;
943    ///
944    /// assert_eq!(x.minimum(y), x);
945    /// assert!(x.minimum(f16::NAN).is_nan());
946    /// # }
947    /// ```
948    #[inline]
949    #[unstable(feature = "f16", issue = "116909")]
950    // #[unstable(feature = "float_minimum_maximum", issue = "91079")]
951    #[must_use = "this returns the result of the comparison, without modifying either input"]
952    pub const fn minimum(self, other: f16) -> f16 {
953        intrinsics::minimumf16(self, other)
954    }
955
956    /// Calculates the midpoint (average) between `self` and `rhs`.
957    ///
958    /// This returns NaN when *either* argument is NaN or if a combination of
959    /// +inf and -inf is provided as arguments.
960    ///
961    /// # Examples
962    ///
963    /// ```
964    /// #![feature(f16)]
965    /// # #[cfg(target_has_reliable_f16)] {
966    ///
967    /// assert_eq!(1f16.midpoint(4.0), 2.5);
968    /// assert_eq!((-5.5f16).midpoint(8.0), 1.25);
969    /// # }
970    /// ```
971    #[inline]
972    #[doc(alias = "average")]
973    #[unstable(feature = "f16", issue = "116909")]
974    #[rustc_const_unstable(feature = "f16", issue = "116909")]
975    #[must_use = "this returns the result of the operation, \
976                  without modifying the original"]
977    pub const fn midpoint(self, other: f16) -> f16 {
978        const HI: f16 = f16::MAX * 0.5;
979
980        let (a, b) = (self, other);
981        let abs_a = a.abs();
982        let abs_b = b.abs();
983
984        if abs_a <= HI && abs_b <= HI {
985            // Overflow is impossible
986            (a + b) * 0.5
987        } else {
988            (a * 0.5) + (b * 0.5)
989        }
990    }
991
992    /// Rounds toward zero and converts to any primitive integer type,
993    /// assuming that the value is finite and fits in that type.
994    ///
995    /// ```
996    /// #![feature(f16)]
997    /// # #[cfg(target_has_reliable_f16)] {
998    ///
999    /// let value = 4.6_f16;
1000    /// let rounded = unsafe { value.to_int_unchecked::<u16>() };
1001    /// assert_eq!(rounded, 4);
1002    ///
1003    /// let value = -128.9_f16;
1004    /// let rounded = unsafe { value.to_int_unchecked::<i8>() };
1005    /// assert_eq!(rounded, i8::MIN);
1006    /// # }
1007    /// ```
1008    ///
1009    /// # Safety
1010    ///
1011    /// The value must:
1012    ///
1013    /// * Not be `NaN`
1014    /// * Not be infinite
1015    /// * Be representable in the return type `Int`, after truncating off its fractional part
1016    #[inline]
1017    #[unstable(feature = "f16", issue = "116909")]
1018    #[must_use = "this returns the result of the operation, without modifying the original"]
1019    pub unsafe fn to_int_unchecked<Int>(self) -> Int
1020    where
1021        Self: FloatToInt<Int>,
1022    {
1023        // SAFETY: the caller must uphold the safety contract for
1024        // `FloatToInt::to_int_unchecked`.
1025        unsafe { FloatToInt::<Int>::to_int_unchecked(self) }
1026    }
1027
1028    /// Raw transmutation to `u16`.
1029    ///
1030    /// This is currently identical to `transmute::<f16, u16>(self)` on all platforms.
1031    ///
1032    /// See [`from_bits`](#method.from_bits) for some discussion of the
1033    /// portability of this operation (there are almost no issues).
1034    ///
1035    /// Note that this function is distinct from `as` casting, which attempts to
1036    /// preserve the *numeric* value, and not the bitwise value.
1037    ///
1038    /// ```
1039    /// #![feature(f16)]
1040    /// # #[cfg(target_has_reliable_f16)] {
1041    ///
1042    /// assert_ne!((1f16).to_bits(), 1f16 as u16); // to_bits() is not casting!
1043    /// assert_eq!((12.5f16).to_bits(), 0x4a40);
1044    /// # }
1045    /// ```
1046    #[inline]
1047    #[unstable(feature = "f16", issue = "116909")]
1048    #[must_use = "this returns the result of the operation, without modifying the original"]
1049    #[allow(unnecessary_transmutes)]
1050    #[ferrocene::prevalidated]
1051    pub const fn to_bits(self) -> u16 {
1052        // SAFETY: `u16` is a plain old datatype so we can always transmute to it.
1053        unsafe { mem::transmute(self) }
1054    }
1055
1056    /// Raw transmutation from `u16`.
1057    ///
1058    /// This is currently identical to `transmute::<u16, f16>(v)` on all platforms.
1059    /// It turns out this is incredibly portable, for two reasons:
1060    ///
1061    /// * Floats and Ints have the same endianness on all supported platforms.
1062    /// * IEEE 754 very precisely specifies the bit layout of floats.
1063    ///
1064    /// However there is one caveat: prior to the 2008 version of IEEE 754, how
1065    /// to interpret the NaN signaling bit wasn't actually specified. Most platforms
1066    /// (notably x86 and ARM) picked the interpretation that was ultimately
1067    /// standardized in 2008, but some didn't (notably MIPS). As a result, all
1068    /// signaling NaNs on MIPS are quiet NaNs on x86, and vice-versa.
1069    ///
1070    /// Rather than trying to preserve signaling-ness cross-platform, this
1071    /// implementation favors preserving the exact bits. This means that
1072    /// any payloads encoded in NaNs will be preserved even if the result of
1073    /// this method is sent over the network from an x86 machine to a MIPS one.
1074    ///
1075    /// If the results of this method are only manipulated by the same
1076    /// architecture that produced them, then there is no portability concern.
1077    ///
1078    /// If the input isn't NaN, then there is no portability concern.
1079    ///
1080    /// If you don't care about signalingness (very likely), then there is no
1081    /// portability concern.
1082    ///
1083    /// Note that this function is distinct from `as` casting, which attempts to
1084    /// preserve the *numeric* value, and not the bitwise value.
1085    ///
1086    /// ```
1087    /// #![feature(f16)]
1088    /// # #[cfg(target_has_reliable_f16)] {
1089    ///
1090    /// let v = f16::from_bits(0x4a40);
1091    /// assert_eq!(v, 12.5);
1092    /// # }
1093    /// ```
1094    #[inline]
1095    #[must_use]
1096    #[unstable(feature = "f16", issue = "116909")]
1097    #[allow(unnecessary_transmutes)]
1098    #[ferrocene::prevalidated]
1099    pub const fn from_bits(v: u16) -> Self {
1100        // It turns out the safety issues with sNaN were overblown! Hooray!
1101        // SAFETY: `u16` is a plain old datatype so we can always transmute from it.
1102        unsafe { mem::transmute(v) }
1103    }
1104
1105    /// Returns the memory representation of this floating point number as a byte array in
1106    /// big-endian (network) byte order.
1107    ///
1108    /// See [`from_bits`](Self::from_bits) for some discussion of the
1109    /// portability of this operation (there are almost no issues).
1110    ///
1111    /// # Examples
1112    ///
1113    /// ```
1114    /// #![feature(f16)]
1115    /// # #[cfg(target_has_reliable_f16)] {
1116    ///
1117    /// let bytes = 12.5f16.to_be_bytes();
1118    /// assert_eq!(bytes, [0x4a, 0x40]);
1119    /// # }
1120    /// ```
1121    #[inline]
1122    #[unstable(feature = "f16", issue = "116909")]
1123    #[must_use = "this returns the result of the operation, without modifying the original"]
1124    pub const fn to_be_bytes(self) -> [u8; 2] {
1125        self.to_bits().to_be_bytes()
1126    }
1127
1128    /// Returns the memory representation of this floating point number as a byte array in
1129    /// little-endian byte order.
1130    ///
1131    /// See [`from_bits`](Self::from_bits) for some discussion of the
1132    /// portability of this operation (there are almost no issues).
1133    ///
1134    /// # Examples
1135    ///
1136    /// ```
1137    /// #![feature(f16)]
1138    /// # #[cfg(target_has_reliable_f16)] {
1139    ///
1140    /// let bytes = 12.5f16.to_le_bytes();
1141    /// assert_eq!(bytes, [0x40, 0x4a]);
1142    /// # }
1143    /// ```
1144    #[inline]
1145    #[unstable(feature = "f16", issue = "116909")]
1146    #[must_use = "this returns the result of the operation, without modifying the original"]
1147    pub const fn to_le_bytes(self) -> [u8; 2] {
1148        self.to_bits().to_le_bytes()
1149    }
1150
1151    /// Returns the memory representation of this floating point number as a byte array in
1152    /// native byte order.
1153    ///
1154    /// As the target platform's native endianness is used, portable code
1155    /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1156    ///
1157    /// [`to_be_bytes`]: f16::to_be_bytes
1158    /// [`to_le_bytes`]: f16::to_le_bytes
1159    ///
1160    /// See [`from_bits`](Self::from_bits) for some discussion of the
1161    /// portability of this operation (there are almost no issues).
1162    ///
1163    /// # Examples
1164    ///
1165    /// ```
1166    /// #![feature(f16)]
1167    /// # #[cfg(target_has_reliable_f16)] {
1168    ///
1169    /// let bytes = 12.5f16.to_ne_bytes();
1170    /// assert_eq!(
1171    ///     bytes,
1172    ///     if cfg!(target_endian = "big") {
1173    ///         [0x4a, 0x40]
1174    ///     } else {
1175    ///         [0x40, 0x4a]
1176    ///     }
1177    /// );
1178    /// # }
1179    /// ```
1180    #[inline]
1181    #[unstable(feature = "f16", issue = "116909")]
1182    #[must_use = "this returns the result of the operation, without modifying the original"]
1183    pub const fn to_ne_bytes(self) -> [u8; 2] {
1184        self.to_bits().to_ne_bytes()
1185    }
1186
1187    /// Creates a floating point value from its representation as a byte array in big endian.
1188    ///
1189    /// See [`from_bits`](Self::from_bits) for some discussion of the
1190    /// portability of this operation (there are almost no issues).
1191    ///
1192    /// # Examples
1193    ///
1194    /// ```
1195    /// #![feature(f16)]
1196    /// # #[cfg(target_has_reliable_f16)] {
1197    ///
1198    /// let value = f16::from_be_bytes([0x4a, 0x40]);
1199    /// assert_eq!(value, 12.5);
1200    /// # }
1201    /// ```
1202    #[inline]
1203    #[must_use]
1204    #[unstable(feature = "f16", issue = "116909")]
1205    pub const fn from_be_bytes(bytes: [u8; 2]) -> Self {
1206        Self::from_bits(u16::from_be_bytes(bytes))
1207    }
1208
1209    /// Creates a floating point value from its representation as a byte array in little endian.
1210    ///
1211    /// See [`from_bits`](Self::from_bits) for some discussion of the
1212    /// portability of this operation (there are almost no issues).
1213    ///
1214    /// # Examples
1215    ///
1216    /// ```
1217    /// #![feature(f16)]
1218    /// # #[cfg(target_has_reliable_f16)] {
1219    ///
1220    /// let value = f16::from_le_bytes([0x40, 0x4a]);
1221    /// assert_eq!(value, 12.5);
1222    /// # }
1223    /// ```
1224    #[inline]
1225    #[must_use]
1226    #[unstable(feature = "f16", issue = "116909")]
1227    pub const fn from_le_bytes(bytes: [u8; 2]) -> Self {
1228        Self::from_bits(u16::from_le_bytes(bytes))
1229    }
1230
1231    /// Creates a floating point value from its representation as a byte array in native endian.
1232    ///
1233    /// As the target platform's native endianness is used, portable code
1234    /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1235    /// appropriate instead.
1236    ///
1237    /// [`from_be_bytes`]: f16::from_be_bytes
1238    /// [`from_le_bytes`]: f16::from_le_bytes
1239    ///
1240    /// See [`from_bits`](Self::from_bits) for some discussion of the
1241    /// portability of this operation (there are almost no issues).
1242    ///
1243    /// # Examples
1244    ///
1245    /// ```
1246    /// #![feature(f16)]
1247    /// # #[cfg(target_has_reliable_f16)] {
1248    ///
1249    /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") {
1250    ///     [0x4a, 0x40]
1251    /// } else {
1252    ///     [0x40, 0x4a]
1253    /// });
1254    /// assert_eq!(value, 12.5);
1255    /// # }
1256    /// ```
1257    #[inline]
1258    #[must_use]
1259    #[unstable(feature = "f16", issue = "116909")]
1260    pub const fn from_ne_bytes(bytes: [u8; 2]) -> Self {
1261        Self::from_bits(u16::from_ne_bytes(bytes))
1262    }
1263
1264    /// Returns the ordering between `self` and `other`.
1265    ///
1266    /// Unlike the standard partial comparison between floating point numbers,
1267    /// this comparison always produces an ordering in accordance to
1268    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
1269    /// floating point standard. The values are ordered in the following sequence:
1270    ///
1271    /// - negative quiet NaN
1272    /// - negative signaling NaN
1273    /// - negative infinity
1274    /// - negative numbers
1275    /// - negative subnormal numbers
1276    /// - negative zero
1277    /// - positive zero
1278    /// - positive subnormal numbers
1279    /// - positive numbers
1280    /// - positive infinity
1281    /// - positive signaling NaN
1282    /// - positive quiet NaN.
1283    ///
1284    /// The ordering established by this function does not always agree with the
1285    /// [`PartialOrd`] and [`PartialEq`] implementations of `f16`. For example,
1286    /// they consider negative and positive zero equal, while `total_cmp`
1287    /// doesn't.
1288    ///
1289    /// The interpretation of the signaling NaN bit follows the definition in
1290    /// the IEEE 754 standard, which may not match the interpretation by some of
1291    /// the older, non-conformant (e.g. MIPS) hardware implementations.
1292    ///
1293    /// # Example
1294    ///
1295    /// ```
1296    /// #![feature(f16)]
1297    /// # #[cfg(target_has_reliable_f16)] {
1298    ///
1299    /// struct GoodBoy {
1300    ///     name: &'static str,
1301    ///     weight: f16,
1302    /// }
1303    ///
1304    /// let mut bois = vec![
1305    ///     GoodBoy { name: "Pucci", weight: 0.1 },
1306    ///     GoodBoy { name: "Woofer", weight: 99.0 },
1307    ///     GoodBoy { name: "Yapper", weight: 10.0 },
1308    ///     GoodBoy { name: "Chonk", weight: f16::INFINITY },
1309    ///     GoodBoy { name: "Abs. Unit", weight: f16::NAN },
1310    ///     GoodBoy { name: "Floaty", weight: -5.0 },
1311    /// ];
1312    ///
1313    /// bois.sort_by(|a, b| a.weight.total_cmp(&b.weight));
1314    ///
1315    /// // `f16::NAN` could be positive or negative, which will affect the sort order.
1316    /// if f16::NAN.is_sign_negative() {
1317    ///     bois.into_iter().map(|b| b.weight)
1318    ///         .zip([f16::NAN, -5.0, 0.1, 10.0, 99.0, f16::INFINITY].iter())
1319    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1320    /// } else {
1321    ///     bois.into_iter().map(|b| b.weight)
1322    ///         .zip([-5.0, 0.1, 10.0, 99.0, f16::INFINITY, f16::NAN].iter())
1323    ///         .for_each(|(a, b)| assert_eq!(a.to_bits(), b.to_bits()))
1324    /// }
1325    /// # }
1326    /// ```
1327    #[inline]
1328    #[must_use]
1329    #[unstable(feature = "f16", issue = "116909")]
1330    #[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
1331    pub const fn total_cmp(&self, other: &Self) -> crate::cmp::Ordering {
1332        let mut left = self.to_bits() as i16;
1333        let mut right = other.to_bits() as i16;
1334
1335        // In case of negatives, flip all the bits except the sign
1336        // to achieve a similar layout as two's complement integers
1337        //
1338        // Why does this work? IEEE 754 floats consist of three fields:
1339        // Sign bit, exponent and mantissa. The set of exponent and mantissa
1340        // fields as a whole have the property that their bitwise order is
1341        // equal to the numeric magnitude where the magnitude is defined.
1342        // The magnitude is not normally defined on NaN values, but
1343        // IEEE 754 totalOrder defines the NaN values also to follow the
1344        // bitwise order. This leads to order explained in the doc comment.
1345        // However, the representation of magnitude is the same for negative
1346        // and positive numbers – only the sign bit is different.
1347        // To easily compare the floats as signed integers, we need to
1348        // flip the exponent and mantissa bits in case of negative numbers.
1349        // We effectively convert the numbers to "two's complement" form.
1350        //
1351        // To do the flipping, we construct a mask and XOR against it.
1352        // We branchlessly calculate an "all-ones except for the sign bit"
1353        // mask from negative-signed values: right shifting sign-extends
1354        // the integer, so we "fill" the mask with sign bits, and then
1355        // convert to unsigned to push one more zero bit.
1356        // On positive values, the mask is all zeros, so it's a no-op.
1357        left ^= (((left >> 15) as u16) >> 1) as i16;
1358        right ^= (((right >> 15) as u16) >> 1) as i16;
1359
1360        left.cmp(&right)
1361    }
1362
1363    /// Restrict a value to a certain interval unless it is NaN.
1364    ///
1365    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
1366    /// less than `min`. Otherwise this returns `self`.
1367    ///
1368    /// Note that this function returns NaN if the initial value was NaN as
1369    /// well. If the result is zero and among the three inputs `self`, `min`, and `max` there are
1370    /// zeros with different sign, either `0.0` or `-0.0` is returned non-deterministically.
1371    ///
1372    /// # Panics
1373    ///
1374    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
1375    ///
1376    /// # Examples
1377    ///
1378    /// ```
1379    /// #![feature(f16)]
1380    /// # #[cfg(target_has_reliable_f16)] {
1381    ///
1382    /// assert!((-3.0f16).clamp(-2.0, 1.0) == -2.0);
1383    /// assert!((0.0f16).clamp(-2.0, 1.0) == 0.0);
1384    /// assert!((2.0f16).clamp(-2.0, 1.0) == 1.0);
1385    /// assert!((f16::NAN).clamp(-2.0, 1.0).is_nan());
1386    ///
1387    /// // These always returns zero, but the sign (which is ignored by `==`) is non-deterministic.
1388    /// assert!((0.0f16).clamp(-0.0, -0.0) == 0.0);
1389    /// assert!((1.0f16).clamp(-0.0, 0.0) == 0.0);
1390    /// // This is definitely a negative zero.
1391    /// assert!((-1.0f16).clamp(-0.0, 1.0).is_sign_negative());
1392    /// # }
1393    /// ```
1394    #[inline]
1395    #[unstable(feature = "f16", issue = "116909")]
1396    #[must_use = "method returns a new number and does not mutate the original value"]
1397    pub const fn clamp(mut self, min: f16, max: f16) -> f16 {
1398        const_assert!(
1399            min <= max,
1400            "min > max, or either was NaN",
1401            "min > max, or either was NaN. min = {min:?}, max = {max:?}",
1402            min: f16,
1403            max: f16,
1404        );
1405
1406        if self < min {
1407            self = min;
1408        }
1409        if self > max {
1410            self = max;
1411        }
1412        self
1413    }
1414
1415    /// Clamps this number to a symmetric range centered around zero.
1416    ///
1417    /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
1418    ///
1419    /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
1420    /// explicit about the intent.
1421    ///
1422    /// # Panics
1423    ///
1424    /// Panics if `limit` is negative or NaN, as this indicates a logic error.
1425    ///
1426    /// # Examples
1427    ///
1428    /// ```
1429    /// #![feature(f16)]
1430    /// #![feature(clamp_magnitude)]
1431    /// # #[cfg(target_has_reliable_f16)] {
1432    /// assert_eq!(5.0f16.clamp_magnitude(3.0), 3.0);
1433    /// assert_eq!((-5.0f16).clamp_magnitude(3.0), -3.0);
1434    /// assert_eq!(2.0f16.clamp_magnitude(3.0), 2.0);
1435    /// assert_eq!((-2.0f16).clamp_magnitude(3.0), -2.0);
1436    /// # }
1437    /// ```
1438    #[inline]
1439    #[unstable(feature = "clamp_magnitude", issue = "148519")]
1440    #[must_use = "this returns the clamped value and does not modify the original"]
1441    pub fn clamp_magnitude(self, limit: f16) -> f16 {
1442        assert!(limit >= 0.0, "limit must be non-negative");
1443        let limit = limit.abs(); // Canonicalises -0.0 to 0.0
1444        self.clamp(-limit, limit)
1445    }
1446
1447    /// Computes the absolute value of `self`.
1448    ///
1449    /// This function always returns the precise result.
1450    ///
1451    /// # Examples
1452    ///
1453    /// ```
1454    /// #![feature(f16)]
1455    /// # #[cfg(target_has_reliable_f16)] {
1456    ///
1457    /// let x = 3.5_f16;
1458    /// let y = -3.5_f16;
1459    ///
1460    /// assert_eq!(x.abs(), x);
1461    /// assert_eq!(y.abs(), -y);
1462    ///
1463    /// assert!(f16::NAN.abs().is_nan());
1464    /// # }
1465    /// ```
1466    #[inline]
1467    #[unstable(feature = "f16", issue = "116909")]
1468    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1469    #[must_use = "method returns a new number and does not mutate the original value"]
1470    #[ferrocene::prevalidated]
1471    pub const fn abs(self) -> Self {
1472        intrinsics::fabs(self)
1473    }
1474
1475    /// Returns a number that represents the sign of `self`.
1476    ///
1477    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
1478    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
1479    /// - NaN if the number is NaN
1480    ///
1481    /// # Examples
1482    ///
1483    /// ```
1484    /// #![feature(f16)]
1485    /// # #[cfg(target_has_reliable_f16)] {
1486    ///
1487    /// let f = 3.5_f16;
1488    ///
1489    /// assert_eq!(f.signum(), 1.0);
1490    /// assert_eq!(f16::NEG_INFINITY.signum(), -1.0);
1491    ///
1492    /// assert!(f16::NAN.signum().is_nan());
1493    /// # }
1494    /// ```
1495    #[inline]
1496    #[unstable(feature = "f16", issue = "116909")]
1497    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1498    #[must_use = "method returns a new number and does not mutate the original value"]
1499    pub const fn signum(self) -> f16 {
1500        if self.is_nan() { Self::NAN } else { 1.0_f16.copysign(self) }
1501    }
1502
1503    /// Returns a number composed of the magnitude of `self` and the sign of
1504    /// `sign`.
1505    ///
1506    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
1507    /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is
1508    /// returned.
1509    ///
1510    /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note
1511    /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust
1512    /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the
1513    /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable
1514    /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more
1515    /// info.
1516    ///
1517    /// # Examples
1518    ///
1519    /// ```
1520    /// #![feature(f16)]
1521    /// # #[cfg(target_has_reliable_f16)] {
1522    ///
1523    /// let f = 3.5_f16;
1524    ///
1525    /// assert_eq!(f.copysign(0.42), 3.5_f16);
1526    /// assert_eq!(f.copysign(-0.42), -3.5_f16);
1527    /// assert_eq!((-f).copysign(0.42), 3.5_f16);
1528    /// assert_eq!((-f).copysign(-0.42), -3.5_f16);
1529    ///
1530    /// assert!(f16::NAN.copysign(1.0).is_nan());
1531    /// # }
1532    /// ```
1533    #[inline]
1534    #[unstable(feature = "f16", issue = "116909")]
1535    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1536    #[must_use = "method returns a new number and does not mutate the original value"]
1537    pub const fn copysign(self, sign: f16) -> f16 {
1538        intrinsics::copysignf16(self, sign)
1539    }
1540
1541    /// Float addition that allows optimizations based on algebraic rules.
1542    ///
1543    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1544    #[must_use = "method returns a new number and does not mutate the original value"]
1545    #[unstable(feature = "float_algebraic", issue = "136469")]
1546    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1547    #[inline]
1548    pub const fn algebraic_add(self, rhs: f16) -> f16 {
1549        intrinsics::fadd_algebraic(self, rhs)
1550    }
1551
1552    /// Float subtraction that allows optimizations based on algebraic rules.
1553    ///
1554    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1555    #[must_use = "method returns a new number and does not mutate the original value"]
1556    #[unstable(feature = "float_algebraic", issue = "136469")]
1557    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1558    #[inline]
1559    pub const fn algebraic_sub(self, rhs: f16) -> f16 {
1560        intrinsics::fsub_algebraic(self, rhs)
1561    }
1562
1563    /// Float multiplication that allows optimizations based on algebraic rules.
1564    ///
1565    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1566    #[must_use = "method returns a new number and does not mutate the original value"]
1567    #[unstable(feature = "float_algebraic", issue = "136469")]
1568    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1569    #[inline]
1570    pub const fn algebraic_mul(self, rhs: f16) -> f16 {
1571        intrinsics::fmul_algebraic(self, rhs)
1572    }
1573
1574    /// Float division that allows optimizations based on algebraic rules.
1575    ///
1576    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1577    #[must_use = "method returns a new number and does not mutate the original value"]
1578    #[unstable(feature = "float_algebraic", issue = "136469")]
1579    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1580    #[inline]
1581    pub const fn algebraic_div(self, rhs: f16) -> f16 {
1582        intrinsics::fdiv_algebraic(self, rhs)
1583    }
1584
1585    /// Float remainder that allows optimizations based on algebraic rules.
1586    ///
1587    /// See [algebraic operators](primitive@f32#algebraic-operators) for more info.
1588    #[must_use = "method returns a new number and does not mutate the original value"]
1589    #[unstable(feature = "float_algebraic", issue = "136469")]
1590    #[rustc_const_unstable(feature = "float_algebraic", issue = "136469")]
1591    #[inline]
1592    pub const fn algebraic_rem(self, rhs: f16) -> f16 {
1593        intrinsics::frem_algebraic(self, rhs)
1594    }
1595}
1596
1597// Functions in this module fall into `core_float_math`
1598// #[unstable(feature = "core_float_math", issue = "137578")]
1599#[cfg(not(test))]
1600#[doc(test(attr(
1601    feature(cfg_target_has_reliable_f16_f128),
1602    expect(internal_features),
1603    allow(unused_features)
1604)))]
1605impl f16 {
1606    /// Returns the largest integer less than or equal to `self`.
1607    ///
1608    /// This function always returns the precise result.
1609    ///
1610    /// # Examples
1611    ///
1612    /// ```
1613    /// #![feature(f16)]
1614    /// # #[cfg(target_has_reliable_f16)] {
1615    ///
1616    /// let f = 3.7_f16;
1617    /// let g = 3.0_f16;
1618    /// let h = -3.7_f16;
1619    ///
1620    /// assert_eq!(f.floor(), 3.0);
1621    /// assert_eq!(g.floor(), 3.0);
1622    /// assert_eq!(h.floor(), -4.0);
1623    /// # }
1624    /// ```
1625    #[inline]
1626    #[rustc_allow_incoherent_impl]
1627    #[unstable(feature = "f16", issue = "116909")]
1628    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1629    #[must_use = "method returns a new number and does not mutate the original value"]
1630    pub const fn floor(self) -> f16 {
1631        intrinsics::floorf16(self)
1632    }
1633
1634    /// Returns the smallest integer greater than or equal to `self`.
1635    ///
1636    /// This function always returns the precise result.
1637    ///
1638    /// # Examples
1639    ///
1640    /// ```
1641    /// #![feature(f16)]
1642    /// # #[cfg(target_has_reliable_f16)] {
1643    ///
1644    /// let f = 3.01_f16;
1645    /// let g = 4.0_f16;
1646    ///
1647    /// assert_eq!(f.ceil(), 4.0);
1648    /// assert_eq!(g.ceil(), 4.0);
1649    /// # }
1650    /// ```
1651    #[inline]
1652    #[doc(alias = "ceiling")]
1653    #[rustc_allow_incoherent_impl]
1654    #[unstable(feature = "f16", issue = "116909")]
1655    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1656    #[must_use = "method returns a new number and does not mutate the original value"]
1657    pub const fn ceil(self) -> f16 {
1658        intrinsics::ceilf16(self)
1659    }
1660
1661    /// Returns the nearest integer to `self`. If a value is half-way between two
1662    /// integers, round away from `0.0`.
1663    ///
1664    /// This function always returns the precise result.
1665    ///
1666    /// # Examples
1667    ///
1668    /// ```
1669    /// #![feature(f16)]
1670    /// # #[cfg(target_has_reliable_f16)] {
1671    ///
1672    /// let f = 3.3_f16;
1673    /// let g = -3.3_f16;
1674    /// let h = -3.7_f16;
1675    /// let i = 3.5_f16;
1676    /// let j = 4.5_f16;
1677    ///
1678    /// assert_eq!(f.round(), 3.0);
1679    /// assert_eq!(g.round(), -3.0);
1680    /// assert_eq!(h.round(), -4.0);
1681    /// assert_eq!(i.round(), 4.0);
1682    /// assert_eq!(j.round(), 5.0);
1683    /// # }
1684    /// ```
1685    #[inline]
1686    #[rustc_allow_incoherent_impl]
1687    #[unstable(feature = "f16", issue = "116909")]
1688    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1689    #[must_use = "method returns a new number and does not mutate the original value"]
1690    pub const fn round(self) -> f16 {
1691        intrinsics::roundf16(self)
1692    }
1693
1694    /// Returns the nearest integer to a number. Rounds half-way cases to the number
1695    /// with an even least significant digit.
1696    ///
1697    /// This function always returns the precise result.
1698    ///
1699    /// # Examples
1700    ///
1701    /// ```
1702    /// #![feature(f16)]
1703    /// # #[cfg(target_has_reliable_f16)] {
1704    ///
1705    /// let f = 3.3_f16;
1706    /// let g = -3.3_f16;
1707    /// let h = 3.5_f16;
1708    /// let i = 4.5_f16;
1709    ///
1710    /// assert_eq!(f.round_ties_even(), 3.0);
1711    /// assert_eq!(g.round_ties_even(), -3.0);
1712    /// assert_eq!(h.round_ties_even(), 4.0);
1713    /// assert_eq!(i.round_ties_even(), 4.0);
1714    /// # }
1715    /// ```
1716    #[inline]
1717    #[rustc_allow_incoherent_impl]
1718    #[unstable(feature = "f16", issue = "116909")]
1719    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1720    #[must_use = "method returns a new number and does not mutate the original value"]
1721    pub const fn round_ties_even(self) -> f16 {
1722        intrinsics::round_ties_even_f16(self)
1723    }
1724
1725    /// Returns the integer part of `self`.
1726    /// This means that non-integer numbers are always truncated towards zero.
1727    ///
1728    /// This function always returns the precise result.
1729    ///
1730    /// # Examples
1731    ///
1732    /// ```
1733    /// #![feature(f16)]
1734    /// # #[cfg(target_has_reliable_f16)] {
1735    ///
1736    /// let f = 3.7_f16;
1737    /// let g = 3.0_f16;
1738    /// let h = -3.7_f16;
1739    ///
1740    /// assert_eq!(f.trunc(), 3.0);
1741    /// assert_eq!(g.trunc(), 3.0);
1742    /// assert_eq!(h.trunc(), -3.0);
1743    /// # }
1744    /// ```
1745    #[inline]
1746    #[doc(alias = "truncate")]
1747    #[rustc_allow_incoherent_impl]
1748    #[unstable(feature = "f16", issue = "116909")]
1749    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1750    #[must_use = "method returns a new number and does not mutate the original value"]
1751    pub const fn trunc(self) -> f16 {
1752        intrinsics::truncf16(self)
1753    }
1754
1755    /// Returns the fractional part of `self`.
1756    ///
1757    /// This function always returns the precise result.
1758    ///
1759    /// # Examples
1760    ///
1761    /// ```
1762    /// #![feature(f16)]
1763    /// # #[cfg(target_has_reliable_f16)] {
1764    ///
1765    /// let x = 3.6_f16;
1766    /// let y = -3.6_f16;
1767    /// let abs_difference_x = (x.fract() - 0.6).abs();
1768    /// let abs_difference_y = (y.fract() - (-0.6)).abs();
1769    ///
1770    /// assert!(abs_difference_x <= f16::EPSILON);
1771    /// assert!(abs_difference_y <= f16::EPSILON);
1772    /// # }
1773    /// ```
1774    #[inline]
1775    #[rustc_allow_incoherent_impl]
1776    #[unstable(feature = "f16", issue = "116909")]
1777    #[rustc_const_unstable(feature = "f16", issue = "116909")]
1778    #[must_use = "method returns a new number and does not mutate the original value"]
1779    pub const fn fract(self) -> f16 {
1780        self - self.trunc()
1781    }
1782
1783    /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1784    /// error, yielding a more accurate result than an unfused multiply-add.
1785    ///
1786    /// Using `mul_add` *may* be more performant than an unfused multiply-add if
1787    /// the target architecture has a dedicated `fma` CPU instruction. However,
1788    /// this is not always true, and will be heavily dependant on designing
1789    /// algorithms with specific target hardware in mind.
1790    ///
1791    /// # Precision
1792    ///
1793    /// The result of this operation is guaranteed to be the rounded
1794    /// infinite-precision result. It is specified by IEEE 754 as
1795    /// `fusedMultiplyAdd` and guaranteed not to change.
1796    ///
1797    /// # Examples
1798    ///
1799    /// ```
1800    /// #![feature(f16)]
1801    /// # #[cfg(target_has_reliable_f16)] {
1802    ///
1803    /// let m = 10.0_f16;
1804    /// let x = 4.0_f16;
1805    /// let b = 60.0_f16;
1806    ///
1807    /// assert_eq!(m.mul_add(x, b), 100.0);
1808    /// assert_eq!(m * x + b, 100.0);
1809    ///
1810    /// let one_plus_eps = 1.0_f16 + f16::EPSILON;
1811    /// let one_minus_eps = 1.0_f16 - f16::EPSILON;
1812    /// let minus_one = -1.0_f16;
1813    ///
1814    /// // The exact result (1 + eps) * (1 - eps) = 1 - eps * eps.
1815    /// assert_eq!(one_plus_eps.mul_add(one_minus_eps, minus_one), -f16::EPSILON * f16::EPSILON);
1816    /// // Different rounding with the non-fused multiply and add.
1817    /// assert_eq!(one_plus_eps * one_minus_eps + minus_one, 0.0);
1818    /// # }
1819    /// ```
1820    #[inline]
1821    #[rustc_allow_incoherent_impl]
1822    #[unstable(feature = "f16", issue = "116909")]
1823    #[doc(alias = "fmaf16", alias = "fusedMultiplyAdd")]
1824    #[must_use = "method returns a new number and does not mutate the original value"]
1825    pub const fn mul_add(self, a: f16, b: f16) -> f16 {
1826        intrinsics::fmaf16(self, a, b)
1827    }
1828
1829    /// Calculates Euclidean division, the matching method for `rem_euclid`.
1830    ///
1831    /// This computes the integer `n` such that
1832    /// `self = n * rhs + self.rem_euclid(rhs)`.
1833    /// In other words, the result is `self / rhs` rounded to the integer `n`
1834    /// such that `self >= n * rhs`.
1835    ///
1836    /// # Precision
1837    ///
1838    /// The result of this operation is guaranteed to be the rounded
1839    /// infinite-precision result.
1840    ///
1841    /// # Examples
1842    ///
1843    /// ```
1844    /// #![feature(f16)]
1845    /// # #[cfg(target_has_reliable_f16)] {
1846    ///
1847    /// let a: f16 = 7.0;
1848    /// let b = 4.0;
1849    /// assert_eq!(a.div_euclid(b), 1.0); // 7.0 > 4.0 * 1.0
1850    /// assert_eq!((-a).div_euclid(b), -2.0); // -7.0 >= 4.0 * -2.0
1851    /// assert_eq!(a.div_euclid(-b), -1.0); // 7.0 >= -4.0 * -1.0
1852    /// assert_eq!((-a).div_euclid(-b), 2.0); // -7.0 >= -4.0 * 2.0
1853    /// # }
1854    /// ```
1855    #[inline]
1856    #[rustc_allow_incoherent_impl]
1857    #[unstable(feature = "f16", issue = "116909")]
1858    #[must_use = "method returns a new number and does not mutate the original value"]
1859    pub fn div_euclid(self, rhs: f16) -> f16 {
1860        let q = (self / rhs).trunc();
1861        if self % rhs < 0.0 {
1862            return if rhs > 0.0 { q - 1.0 } else { q + 1.0 };
1863        }
1864        q
1865    }
1866
1867    /// Calculates the least nonnegative remainder of `self` when
1868    /// divided by `rhs`.
1869    ///
1870    /// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in
1871    /// most cases. However, due to a floating point round-off error it can
1872    /// result in `r == rhs.abs()`, violating the mathematical definition, if
1873    /// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`.
1874    /// This result is not an element of the function's codomain, but it is the
1875    /// closest floating point number in the real numbers and thus fulfills the
1876    /// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)`
1877    /// approximately.
1878    ///
1879    /// # Precision
1880    ///
1881    /// The result of this operation is guaranteed to be the rounded
1882    /// infinite-precision result.
1883    ///
1884    /// # Examples
1885    ///
1886    /// ```
1887    /// #![feature(f16)]
1888    /// # #[cfg(target_has_reliable_f16)] {
1889    ///
1890    /// let a: f16 = 7.0;
1891    /// let b = 4.0;
1892    /// assert_eq!(a.rem_euclid(b), 3.0);
1893    /// assert_eq!((-a).rem_euclid(b), 1.0);
1894    /// assert_eq!(a.rem_euclid(-b), 3.0);
1895    /// assert_eq!((-a).rem_euclid(-b), 1.0);
1896    /// // limitation due to round-off error
1897    /// assert!((-f16::EPSILON).rem_euclid(3.0) != 0.0);
1898    /// # }
1899    /// ```
1900    #[inline]
1901    #[rustc_allow_incoherent_impl]
1902    #[doc(alias = "modulo", alias = "mod")]
1903    #[unstable(feature = "f16", issue = "116909")]
1904    #[must_use = "method returns a new number and does not mutate the original value"]
1905    pub fn rem_euclid(self, rhs: f16) -> f16 {
1906        let r = self % rhs;
1907        if r < 0.0 { r + rhs.abs() } else { r }
1908    }
1909
1910    /// Raises a number to an integer power.
1911    ///
1912    /// Using this function is generally faster than using `powf`.
1913    /// It might have a different sequence of rounding operations than `powf`,
1914    /// so the results are not guaranteed to agree.
1915    ///
1916    /// Note that this function is special in that it can return non-NaN results for NaN inputs. For
1917    /// example, `f16::powi(f16::NAN, 0)` returns `1.0`. However, if an input is a *signaling*
1918    /// NaN, then the result is non-deterministically either a NaN or the result that the
1919    /// corresponding quiet NaN would produce.
1920    ///
1921    /// # Unspecified precision
1922    ///
1923    /// The precision of this function is non-deterministic. This means it varies by platform,
1924    /// Rust version, and can even differ within the same execution from one invocation to the next.
1925    ///
1926    /// # Examples
1927    ///
1928    /// ```
1929    /// #![feature(f16)]
1930    /// # #[cfg(target_has_reliable_f16_math)] {
1931    ///
1932    /// let x = 2.0_f16;
1933    /// let abs_difference = (x.powi(2) - (x * x)).abs();
1934    /// assert!(abs_difference <= 0.1);
1935    ///
1936    /// assert_eq!(f16::powi(f16::NAN, 0), 1.0);
1937    /// assert_eq!(f16::powi(0.0, 0), 1.0);
1938    /// # }
1939    /// ```
1940    #[inline]
1941    #[rustc_allow_incoherent_impl]
1942    #[unstable(feature = "f16", issue = "116909")]
1943    #[must_use = "method returns a new number and does not mutate the original value"]
1944    pub fn powi(self, n: i32) -> f16 {
1945        intrinsics::powif16(self, n)
1946    }
1947
1948    /// Returns the square root of a number.
1949    ///
1950    /// Returns NaN if `self` is a negative number other than `-0.0`.
1951    ///
1952    /// # Precision
1953    ///
1954    /// The result of this operation is guaranteed to be the rounded
1955    /// infinite-precision result. It is specified by IEEE 754 as `squareRoot`
1956    /// and guaranteed not to change.
1957    ///
1958    /// # Examples
1959    ///
1960    /// ```
1961    /// #![feature(f16)]
1962    /// # #[cfg(target_has_reliable_f16)] {
1963    ///
1964    /// let positive = 4.0_f16;
1965    /// let negative = -4.0_f16;
1966    /// let negative_zero = -0.0_f16;
1967    ///
1968    /// assert_eq!(positive.sqrt(), 2.0);
1969    /// assert!(negative.sqrt().is_nan());
1970    /// assert!(negative_zero.sqrt() == negative_zero);
1971    /// # }
1972    /// ```
1973    #[inline]
1974    #[doc(alias = "squareRoot")]
1975    #[rustc_allow_incoherent_impl]
1976    #[unstable(feature = "f16", issue = "116909")]
1977    #[must_use = "method returns a new number and does not mutate the original value"]
1978    pub fn sqrt(self) -> f16 {
1979        intrinsics::sqrtf16(self)
1980    }
1981
1982    /// Returns the cube root of a number.
1983    ///
1984    /// # Unspecified precision
1985    ///
1986    /// The precision of this function is non-deterministic. This means it varies by platform,
1987    /// Rust version, and can even differ within the same execution from one invocation to the next.
1988    ///
1989    /// This function currently corresponds to the `cbrtf` from libc on Unix
1990    /// and Windows. Note that this might change in the future.
1991    ///
1992    /// # Examples
1993    ///
1994    /// ```
1995    /// #![feature(f16)]
1996    /// # #[cfg(target_has_reliable_f16)] {
1997    ///
1998    /// let x = 8.0f16;
1999    ///
2000    /// // x^(1/3) - 2 == 0
2001    /// let abs_difference = (x.cbrt() - 2.0).abs();
2002    ///
2003    /// assert!(abs_difference <= f16::EPSILON);
2004    /// # }
2005    /// ```
2006    #[inline]
2007    #[rustc_allow_incoherent_impl]
2008    #[unstable(feature = "f16", issue = "116909")]
2009    #[must_use = "method returns a new number and does not mutate the original value"]
2010    pub fn cbrt(self) -> f16 {
2011        libm::cbrtf(self as f32) as f16
2012    }
2013}