half_2/
binary16.rs

1#[cfg(all(feature = "serde", feature = "alloc"))]
2#[allow(unused_imports)]
3use alloc::string::ToString;
4#[cfg(feature = "bytemuck")]
5use bytemuck::{Pod, Zeroable};
6use core::{
7    cmp::Ordering,
8    iter::{Product, Sum},
9    num::FpCategory,
10    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign},
11};
12#[cfg(not(target_arch = "spirv"))]
13use core::{
14    fmt::{
15        Binary, Debug, Display, Error, Formatter, LowerExp, LowerHex, Octal, UpperExp, UpperHex,
16    },
17    num::ParseFloatError,
18    str::FromStr,
19};
20#[cfg(feature = "serde")]
21use serde::{Deserialize, Serialize};
22#[cfg(feature = "zerocopy")]
23use zerocopy::{AsBytes, FromBytes};
24
25pub(crate) mod arch;
26
27/// A 16-bit floating point type implementing the IEEE 754-2008 standard [`binary16`] a.k.a "half"
28/// format.
29///
30/// This 16-bit floating point type is intended for efficient storage where the full range and
31/// precision of a larger floating point value is not required.
32///
33/// [`binary16`]: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
34#[allow(non_camel_case_types)]
35#[derive(Clone, Copy, Default)]
36#[repr(transparent)]
37#[cfg_attr(feature = "serde", derive(Serialize))]
38#[cfg_attr(
39    feature = "rkyv",
40    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
41)]
42#[cfg_attr(feature = "rkyv", archive(resolver = "F16Resolver"))]
43#[cfg_attr(feature = "bytemuck", derive(Zeroable, Pod))]
44#[cfg_attr(feature = "zerocopy", derive(AsBytes, FromBytes))]
45#[cfg_attr(kani, derive(kani::Arbitrary))]
46#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
47pub struct f16(u16);
48
49impl f16 {
50    /// Constructs a 16-bit floating point value from the raw bits.
51    #[inline]
52    #[must_use]
53    pub const fn from_bits(bits: u16) -> f16 {
54        f16(bits)
55    }
56
57    /// Constructs a 16-bit floating point value from a 32-bit floating point value.
58    ///
59    /// This operation is lossy. If the 32-bit value is to large to fit in 16-bits, ±∞ will result.
60    /// NaN values are preserved. 32-bit subnormal values are too tiny to be represented in 16-bits
61    /// and result in ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit
62    /// subnormals or ±0. All other values are truncated and rounded to the nearest representable
63    /// 16-bit value.
64    #[inline]
65    #[must_use]
66    pub fn from_f32(value: f32) -> f16 {
67        f16(arch::f32_to_f16(value))
68    }
69
70    /// Constructs a 16-bit floating point value from a 32-bit floating point value.
71    ///
72    /// This function is identical to [`from_f32`][Self::from_f32] except it never uses hardware
73    /// intrinsics, which allows it to be `const`. [`from_f32`][Self::from_f32] should be preferred
74    /// in any non-`const` context.
75    ///
76    /// This operation is lossy. If the 32-bit value is to large to fit in 16-bits, ±∞ will result.
77    /// NaN values are preserved. 32-bit subnormal values are too tiny to be represented in 16-bits
78    /// and result in ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit
79    /// subnormals or ±0. All other values are truncated and rounded to the nearest representable
80    /// 16-bit value.
81    #[inline]
82    #[must_use]
83    pub const fn from_f32_const(value: f32) -> f16 {
84        f16(arch::f32_to_f16_fallback(value))
85    }
86
87    /// Constructs a 16-bit floating point value from a 64-bit floating point value.
88    ///
89    /// This operation is lossy. If the 64-bit value is to large to fit in 16-bits, ±∞ will result.
90    /// NaN values are preserved. 64-bit subnormal values are too tiny to be represented in 16-bits
91    /// and result in ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit
92    /// subnormals or ±0. All other values are truncated and rounded to the nearest representable
93    /// 16-bit value.
94    #[inline]
95    #[must_use]
96    pub fn from_f64(value: f64) -> f16 {
97        f16(arch::f64_to_f16(value))
98    }
99
100    /// Constructs a 16-bit floating point value from a 64-bit floating point value.
101    ///
102    /// This function is identical to [`from_f64`][Self::from_f64] except it never uses hardware
103    /// intrinsics, which allows it to be `const`. [`from_f64`][Self::from_f64] should be preferred
104    /// in any non-`const` context.
105    ///
106    /// This operation is lossy. If the 64-bit value is to large to fit in 16-bits, ±∞ will result.
107    /// NaN values are preserved. 64-bit subnormal values are too tiny to be represented in 16-bits
108    /// and result in ±0. Exponents that underflow the minimum 16-bit exponent will result in 16-bit
109    /// subnormals or ±0. All other values are truncated and rounded to the nearest representable
110    /// 16-bit value.
111    #[inline]
112    #[must_use]
113    pub const fn from_f64_const(value: f64) -> f16 {
114        f16(arch::f64_to_f16_fallback(value))
115    }
116
117    /// Converts a [`f16`] into the underlying bit representation.
118    #[inline]
119    #[must_use]
120    pub const fn to_bits(self) -> u16 {
121        self.0
122    }
123
124    /// Returns the memory representation of the underlying bit representation as a byte array in
125    /// little-endian byte order.
126    ///
127    /// # Examples
128    ///
129    /// ```rust
130    /// # use half::prelude::*;
131    /// let bytes = f16::from_f32(12.5).to_le_bytes();
132    /// assert_eq!(bytes, [0x40, 0x4A]);
133    /// ```
134    #[inline]
135    #[must_use]
136    pub const fn to_le_bytes(self) -> [u8; 2] {
137        self.0.to_le_bytes()
138    }
139
140    /// Returns the memory representation of the underlying bit representation as a byte array in
141    /// big-endian (network) byte order.
142    ///
143    /// # Examples
144    ///
145    /// ```rust
146    /// # use half::prelude::*;
147    /// let bytes = f16::from_f32(12.5).to_be_bytes();
148    /// assert_eq!(bytes, [0x4A, 0x40]);
149    /// ```
150    #[inline]
151    #[must_use]
152    pub const fn to_be_bytes(self) -> [u8; 2] {
153        self.0.to_be_bytes()
154    }
155
156    /// Returns the memory representation of the underlying bit representation as a byte array in
157    /// native byte order.
158    ///
159    /// As the target platform's native endianness is used, portable code should use
160    /// [`to_be_bytes`][Self::to_be_bytes] or [`to_le_bytes`][Self::to_le_bytes], as appropriate,
161    /// instead.
162    ///
163    /// # Examples
164    ///
165    /// ```rust
166    /// # use half::prelude::*;
167    /// let bytes = f16::from_f32(12.5).to_ne_bytes();
168    /// assert_eq!(bytes, if cfg!(target_endian = "big") {
169    ///     [0x4A, 0x40]
170    /// } else {
171    ///     [0x40, 0x4A]
172    /// });
173    /// ```
174    #[inline]
175    #[must_use]
176    pub const fn to_ne_bytes(self) -> [u8; 2] {
177        self.0.to_ne_bytes()
178    }
179
180    /// Creates a floating point value from its representation as a byte array in little endian.
181    ///
182    /// # Examples
183    ///
184    /// ```rust
185    /// # use half::prelude::*;
186    /// let value = f16::from_le_bytes([0x40, 0x4A]);
187    /// assert_eq!(value, f16::from_f32(12.5));
188    /// ```
189    #[inline]
190    #[must_use]
191    pub const fn from_le_bytes(bytes: [u8; 2]) -> f16 {
192        f16::from_bits(u16::from_le_bytes(bytes))
193    }
194
195    /// Creates a floating point value from its representation as a byte array in big endian.
196    ///
197    /// # Examples
198    ///
199    /// ```rust
200    /// # use half::prelude::*;
201    /// let value = f16::from_be_bytes([0x4A, 0x40]);
202    /// assert_eq!(value, f16::from_f32(12.5));
203    /// ```
204    #[inline]
205    #[must_use]
206    pub const fn from_be_bytes(bytes: [u8; 2]) -> f16 {
207        f16::from_bits(u16::from_be_bytes(bytes))
208    }
209
210    /// Creates a floating point value from its representation as a byte array in native endian.
211    ///
212    /// As the target platform's native endianness is used, portable code likely wants to use
213    /// [`from_be_bytes`][Self::from_be_bytes] or [`from_le_bytes`][Self::from_le_bytes], as
214    /// appropriate instead.
215    ///
216    /// # Examples
217    ///
218    /// ```rust
219    /// # use half::prelude::*;
220    /// let value = f16::from_ne_bytes(if cfg!(target_endian = "big") {
221    ///     [0x4A, 0x40]
222    /// } else {
223    ///     [0x40, 0x4A]
224    /// });
225    /// assert_eq!(value, f16::from_f32(12.5));
226    /// ```
227    #[inline]
228    #[must_use]
229    pub const fn from_ne_bytes(bytes: [u8; 2]) -> f16 {
230        f16::from_bits(u16::from_ne_bytes(bytes))
231    }
232
233    /// Converts a [`f16`] value into a `f32` value.
234    ///
235    /// This conversion is lossless as all 16-bit floating point values can be represented exactly
236    /// in 32-bit floating point.
237    #[inline]
238    #[must_use]
239    pub fn to_f32(self) -> f32 {
240        arch::f16_to_f32(self.0)
241    }
242
243    /// Converts a [`f16`] value into a `f32` value.
244    ///
245    /// This function is identical to [`to_f32`][Self::to_f32] except it never uses hardware
246    /// intrinsics, which allows it to be `const`. [`to_f32`][Self::to_f32] should be preferred
247    /// in any non-`const` context.
248    ///
249    /// This conversion is lossless as all 16-bit floating point values can be represented exactly
250    /// in 32-bit floating point.
251    #[inline]
252    #[must_use]
253    pub const fn to_f32_const(self) -> f32 {
254        arch::f16_to_f32_fallback(self.0)
255    }
256
257    /// Converts a [`f16`] value into a `f64` value.
258    ///
259    /// This conversion is lossless as all 16-bit floating point values can be represented exactly
260    /// in 64-bit floating point.
261    #[inline]
262    #[must_use]
263    pub fn to_f64(self) -> f64 {
264        arch::f16_to_f64(self.0)
265    }
266
267    /// Converts a [`f16`] value into a `f64` value.
268    ///
269    /// This function is identical to [`to_f64`][Self::to_f64] except it never uses hardware
270    /// intrinsics, which allows it to be `const`. [`to_f64`][Self::to_f64] should be preferred
271    /// in any non-`const` context.
272    ///
273    /// This conversion is lossless as all 16-bit floating point values can be represented exactly
274    /// in 64-bit floating point.
275    #[inline]
276    #[must_use]
277    pub const fn to_f64_const(self) -> f64 {
278        arch::f16_to_f64_fallback(self.0)
279    }
280
281    /// Returns `true` if this value is `NaN` and `false` otherwise.
282    ///
283    /// # Examples
284    ///
285    /// ```rust
286    /// # use half::prelude::*;
287    ///
288    /// let nan = f16::NAN;
289    /// let f = f16::from_f32(7.0_f32);
290    ///
291    /// assert!(nan.is_nan());
292    /// assert!(!f.is_nan());
293    /// ```
294    #[inline]
295    #[must_use]
296    pub const fn is_nan(self) -> bool {
297        self.0 & 0x7FFFu16 > 0x7C00u16
298    }
299
300    /// Returns `true` if this value is ±∞ and `false`.
301    /// otherwise.
302    ///
303    /// # Examples
304    ///
305    /// ```rust
306    /// # use half::prelude::*;
307    ///
308    /// let f = f16::from_f32(7.0f32);
309    /// let inf = f16::INFINITY;
310    /// let neg_inf = f16::NEG_INFINITY;
311    /// let nan = f16::NAN;
312    ///
313    /// assert!(!f.is_infinite());
314    /// assert!(!nan.is_infinite());
315    ///
316    /// assert!(inf.is_infinite());
317    /// assert!(neg_inf.is_infinite());
318    /// ```
319    #[inline]
320    #[must_use]
321    pub const fn is_infinite(self) -> bool {
322        self.0 & 0x7FFFu16 == 0x7C00u16
323    }
324
325    /// Returns `true` if this number is neither infinite nor `NaN`.
326    ///
327    /// # Examples
328    ///
329    /// ```rust
330    /// # use half::prelude::*;
331    ///
332    /// let f = f16::from_f32(7.0f32);
333    /// let inf = f16::INFINITY;
334    /// let neg_inf = f16::NEG_INFINITY;
335    /// let nan = f16::NAN;
336    ///
337    /// assert!(f.is_finite());
338    ///
339    /// assert!(!nan.is_finite());
340    /// assert!(!inf.is_finite());
341    /// assert!(!neg_inf.is_finite());
342    /// ```
343    #[inline]
344    #[must_use]
345    pub const fn is_finite(self) -> bool {
346        self.0 & 0x7C00u16 != 0x7C00u16
347    }
348
349    /// Returns `true` if the number is neither zero, infinite, subnormal, or `NaN`.
350    ///
351    /// # Examples
352    ///
353    /// ```rust
354    /// # use half::prelude::*;
355    ///
356    /// let min = f16::MIN_POSITIVE;
357    /// let max = f16::MAX;
358    /// let lower_than_min = f16::from_f32(1.0e-10_f32);
359    /// let zero = f16::from_f32(0.0_f32);
360    ///
361    /// assert!(min.is_normal());
362    /// assert!(max.is_normal());
363    ///
364    /// assert!(!zero.is_normal());
365    /// assert!(!f16::NAN.is_normal());
366    /// assert!(!f16::INFINITY.is_normal());
367    /// // Values between `0` and `min` are Subnormal.
368    /// assert!(!lower_than_min.is_normal());
369    /// ```
370    #[inline]
371    #[must_use]
372    pub const fn is_normal(self) -> bool {
373        let exp = self.0 & 0x7C00u16;
374        exp != 0x7C00u16 && exp != 0
375    }
376
377    /// Returns the floating point category of the number.
378    ///
379    /// If only one property is going to be tested, it is generally faster to use the specific
380    /// predicate instead.
381    ///
382    /// # Examples
383    ///
384    /// ```rust
385    /// use std::num::FpCategory;
386    /// # use half::prelude::*;
387    ///
388    /// let num = f16::from_f32(12.4_f32);
389    /// let inf = f16::INFINITY;
390    ///
391    /// assert_eq!(num.classify(), FpCategory::Normal);
392    /// assert_eq!(inf.classify(), FpCategory::Infinite);
393    /// ```
394    #[must_use]
395    pub const fn classify(self) -> FpCategory {
396        let exp = self.0 & 0x7C00u16;
397        let man = self.0 & 0x03FFu16;
398        match (exp, man) {
399            (0, 0) => FpCategory::Zero,
400            (0, _) => FpCategory::Subnormal,
401            (0x7C00u16, 0) => FpCategory::Infinite,
402            (0x7C00u16, _) => FpCategory::Nan,
403            _ => FpCategory::Normal,
404        }
405    }
406
407    /// Returns a number that represents the sign of `self`.
408    ///
409    /// * `1.0` if the number is positive, `+0.0` or [`INFINITY`][f16::INFINITY]
410    /// * `-1.0` if the number is negative, `-0.0` or [`NEG_INFINITY`][f16::NEG_INFINITY]
411    /// * [`NAN`][f16::NAN] if the number is `NaN`
412    ///
413    /// # Examples
414    ///
415    /// ```rust
416    /// # use half::prelude::*;
417    ///
418    /// let f = f16::from_f32(3.5_f32);
419    ///
420    /// assert_eq!(f.signum(), f16::from_f32(1.0));
421    /// assert_eq!(f16::NEG_INFINITY.signum(), f16::from_f32(-1.0));
422    ///
423    /// assert!(f16::NAN.signum().is_nan());
424    /// ```
425    #[must_use]
426    pub const fn signum(self) -> f16 {
427        if self.is_nan() {
428            self
429        } else if self.0 & 0x8000u16 != 0 {
430            Self::NEG_ONE
431        } else {
432            Self::ONE
433        }
434    }
435
436    /// Returns `true` if and only if `self` has a positive sign, including `+0.0`, `NaNs` with a
437    /// positive sign bit and +∞.
438    ///
439    /// # Examples
440    ///
441    /// ```rust
442    /// # use half::prelude::*;
443    ///
444    /// let nan = f16::NAN;
445    /// let f = f16::from_f32(7.0_f32);
446    /// let g = f16::from_f32(-7.0_f32);
447    ///
448    /// assert!(f.is_sign_positive());
449    /// assert!(!g.is_sign_positive());
450    /// // `NaN` can be either positive or negative
451    /// assert!(nan.is_sign_positive() != nan.is_sign_negative());
452    /// ```
453    #[inline]
454    #[must_use]
455    pub const fn is_sign_positive(self) -> bool {
456        self.0 & 0x8000u16 == 0
457    }
458
459    /// Returns `true` if and only if `self` has a negative sign, including `-0.0`, `NaNs` with a
460    /// negative sign bit and −∞.
461    ///
462    /// # Examples
463    ///
464    /// ```rust
465    /// # use half::prelude::*;
466    ///
467    /// let nan = f16::NAN;
468    /// let f = f16::from_f32(7.0f32);
469    /// let g = f16::from_f32(-7.0f32);
470    ///
471    /// assert!(!f.is_sign_negative());
472    /// assert!(g.is_sign_negative());
473    /// // `NaN` can be either positive or negative
474    /// assert!(nan.is_sign_positive() != nan.is_sign_negative());
475    /// ```
476    #[inline]
477    #[must_use]
478    pub const fn is_sign_negative(self) -> bool {
479        self.0 & 0x8000u16 != 0
480    }
481
482    /// Returns a number composed of the magnitude of `self` and the sign of `sign`.
483    ///
484    /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`.
485    /// If `self` is NaN, then NaN with the sign of `sign` is returned.
486    ///
487    /// # Examples
488    ///
489    /// ```
490    /// # use half::prelude::*;
491    /// let f = f16::from_f32(3.5);
492    ///
493    /// assert_eq!(f.copysign(f16::from_f32(0.42)), f16::from_f32(3.5));
494    /// assert_eq!(f.copysign(f16::from_f32(-0.42)), f16::from_f32(-3.5));
495    /// assert_eq!((-f).copysign(f16::from_f32(0.42)), f16::from_f32(3.5));
496    /// assert_eq!((-f).copysign(f16::from_f32(-0.42)), f16::from_f32(-3.5));
497    ///
498    /// assert!(f16::NAN.copysign(f16::from_f32(1.0)).is_nan());
499    /// ```
500    #[inline]
501    #[must_use]
502    pub const fn copysign(self, sign: f16) -> f16 {
503        f16((sign.0 & 0x8000u16) | (self.0 & 0x7FFFu16))
504    }
505
506    /// Returns the maximum of the two numbers.
507    ///
508    /// If one of the arguments is NaN, then the other argument is returned.
509    ///
510    /// # Examples
511    ///
512    /// ```
513    /// # use half::prelude::*;
514    /// let x = f16::from_f32(1.0);
515    /// let y = f16::from_f32(2.0);
516    ///
517    /// assert_eq!(x.max(y), y);
518    /// ```
519    #[inline]
520    #[must_use]
521    pub fn max(self, other: f16) -> f16 {
522        if other > self && !other.is_nan() {
523            other
524        } else {
525            self
526        }
527    }
528
529    /// Returns the minimum of the two numbers.
530    ///
531    /// If one of the arguments is NaN, then the other argument is returned.
532    ///
533    /// # Examples
534    ///
535    /// ```
536    /// # use half::prelude::*;
537    /// let x = f16::from_f32(1.0);
538    /// let y = f16::from_f32(2.0);
539    ///
540    /// assert_eq!(x.min(y), x);
541    /// ```
542    #[inline]
543    #[must_use]
544    pub fn min(self, other: f16) -> f16 {
545        if other < self && !other.is_nan() {
546            other
547        } else {
548            self
549        }
550    }
551
552    /// Restrict a value to a certain interval unless it is NaN.
553    ///
554    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`.
555    /// Otherwise this returns `self`.
556    ///
557    /// Note that this function returns NaN if the initial value was NaN as well.
558    ///
559    /// # Panics
560    /// Panics if `min > max`, `min` is NaN, or `max` is NaN.
561    ///
562    /// # Examples
563    ///
564    /// ```
565    /// # use half::prelude::*;
566    /// assert!(f16::from_f32(-3.0).clamp(f16::from_f32(-2.0), f16::from_f32(1.0)) == f16::from_f32(-2.0));
567    /// assert!(f16::from_f32(0.0).clamp(f16::from_f32(-2.0), f16::from_f32(1.0)) == f16::from_f32(0.0));
568    /// assert!(f16::from_f32(2.0).clamp(f16::from_f32(-2.0), f16::from_f32(1.0)) == f16::from_f32(1.0));
569    /// assert!(f16::NAN.clamp(f16::from_f32(-2.0), f16::from_f32(1.0)).is_nan());
570    /// ```
571    #[inline]
572    #[must_use]
573    pub fn clamp(self, min: f16, max: f16) -> f16 {
574        assert!(min <= max);
575        let mut x = self;
576        if x < min {
577            x = min;
578        }
579        if x > max {
580            x = max;
581        }
582        x
583    }
584
585    /// Returns the ordering between `self` and `other`.
586    ///
587    /// Unlike the standard partial comparison between floating point numbers,
588    /// this comparison always produces an ordering in accordance to
589    /// the `totalOrder` predicate as defined in the IEEE 754 (2008 revision)
590    /// floating point standard. The values are ordered in the following sequence:
591    ///
592    /// - negative quiet NaN
593    /// - negative signaling NaN
594    /// - negative infinity
595    /// - negative numbers
596    /// - negative subnormal numbers
597    /// - negative zero
598    /// - positive zero
599    /// - positive subnormal numbers
600    /// - positive numbers
601    /// - positive infinity
602    /// - positive signaling NaN
603    /// - positive quiet NaN.
604    ///
605    /// The ordering established by this function does not always agree with the
606    /// [`PartialOrd`] and [`PartialEq`] implementations of `f16`. For example,
607    /// they consider negative and positive zero equal, while `total_cmp`
608    /// doesn't.
609    ///
610    /// The interpretation of the signaling NaN bit follows the definition in
611    /// the IEEE 754 standard, which may not match the interpretation by some of
612    /// the older, non-conformant (e.g. MIPS) hardware implementations.
613    ///
614    /// # Examples
615    /// ```
616    /// # use half::f16;
617    /// let mut v: Vec<f16> = vec![];
618    /// v.push(f16::ONE);
619    /// v.push(f16::INFINITY);
620    /// v.push(f16::NEG_INFINITY);
621    /// v.push(f16::NAN);
622    /// v.push(f16::MAX_SUBNORMAL);
623    /// v.push(-f16::MAX_SUBNORMAL);
624    /// v.push(f16::ZERO);
625    /// v.push(f16::NEG_ZERO);
626    /// v.push(f16::NEG_ONE);
627    /// v.push(f16::MIN_POSITIVE);
628    ///
629    /// v.sort_by(|a, b| a.total_cmp(&b));
630    ///
631    /// assert!(v
632    ///     .into_iter()
633    ///     .zip(
634    ///         [
635    ///             f16::NEG_INFINITY,
636    ///             f16::NEG_ONE,
637    ///             -f16::MAX_SUBNORMAL,
638    ///             f16::NEG_ZERO,
639    ///             f16::ZERO,
640    ///             f16::MAX_SUBNORMAL,
641    ///             f16::MIN_POSITIVE,
642    ///             f16::ONE,
643    ///             f16::INFINITY,
644    ///             f16::NAN
645    ///         ]
646    ///         .iter()
647    ///     )
648    ///     .all(|(a, b)| a.to_bits() == b.to_bits()));
649    /// ```
650    // Implementation based on: https://doc.rust-lang.org/std/primitive.f32.html#method.total_cmp
651    #[inline]
652    #[must_use]
653    pub fn total_cmp(&self, other: &Self) -> Ordering {
654        let mut left = self.to_bits() as i16;
655        let mut right = other.to_bits() as i16;
656        left ^= (((left >> 15) as u16) >> 1) as i16;
657        right ^= (((right >> 15) as u16) >> 1) as i16;
658        left.cmp(&right)
659    }
660
661    /// Alternate serialize adapter for serializing as a float.
662    ///
663    /// By default, [`f16`] serializes as a newtype of [`u16`]. This is an alternate serialize
664    /// implementation that serializes as an [`f32`] value. It is designed for use with
665    /// `serialize_with` serde attributes. Deserialization from `f32` values is already supported by
666    /// the default deserialize implementation.
667    ///
668    /// # Examples
669    ///
670    /// A demonstration on how to use this adapater:
671    ///
672    /// ```
673    /// use serde::{Serialize, Deserialize};
674    /// use half::f16;
675    ///
676    /// #[derive(Serialize, Deserialize)]
677    /// struct MyStruct {
678    ///     #[serde(serialize_with = "f16::serialize_as_f32")]
679    ///     value: f16 // Will be serialized as f32 instead of u16
680    /// }
681    /// ```
682    #[cfg(feature = "serde")]
683    pub fn serialize_as_f32<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
684        serializer.serialize_f32(self.to_f32())
685    }
686
687    /// Alternate serialize adapter for serializing as a string.
688    ///
689    /// By default, [`f16`] serializes as a newtype of [`u16`]. This is an alternate serialize
690    /// implementation that serializes as a string value. It is designed for use with
691    /// `serialize_with` serde attributes. Deserialization from string values is already supported
692    /// by the default deserialize implementation.
693    ///
694    /// # Examples
695    ///
696    /// A demonstration on how to use this adapater:
697    ///
698    /// ```
699    /// use serde::{Serialize, Deserialize};
700    /// use half::f16;
701    ///
702    /// #[derive(Serialize, Deserialize)]
703    /// struct MyStruct {
704    ///     #[serde(serialize_with = "f16::serialize_as_string")]
705    ///     value: f16 // Will be serialized as a string instead of u16
706    /// }
707    /// ```
708    #[cfg(all(feature = "serde", feature = "alloc"))]
709    pub fn serialize_as_string<S: serde::Serializer>(
710        &self,
711        serializer: S,
712    ) -> Result<S::Ok, S::Error> {
713        serializer.serialize_str(&self.to_string())
714    }
715
716    /// Approximate number of [`f16`] significant digits in base 10
717    pub const DIGITS: u32 = 3;
718    /// [`f16`]
719    /// [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon) value
720    ///
721    /// This is the difference between 1.0 and the next largest representable number.
722    pub const EPSILON: f16 = f16(0x1400u16);
723    /// [`f16`] positive Infinity (+∞)
724    pub const INFINITY: f16 = f16(0x7C00u16);
725    /// Number of [`f16`] significant digits in base 2
726    pub const MANTISSA_DIGITS: u32 = 11;
727    /// Largest finite [`f16`] value
728    pub const MAX: f16 = f16(0x7BFF);
729    /// Maximum possible [`f16`] power of 10 exponent
730    pub const MAX_10_EXP: i32 = 4;
731    /// Maximum possible [`f16`] power of 2 exponent
732    pub const MAX_EXP: i32 = 16;
733    /// Smallest finite [`f16`] value
734    pub const MIN: f16 = f16(0xFBFF);
735    /// Minimum possible normal [`f16`] power of 10 exponent
736    pub const MIN_10_EXP: i32 = -4;
737    /// One greater than the minimum possible normal [`f16`] power of 2 exponent
738    pub const MIN_EXP: i32 = -13;
739    /// Smallest positive normal [`f16`] value
740    pub const MIN_POSITIVE: f16 = f16(0x0400u16);
741    /// [`f16`] Not a Number (NaN)
742    pub const NAN: f16 = f16(0x7E00u16);
743    /// [`f16`] negative infinity (-∞)
744    pub const NEG_INFINITY: f16 = f16(0xFC00u16);
745    /// The radix or base of the internal representation of [`f16`]
746    pub const RADIX: u32 = 2;
747
748    /// Minimum positive subnormal [`f16`] value
749    pub const MIN_POSITIVE_SUBNORMAL: f16 = f16(0x0001u16);
750    /// Maximum subnormal [`f16`] value
751    pub const MAX_SUBNORMAL: f16 = f16(0x03FFu16);
752
753    /// [`f16`] 1
754    pub const ONE: f16 = f16(0x3C00u16);
755    /// [`f16`] 0
756    pub const ZERO: f16 = f16(0x0000u16);
757    /// [`f16`] -0
758    pub const NEG_ZERO: f16 = f16(0x8000u16);
759    /// [`f16`] -1
760    pub const NEG_ONE: f16 = f16(0xBC00u16);
761
762    /// [`f16`] Euler's number (ℯ)
763    pub const E: f16 = f16(0x4170u16);
764    /// [`f16`] Archimedes' constant (π)
765    pub const PI: f16 = f16(0x4248u16);
766    /// [`f16`] 1/π
767    pub const FRAC_1_PI: f16 = f16(0x3518u16);
768    /// [`f16`] 1/√2
769    pub const FRAC_1_SQRT_2: f16 = f16(0x39A8u16);
770    /// [`f16`] 2/π
771    pub const FRAC_2_PI: f16 = f16(0x3918u16);
772    /// [`f16`] 2/√π
773    pub const FRAC_2_SQRT_PI: f16 = f16(0x3C83u16);
774    /// [`f16`] π/2
775    pub const FRAC_PI_2: f16 = f16(0x3E48u16);
776    /// [`f16`] π/3
777    pub const FRAC_PI_3: f16 = f16(0x3C30u16);
778    /// [`f16`] π/4
779    pub const FRAC_PI_4: f16 = f16(0x3A48u16);
780    /// [`f16`] π/6
781    pub const FRAC_PI_6: f16 = f16(0x3830u16);
782    /// [`f16`] π/8
783    pub const FRAC_PI_8: f16 = f16(0x3648u16);
784    /// [`f16`] 𝗅𝗇 10
785    pub const LN_10: f16 = f16(0x409Bu16);
786    /// [`f16`] 𝗅𝗇 2
787    pub const LN_2: f16 = f16(0x398Cu16);
788    /// [`f16`] 𝗅𝗈𝗀₁₀ℯ
789    pub const LOG10_E: f16 = f16(0x36F3u16);
790    /// [`f16`] 𝗅𝗈𝗀₁₀2
791    pub const LOG10_2: f16 = f16(0x34D1u16);
792    /// [`f16`] 𝗅𝗈𝗀₂ℯ
793    pub const LOG2_E: f16 = f16(0x3DC5u16);
794    /// [`f16`] 𝗅𝗈𝗀₂10
795    pub const LOG2_10: f16 = f16(0x42A5u16);
796    /// [`f16`] √2
797    pub const SQRT_2: f16 = f16(0x3DA8u16);
798}
799
800impl From<f16> for f32 {
801    #[inline]
802    fn from(x: f16) -> f32 {
803        x.to_f32()
804    }
805}
806
807impl From<f16> for f64 {
808    #[inline]
809    fn from(x: f16) -> f64 {
810        x.to_f64()
811    }
812}
813
814impl From<i8> for f16 {
815    #[inline]
816    fn from(x: i8) -> f16 {
817        // Convert to f32, then to f16
818        f16::from_f32(f32::from(x))
819    }
820}
821
822impl From<u8> for f16 {
823    #[inline]
824    fn from(x: u8) -> f16 {
825        // Convert to f32, then to f16
826        f16::from_f32(f32::from(x))
827    }
828}
829
830impl PartialEq for f16 {
831    fn eq(&self, other: &f16) -> bool {
832        if self.is_nan() || other.is_nan() {
833            false
834        } else {
835            (self.0 == other.0) || ((self.0 | other.0) & 0x7FFFu16 == 0)
836        }
837    }
838}
839
840impl PartialOrd for f16 {
841    fn partial_cmp(&self, other: &f16) -> Option<Ordering> {
842        if self.is_nan() || other.is_nan() {
843            None
844        } else {
845            let neg = self.0 & 0x8000u16 != 0;
846            let other_neg = other.0 & 0x8000u16 != 0;
847            match (neg, other_neg) {
848                (false, false) => Some(self.0.cmp(&other.0)),
849                (false, true) => {
850                    if (self.0 | other.0) & 0x7FFFu16 == 0 {
851                        Some(Ordering::Equal)
852                    } else {
853                        Some(Ordering::Greater)
854                    }
855                }
856                (true, false) => {
857                    if (self.0 | other.0) & 0x7FFFu16 == 0 {
858                        Some(Ordering::Equal)
859                    } else {
860                        Some(Ordering::Less)
861                    }
862                }
863                (true, true) => Some(other.0.cmp(&self.0)),
864            }
865        }
866    }
867
868    fn lt(&self, other: &f16) -> bool {
869        if self.is_nan() || other.is_nan() {
870            false
871        } else {
872            let neg = self.0 & 0x8000u16 != 0;
873            let other_neg = other.0 & 0x8000u16 != 0;
874            match (neg, other_neg) {
875                (false, false) => self.0 < other.0,
876                (false, true) => false,
877                (true, false) => (self.0 | other.0) & 0x7FFFu16 != 0,
878                (true, true) => self.0 > other.0,
879            }
880        }
881    }
882
883    fn le(&self, other: &f16) -> bool {
884        if self.is_nan() || other.is_nan() {
885            false
886        } else {
887            let neg = self.0 & 0x8000u16 != 0;
888            let other_neg = other.0 & 0x8000u16 != 0;
889            match (neg, other_neg) {
890                (false, false) => self.0 <= other.0,
891                (false, true) => (self.0 | other.0) & 0x7FFFu16 == 0,
892                (true, false) => true,
893                (true, true) => self.0 >= other.0,
894            }
895        }
896    }
897
898    fn gt(&self, other: &f16) -> bool {
899        if self.is_nan() || other.is_nan() {
900            false
901        } else {
902            let neg = self.0 & 0x8000u16 != 0;
903            let other_neg = other.0 & 0x8000u16 != 0;
904            match (neg, other_neg) {
905                (false, false) => self.0 > other.0,
906                (false, true) => (self.0 | other.0) & 0x7FFFu16 != 0,
907                (true, false) => false,
908                (true, true) => self.0 < other.0,
909            }
910        }
911    }
912
913    fn ge(&self, other: &f16) -> bool {
914        if self.is_nan() || other.is_nan() {
915            false
916        } else {
917            let neg = self.0 & 0x8000u16 != 0;
918            let other_neg = other.0 & 0x8000u16 != 0;
919            match (neg, other_neg) {
920                (false, false) => self.0 >= other.0,
921                (false, true) => true,
922                (true, false) => (self.0 | other.0) & 0x7FFFu16 == 0,
923                (true, true) => self.0 <= other.0,
924            }
925        }
926    }
927}
928
929#[cfg(not(target_arch = "spirv"))]
930impl FromStr for f16 {
931    type Err = ParseFloatError;
932    fn from_str(src: &str) -> Result<f16, ParseFloatError> {
933        f32::from_str(src).map(f16::from_f32)
934    }
935}
936
937#[cfg(not(target_arch = "spirv"))]
938impl Debug for f16 {
939    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
940        Debug::fmt(&self.to_f32(), f)
941    }
942}
943
944#[cfg(not(target_arch = "spirv"))]
945impl Display for f16 {
946    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
947        Display::fmt(&self.to_f32(), f)
948    }
949}
950
951#[cfg(not(target_arch = "spirv"))]
952impl LowerExp for f16 {
953    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
954        write!(f, "{:e}", self.to_f32())
955    }
956}
957
958#[cfg(not(target_arch = "spirv"))]
959impl UpperExp for f16 {
960    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
961        write!(f, "{:E}", self.to_f32())
962    }
963}
964
965#[cfg(not(target_arch = "spirv"))]
966impl Binary for f16 {
967    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
968        write!(f, "{:b}", self.0)
969    }
970}
971
972#[cfg(not(target_arch = "spirv"))]
973impl Octal for f16 {
974    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
975        write!(f, "{:o}", self.0)
976    }
977}
978
979#[cfg(not(target_arch = "spirv"))]
980impl LowerHex for f16 {
981    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
982        write!(f, "{:x}", self.0)
983    }
984}
985
986#[cfg(not(target_arch = "spirv"))]
987impl UpperHex for f16 {
988    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
989        write!(f, "{:X}", self.0)
990    }
991}
992
993impl Neg for f16 {
994    type Output = Self;
995
996    #[inline]
997    fn neg(self) -> Self::Output {
998        Self(self.0 ^ 0x8000)
999    }
1000}
1001
1002impl Neg for &f16 {
1003    type Output = <f16 as Neg>::Output;
1004
1005    #[inline]
1006    fn neg(self) -> Self::Output {
1007        Neg::neg(*self)
1008    }
1009}
1010
1011impl Add for f16 {
1012    type Output = Self;
1013
1014    #[inline]
1015    fn add(self, rhs: Self) -> Self::Output {
1016        f16(arch::add_f16(self.0, rhs.0))
1017    }
1018}
1019
1020impl Add<&f16> for f16 {
1021    type Output = <f16 as Add<f16>>::Output;
1022
1023    #[inline]
1024    fn add(self, rhs: &f16) -> Self::Output {
1025        self.add(*rhs)
1026    }
1027}
1028
1029impl Add<&f16> for &f16 {
1030    type Output = <f16 as Add<f16>>::Output;
1031
1032    #[inline]
1033    fn add(self, rhs: &f16) -> Self::Output {
1034        (*self).add(*rhs)
1035    }
1036}
1037
1038impl Add<f16> for &f16 {
1039    type Output = <f16 as Add<f16>>::Output;
1040
1041    #[inline]
1042    fn add(self, rhs: f16) -> Self::Output {
1043        (*self).add(rhs)
1044    }
1045}
1046
1047impl AddAssign for f16 {
1048    #[inline]
1049    fn add_assign(&mut self, rhs: Self) {
1050        *self = (*self).add(rhs);
1051    }
1052}
1053
1054impl AddAssign<&f16> for f16 {
1055    #[inline]
1056    fn add_assign(&mut self, rhs: &f16) {
1057        *self = (*self).add(rhs);
1058    }
1059}
1060
1061impl Sub for f16 {
1062    type Output = Self;
1063
1064    #[inline]
1065    fn sub(self, rhs: Self) -> Self::Output {
1066        f16(arch::subtract_f16(self.0, rhs.0))
1067    }
1068}
1069
1070impl Sub<&f16> for f16 {
1071    type Output = <f16 as Sub<f16>>::Output;
1072
1073    #[inline]
1074    fn sub(self, rhs: &f16) -> Self::Output {
1075        self.sub(*rhs)
1076    }
1077}
1078
1079impl Sub<&f16> for &f16 {
1080    type Output = <f16 as Sub<f16>>::Output;
1081
1082    #[inline]
1083    fn sub(self, rhs: &f16) -> Self::Output {
1084        (*self).sub(*rhs)
1085    }
1086}
1087
1088impl Sub<f16> for &f16 {
1089    type Output = <f16 as Sub<f16>>::Output;
1090
1091    #[inline]
1092    fn sub(self, rhs: f16) -> Self::Output {
1093        (*self).sub(rhs)
1094    }
1095}
1096
1097impl SubAssign for f16 {
1098    #[inline]
1099    fn sub_assign(&mut self, rhs: Self) {
1100        *self = (*self).sub(rhs);
1101    }
1102}
1103
1104impl SubAssign<&f16> for f16 {
1105    #[inline]
1106    fn sub_assign(&mut self, rhs: &f16) {
1107        *self = (*self).sub(rhs);
1108    }
1109}
1110
1111impl Mul for f16 {
1112    type Output = Self;
1113
1114    #[inline]
1115    fn mul(self, rhs: Self) -> Self::Output {
1116        f16(arch::multiply_f16(self.0, rhs.0))
1117    }
1118}
1119
1120impl Mul<&f16> for f16 {
1121    type Output = <f16 as Mul<f16>>::Output;
1122
1123    #[inline]
1124    fn mul(self, rhs: &f16) -> Self::Output {
1125        self.mul(*rhs)
1126    }
1127}
1128
1129impl Mul<&f16> for &f16 {
1130    type Output = <f16 as Mul<f16>>::Output;
1131
1132    #[inline]
1133    fn mul(self, rhs: &f16) -> Self::Output {
1134        (*self).mul(*rhs)
1135    }
1136}
1137
1138impl Mul<f16> for &f16 {
1139    type Output = <f16 as Mul<f16>>::Output;
1140
1141    #[inline]
1142    fn mul(self, rhs: f16) -> Self::Output {
1143        (*self).mul(rhs)
1144    }
1145}
1146
1147impl MulAssign for f16 {
1148    #[inline]
1149    fn mul_assign(&mut self, rhs: Self) {
1150        *self = (*self).mul(rhs);
1151    }
1152}
1153
1154impl MulAssign<&f16> for f16 {
1155    #[inline]
1156    fn mul_assign(&mut self, rhs: &f16) {
1157        *self = (*self).mul(rhs);
1158    }
1159}
1160
1161impl Div for f16 {
1162    type Output = Self;
1163
1164    #[inline]
1165    fn div(self, rhs: Self) -> Self::Output {
1166        f16(arch::divide_f16(self.0, rhs.0))
1167    }
1168}
1169
1170impl Div<&f16> for f16 {
1171    type Output = <f16 as Div<f16>>::Output;
1172
1173    #[inline]
1174    fn div(self, rhs: &f16) -> Self::Output {
1175        self.div(*rhs)
1176    }
1177}
1178
1179impl Div<&f16> for &f16 {
1180    type Output = <f16 as Div<f16>>::Output;
1181
1182    #[inline]
1183    fn div(self, rhs: &f16) -> Self::Output {
1184        (*self).div(*rhs)
1185    }
1186}
1187
1188impl Div<f16> for &f16 {
1189    type Output = <f16 as Div<f16>>::Output;
1190
1191    #[inline]
1192    fn div(self, rhs: f16) -> Self::Output {
1193        (*self).div(rhs)
1194    }
1195}
1196
1197impl DivAssign for f16 {
1198    #[inline]
1199    fn div_assign(&mut self, rhs: Self) {
1200        *self = (*self).div(rhs);
1201    }
1202}
1203
1204impl DivAssign<&f16> for f16 {
1205    #[inline]
1206    fn div_assign(&mut self, rhs: &f16) {
1207        *self = (*self).div(rhs);
1208    }
1209}
1210
1211impl Rem for f16 {
1212    type Output = Self;
1213
1214    #[inline]
1215    fn rem(self, rhs: Self) -> Self::Output {
1216        f16(arch::remainder_f16(self.0, rhs.0))
1217    }
1218}
1219
1220impl Rem<&f16> for f16 {
1221    type Output = <f16 as Rem<f16>>::Output;
1222
1223    #[inline]
1224    fn rem(self, rhs: &f16) -> Self::Output {
1225        self.rem(*rhs)
1226    }
1227}
1228
1229impl Rem<&f16> for &f16 {
1230    type Output = <f16 as Rem<f16>>::Output;
1231
1232    #[inline]
1233    fn rem(self, rhs: &f16) -> Self::Output {
1234        (*self).rem(*rhs)
1235    }
1236}
1237
1238impl Rem<f16> for &f16 {
1239    type Output = <f16 as Rem<f16>>::Output;
1240
1241    #[inline]
1242    fn rem(self, rhs: f16) -> Self::Output {
1243        (*self).rem(rhs)
1244    }
1245}
1246
1247impl RemAssign for f16 {
1248    #[inline]
1249    fn rem_assign(&mut self, rhs: Self) {
1250        *self = (*self).rem(rhs);
1251    }
1252}
1253
1254impl RemAssign<&f16> for f16 {
1255    #[inline]
1256    fn rem_assign(&mut self, rhs: &f16) {
1257        *self = (*self).rem(rhs);
1258    }
1259}
1260
1261impl Product for f16 {
1262    #[inline]
1263    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
1264        f16(arch::product_f16(iter.map(|f| f.to_bits())))
1265    }
1266}
1267
1268impl<'a> Product<&'a f16> for f16 {
1269    #[inline]
1270    fn product<I: Iterator<Item = &'a f16>>(iter: I) -> Self {
1271        f16(arch::product_f16(iter.map(|f| f.to_bits())))
1272    }
1273}
1274
1275impl Sum for f16 {
1276    #[inline]
1277    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1278        f16(arch::sum_f16(iter.map(|f| f.to_bits())))
1279    }
1280}
1281
1282impl<'a> Sum<&'a f16> for f16 {
1283    #[inline]
1284    fn sum<I: Iterator<Item = &'a f16>>(iter: I) -> Self {
1285        f16(arch::sum_f16(iter.map(|f| f.to_bits())))
1286    }
1287}
1288
1289#[cfg(feature = "serde")]
1290struct Visitor;
1291
1292#[cfg(feature = "serde")]
1293impl<'de> Deserialize<'de> for f16 {
1294    fn deserialize<D>(deserializer: D) -> Result<f16, D::Error>
1295    where
1296        D: serde::de::Deserializer<'de>,
1297    {
1298        deserializer.deserialize_newtype_struct("f16", Visitor)
1299    }
1300}
1301
1302#[cfg(feature = "serde")]
1303impl<'de> serde::de::Visitor<'de> for Visitor {
1304    type Value = f16;
1305
1306    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
1307        write!(formatter, "tuple struct f16")
1308    }
1309
1310    fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1311    where
1312        D: serde::Deserializer<'de>,
1313    {
1314        Ok(f16(<u16 as Deserialize>::deserialize(deserializer)?))
1315    }
1316
1317    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1318    where
1319        E: serde::de::Error,
1320    {
1321        v.parse().map_err(|_| {
1322            serde::de::Error::invalid_value(serde::de::Unexpected::Str(v), &"a float string")
1323        })
1324    }
1325
1326    fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
1327    where
1328        E: serde::de::Error,
1329    {
1330        Ok(f16::from_f32(v))
1331    }
1332
1333    fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
1334    where
1335        E: serde::de::Error,
1336    {
1337        Ok(f16::from_f64(v))
1338    }
1339}
1340
1341#[allow(
1342    clippy::cognitive_complexity,
1343    clippy::float_cmp,
1344    clippy::neg_cmp_op_on_partial_ord
1345)]
1346#[cfg(test)]
1347mod test {
1348    use super::*;
1349    #[allow(unused_imports)]
1350    use core::cmp::Ordering;
1351    #[cfg(feature = "num-traits")]
1352    use num_traits::{AsPrimitive, FromPrimitive, ToPrimitive};
1353    use quickcheck_macros::quickcheck;
1354
1355    #[cfg(feature = "num-traits")]
1356    #[test]
1357    fn as_primitive() {
1358        let two = f16::from_f32(2.0);
1359        assert_eq!(<i32 as AsPrimitive<f16>>::as_(2), two);
1360        assert_eq!(<f16 as AsPrimitive<i32>>::as_(two), 2);
1361
1362        assert_eq!(<f32 as AsPrimitive<f16>>::as_(2.0), two);
1363        assert_eq!(<f16 as AsPrimitive<f32>>::as_(two), 2.0);
1364
1365        assert_eq!(<f64 as AsPrimitive<f16>>::as_(2.0), two);
1366        assert_eq!(<f16 as AsPrimitive<f64>>::as_(two), 2.0);
1367    }
1368
1369    #[cfg(feature = "num-traits")]
1370    #[test]
1371    fn to_primitive() {
1372        let two = f16::from_f32(2.0);
1373        assert_eq!(ToPrimitive::to_i32(&two).unwrap(), 2i32);
1374        assert_eq!(ToPrimitive::to_f32(&two).unwrap(), 2.0f32);
1375        assert_eq!(ToPrimitive::to_f64(&two).unwrap(), 2.0f64);
1376    }
1377
1378    #[cfg(feature = "num-traits")]
1379    #[test]
1380    fn from_primitive() {
1381        let two = f16::from_f32(2.0);
1382        assert_eq!(<f16 as FromPrimitive>::from_i32(2).unwrap(), two);
1383        assert_eq!(<f16 as FromPrimitive>::from_f32(2.0).unwrap(), two);
1384        assert_eq!(<f16 as FromPrimitive>::from_f64(2.0).unwrap(), two);
1385    }
1386
1387    #[test]
1388    fn test_f16_consts() {
1389        // DIGITS
1390        let digits = ((f16::MANTISSA_DIGITS as f32 - 1.0) * 2f32.log10()).floor() as u32;
1391        assert_eq!(f16::DIGITS, digits);
1392        // sanity check to show test is good
1393        let digits32 = ((core::f32::MANTISSA_DIGITS as f32 - 1.0) * 2f32.log10()).floor() as u32;
1394        assert_eq!(core::f32::DIGITS, digits32);
1395
1396        // EPSILON
1397        let one = f16::from_f32(1.0);
1398        let one_plus_epsilon = f16::from_bits(one.to_bits() + 1);
1399        let epsilon = f16::from_f32(one_plus_epsilon.to_f32() - 1.0);
1400        assert_eq!(f16::EPSILON, epsilon);
1401        // sanity check to show test is good
1402        let one_plus_epsilon32 = f32::from_bits(1.0f32.to_bits() + 1);
1403        let epsilon32 = one_plus_epsilon32 - 1f32;
1404        assert_eq!(core::f32::EPSILON, epsilon32);
1405
1406        // MAX, MIN and MIN_POSITIVE
1407        let max = f16::from_bits(f16::INFINITY.to_bits() - 1);
1408        let min = f16::from_bits(f16::NEG_INFINITY.to_bits() - 1);
1409        let min_pos = f16::from_f32(2f32.powi(f16::MIN_EXP - 1));
1410        assert_eq!(f16::MAX, max);
1411        assert_eq!(f16::MIN, min);
1412        assert_eq!(f16::MIN_POSITIVE, min_pos);
1413        // sanity check to show test is good
1414        let max32 = f32::from_bits(core::f32::INFINITY.to_bits() - 1);
1415        let min32 = f32::from_bits(core::f32::NEG_INFINITY.to_bits() - 1);
1416        let min_pos32 = 2f32.powi(core::f32::MIN_EXP - 1);
1417        assert_eq!(core::f32::MAX, max32);
1418        assert_eq!(core::f32::MIN, min32);
1419        assert_eq!(core::f32::MIN_POSITIVE, min_pos32);
1420
1421        // MIN_10_EXP and MAX_10_EXP
1422        let ten_to_min = 10f32.powi(f16::MIN_10_EXP);
1423        assert!(ten_to_min / 10.0 < f16::MIN_POSITIVE.to_f32());
1424        assert!(ten_to_min > f16::MIN_POSITIVE.to_f32());
1425        let ten_to_max = 10f32.powi(f16::MAX_10_EXP);
1426        assert!(ten_to_max < f16::MAX.to_f32());
1427        assert!(ten_to_max * 10.0 > f16::MAX.to_f32());
1428        // sanity check to show test is good
1429        let ten_to_min32 = 10f64.powi(core::f32::MIN_10_EXP);
1430        assert!(ten_to_min32 / 10.0 < f64::from(core::f32::MIN_POSITIVE));
1431        assert!(ten_to_min32 > f64::from(core::f32::MIN_POSITIVE));
1432        let ten_to_max32 = 10f64.powi(core::f32::MAX_10_EXP);
1433        assert!(ten_to_max32 < f64::from(core::f32::MAX));
1434        assert!(ten_to_max32 * 10.0 > f64::from(core::f32::MAX));
1435    }
1436
1437    #[test]
1438    fn test_f16_consts_from_f32() {
1439        let one = f16::from_f32(1.0);
1440        let zero = f16::from_f32(0.0);
1441        let neg_zero = f16::from_f32(-0.0);
1442        let neg_one = f16::from_f32(-1.0);
1443        let inf = f16::from_f32(core::f32::INFINITY);
1444        let neg_inf = f16::from_f32(core::f32::NEG_INFINITY);
1445        let nan = f16::from_f32(core::f32::NAN);
1446
1447        assert_eq!(f16::ONE, one);
1448        assert_eq!(f16::ZERO, zero);
1449        assert!(zero.is_sign_positive());
1450        assert_eq!(f16::NEG_ZERO, neg_zero);
1451        assert!(neg_zero.is_sign_negative());
1452        assert_eq!(f16::NEG_ONE, neg_one);
1453        assert!(neg_one.is_sign_negative());
1454        assert_eq!(f16::INFINITY, inf);
1455        assert_eq!(f16::NEG_INFINITY, neg_inf);
1456        assert!(nan.is_nan());
1457        assert!(f16::NAN.is_nan());
1458
1459        let e = f16::from_f32(core::f32::consts::E);
1460        let pi = f16::from_f32(core::f32::consts::PI);
1461        let frac_1_pi = f16::from_f32(core::f32::consts::FRAC_1_PI);
1462        let frac_1_sqrt_2 = f16::from_f32(core::f32::consts::FRAC_1_SQRT_2);
1463        let frac_2_pi = f16::from_f32(core::f32::consts::FRAC_2_PI);
1464        let frac_2_sqrt_pi = f16::from_f32(core::f32::consts::FRAC_2_SQRT_PI);
1465        let frac_pi_2 = f16::from_f32(core::f32::consts::FRAC_PI_2);
1466        let frac_pi_3 = f16::from_f32(core::f32::consts::FRAC_PI_3);
1467        let frac_pi_4 = f16::from_f32(core::f32::consts::FRAC_PI_4);
1468        let frac_pi_6 = f16::from_f32(core::f32::consts::FRAC_PI_6);
1469        let frac_pi_8 = f16::from_f32(core::f32::consts::FRAC_PI_8);
1470        let ln_10 = f16::from_f32(core::f32::consts::LN_10);
1471        let ln_2 = f16::from_f32(core::f32::consts::LN_2);
1472        let log10_e = f16::from_f32(core::f32::consts::LOG10_E);
1473        // core::f32::consts::LOG10_2 requires rustc 1.43.0
1474        let log10_2 = f16::from_f32(2f32.log10());
1475        let log2_e = f16::from_f32(core::f32::consts::LOG2_E);
1476        // core::f32::consts::LOG2_10 requires rustc 1.43.0
1477        let log2_10 = f16::from_f32(10f32.log2());
1478        let sqrt_2 = f16::from_f32(core::f32::consts::SQRT_2);
1479
1480        assert_eq!(f16::E, e);
1481        assert_eq!(f16::PI, pi);
1482        assert_eq!(f16::FRAC_1_PI, frac_1_pi);
1483        assert_eq!(f16::FRAC_1_SQRT_2, frac_1_sqrt_2);
1484        assert_eq!(f16::FRAC_2_PI, frac_2_pi);
1485        assert_eq!(f16::FRAC_2_SQRT_PI, frac_2_sqrt_pi);
1486        assert_eq!(f16::FRAC_PI_2, frac_pi_2);
1487        assert_eq!(f16::FRAC_PI_3, frac_pi_3);
1488        assert_eq!(f16::FRAC_PI_4, frac_pi_4);
1489        assert_eq!(f16::FRAC_PI_6, frac_pi_6);
1490        assert_eq!(f16::FRAC_PI_8, frac_pi_8);
1491        assert_eq!(f16::LN_10, ln_10);
1492        assert_eq!(f16::LN_2, ln_2);
1493        assert_eq!(f16::LOG10_E, log10_e);
1494        assert_eq!(f16::LOG10_2, log10_2);
1495        assert_eq!(f16::LOG2_E, log2_e);
1496        assert_eq!(f16::LOG2_10, log2_10);
1497        assert_eq!(f16::SQRT_2, sqrt_2);
1498    }
1499
1500    #[test]
1501    fn test_f16_consts_from_f64() {
1502        let one = f16::from_f64(1.0);
1503        let zero = f16::from_f64(0.0);
1504        let neg_zero = f16::from_f64(-0.0);
1505        let inf = f16::from_f64(core::f64::INFINITY);
1506        let neg_inf = f16::from_f64(core::f64::NEG_INFINITY);
1507        let nan = f16::from_f64(core::f64::NAN);
1508
1509        assert_eq!(f16::ONE, one);
1510        assert_eq!(f16::ZERO, zero);
1511        assert!(zero.is_sign_positive());
1512        assert_eq!(f16::NEG_ZERO, neg_zero);
1513        assert!(neg_zero.is_sign_negative());
1514        assert_eq!(f16::INFINITY, inf);
1515        assert_eq!(f16::NEG_INFINITY, neg_inf);
1516        assert!(nan.is_nan());
1517        assert!(f16::NAN.is_nan());
1518
1519        let e = f16::from_f64(core::f64::consts::E);
1520        let pi = f16::from_f64(core::f64::consts::PI);
1521        let frac_1_pi = f16::from_f64(core::f64::consts::FRAC_1_PI);
1522        let frac_1_sqrt_2 = f16::from_f64(core::f64::consts::FRAC_1_SQRT_2);
1523        let frac_2_pi = f16::from_f64(core::f64::consts::FRAC_2_PI);
1524        let frac_2_sqrt_pi = f16::from_f64(core::f64::consts::FRAC_2_SQRT_PI);
1525        let frac_pi_2 = f16::from_f64(core::f64::consts::FRAC_PI_2);
1526        let frac_pi_3 = f16::from_f64(core::f64::consts::FRAC_PI_3);
1527        let frac_pi_4 = f16::from_f64(core::f64::consts::FRAC_PI_4);
1528        let frac_pi_6 = f16::from_f64(core::f64::consts::FRAC_PI_6);
1529        let frac_pi_8 = f16::from_f64(core::f64::consts::FRAC_PI_8);
1530        let ln_10 = f16::from_f64(core::f64::consts::LN_10);
1531        let ln_2 = f16::from_f64(core::f64::consts::LN_2);
1532        let log10_e = f16::from_f64(core::f64::consts::LOG10_E);
1533        // core::f64::consts::LOG10_2 requires rustc 1.43.0
1534        let log10_2 = f16::from_f64(2f64.log10());
1535        let log2_e = f16::from_f64(core::f64::consts::LOG2_E);
1536        // core::f64::consts::LOG2_10 requires rustc 1.43.0
1537        let log2_10 = f16::from_f64(10f64.log2());
1538        let sqrt_2 = f16::from_f64(core::f64::consts::SQRT_2);
1539
1540        assert_eq!(f16::E, e);
1541        assert_eq!(f16::PI, pi);
1542        assert_eq!(f16::FRAC_1_PI, frac_1_pi);
1543        assert_eq!(f16::FRAC_1_SQRT_2, frac_1_sqrt_2);
1544        assert_eq!(f16::FRAC_2_PI, frac_2_pi);
1545        assert_eq!(f16::FRAC_2_SQRT_PI, frac_2_sqrt_pi);
1546        assert_eq!(f16::FRAC_PI_2, frac_pi_2);
1547        assert_eq!(f16::FRAC_PI_3, frac_pi_3);
1548        assert_eq!(f16::FRAC_PI_4, frac_pi_4);
1549        assert_eq!(f16::FRAC_PI_6, frac_pi_6);
1550        assert_eq!(f16::FRAC_PI_8, frac_pi_8);
1551        assert_eq!(f16::LN_10, ln_10);
1552        assert_eq!(f16::LN_2, ln_2);
1553        assert_eq!(f16::LOG10_E, log10_e);
1554        assert_eq!(f16::LOG10_2, log10_2);
1555        assert_eq!(f16::LOG2_E, log2_e);
1556        assert_eq!(f16::LOG2_10, log2_10);
1557        assert_eq!(f16::SQRT_2, sqrt_2);
1558    }
1559
1560    #[test]
1561    fn test_nan_conversion_to_smaller() {
1562        let nan64 = f64::from_bits(0x7FF0_0000_0000_0001u64);
1563        let neg_nan64 = f64::from_bits(0xFFF0_0000_0000_0001u64);
1564        let nan32 = f32::from_bits(0x7F80_0001u32);
1565        let neg_nan32 = f32::from_bits(0xFF80_0001u32);
1566        let nan32_from_64 = nan64 as f32;
1567        let neg_nan32_from_64 = neg_nan64 as f32;
1568        let nan16_from_64 = f16::from_f64(nan64);
1569        let neg_nan16_from_64 = f16::from_f64(neg_nan64);
1570        let nan16_from_32 = f16::from_f32(nan32);
1571        let neg_nan16_from_32 = f16::from_f32(neg_nan32);
1572
1573        assert!(nan64.is_nan() && nan64.is_sign_positive());
1574        assert!(neg_nan64.is_nan() && neg_nan64.is_sign_negative());
1575        assert!(nan32.is_nan() && nan32.is_sign_positive());
1576        assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative());
1577
1578        // f32/f64 NaN conversion sign is non-deterministic: https://github.com/starkat99/half-rs/issues/103
1579        assert!(nan32_from_64.is_nan());
1580        assert!(neg_nan32_from_64.is_nan());
1581        assert!(nan16_from_64.is_nan());
1582        assert!(neg_nan16_from_64.is_nan());
1583        assert!(nan16_from_32.is_nan());
1584        assert!(neg_nan16_from_32.is_nan());
1585    }
1586
1587    #[test]
1588    fn test_nan_conversion_to_larger() {
1589        let nan16 = f16::from_bits(0x7C01u16);
1590        let neg_nan16 = f16::from_bits(0xFC01u16);
1591        let nan32 = f32::from_bits(0x7F80_0001u32);
1592        let neg_nan32 = f32::from_bits(0xFF80_0001u32);
1593        let nan32_from_16 = f32::from(nan16);
1594        let neg_nan32_from_16 = f32::from(neg_nan16);
1595        let nan64_from_16 = f64::from(nan16);
1596        let neg_nan64_from_16 = f64::from(neg_nan16);
1597        let nan64_from_32 = f64::from(nan32);
1598        let neg_nan64_from_32 = f64::from(neg_nan32);
1599
1600        assert!(nan16.is_nan() && nan16.is_sign_positive());
1601        assert!(neg_nan16.is_nan() && neg_nan16.is_sign_negative());
1602        assert!(nan32.is_nan() && nan32.is_sign_positive());
1603        assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative());
1604
1605        // f32/f64 NaN conversion sign is non-deterministic: https://github.com/starkat99/half-rs/issues/103
1606        assert!(nan32_from_16.is_nan());
1607        assert!(neg_nan32_from_16.is_nan());
1608        assert!(nan64_from_16.is_nan());
1609        assert!(neg_nan64_from_16.is_nan());
1610        assert!(nan64_from_32.is_nan());
1611        assert!(neg_nan64_from_32.is_nan());
1612    }
1613
1614    #[test]
1615    fn test_f16_to_f32() {
1616        let f = f16::from_f32(7.0);
1617        assert_eq!(f.to_f32(), 7.0f32);
1618
1619        // 7.1 is NOT exactly representable in 16-bit, it's rounded
1620        let f = f16::from_f32(7.1);
1621        let diff = (f.to_f32() - 7.1f32).abs();
1622        // diff must be <= 4 * EPSILON, as 7 has two more significant bits than 1
1623        assert!(diff <= 4.0 * f16::EPSILON.to_f32());
1624
1625        assert_eq!(f16::from_bits(0x0000_0001).to_f32(), 2.0f32.powi(-24));
1626        assert_eq!(f16::from_bits(0x0000_0005).to_f32(), 5.0 * 2.0f32.powi(-24));
1627
1628        assert_eq!(f16::from_bits(0x0000_0001), f16::from_f32(2.0f32.powi(-24)));
1629        assert_eq!(
1630            f16::from_bits(0x0000_0005),
1631            f16::from_f32(5.0 * 2.0f32.powi(-24))
1632        );
1633    }
1634
1635    #[test]
1636    fn test_f16_to_f64() {
1637        let f = f16::from_f64(7.0);
1638        assert_eq!(f.to_f64(), 7.0f64);
1639
1640        // 7.1 is NOT exactly representable in 16-bit, it's rounded
1641        let f = f16::from_f64(7.1);
1642        let diff = (f.to_f64() - 7.1f64).abs();
1643        // diff must be <= 4 * EPSILON, as 7 has two more significant bits than 1
1644        assert!(diff <= 4.0 * f16::EPSILON.to_f64());
1645
1646        assert_eq!(f16::from_bits(0x0000_0001).to_f64(), 2.0f64.powi(-24));
1647        assert_eq!(f16::from_bits(0x0000_0005).to_f64(), 5.0 * 2.0f64.powi(-24));
1648
1649        assert_eq!(f16::from_bits(0x0000_0001), f16::from_f64(2.0f64.powi(-24)));
1650        assert_eq!(
1651            f16::from_bits(0x0000_0005),
1652            f16::from_f64(5.0 * 2.0f64.powi(-24))
1653        );
1654    }
1655
1656    #[test]
1657    fn test_comparisons() {
1658        let zero = f16::from_f64(0.0);
1659        let one = f16::from_f64(1.0);
1660        let neg_zero = f16::from_f64(-0.0);
1661        let neg_one = f16::from_f64(-1.0);
1662
1663        assert_eq!(zero.partial_cmp(&neg_zero), Some(Ordering::Equal));
1664        assert_eq!(neg_zero.partial_cmp(&zero), Some(Ordering::Equal));
1665        assert!(zero == neg_zero);
1666        assert!(neg_zero == zero);
1667        assert!(!(zero != neg_zero));
1668        assert!(!(neg_zero != zero));
1669        assert!(!(zero < neg_zero));
1670        assert!(!(neg_zero < zero));
1671        assert!(zero <= neg_zero);
1672        assert!(neg_zero <= zero);
1673        assert!(!(zero > neg_zero));
1674        assert!(!(neg_zero > zero));
1675        assert!(zero >= neg_zero);
1676        assert!(neg_zero >= zero);
1677
1678        assert_eq!(one.partial_cmp(&neg_zero), Some(Ordering::Greater));
1679        assert_eq!(neg_zero.partial_cmp(&one), Some(Ordering::Less));
1680        assert!(!(one == neg_zero));
1681        assert!(!(neg_zero == one));
1682        assert!(one != neg_zero);
1683        assert!(neg_zero != one);
1684        assert!(!(one < neg_zero));
1685        assert!(neg_zero < one);
1686        assert!(!(one <= neg_zero));
1687        assert!(neg_zero <= one);
1688        assert!(one > neg_zero);
1689        assert!(!(neg_zero > one));
1690        assert!(one >= neg_zero);
1691        assert!(!(neg_zero >= one));
1692
1693        assert_eq!(one.partial_cmp(&neg_one), Some(Ordering::Greater));
1694        assert_eq!(neg_one.partial_cmp(&one), Some(Ordering::Less));
1695        assert!(!(one == neg_one));
1696        assert!(!(neg_one == one));
1697        assert!(one != neg_one);
1698        assert!(neg_one != one);
1699        assert!(!(one < neg_one));
1700        assert!(neg_one < one);
1701        assert!(!(one <= neg_one));
1702        assert!(neg_one <= one);
1703        assert!(one > neg_one);
1704        assert!(!(neg_one > one));
1705        assert!(one >= neg_one);
1706        assert!(!(neg_one >= one));
1707    }
1708
1709    #[test]
1710    #[allow(clippy::erasing_op, clippy::identity_op)]
1711    fn round_to_even_f32() {
1712        // smallest positive subnormal = 0b0.0000_0000_01 * 2^-14 = 2^-24
1713        let min_sub = f16::from_bits(1);
1714        let min_sub_f = (-24f32).exp2();
1715        assert_eq!(f16::from_f32(min_sub_f).to_bits(), min_sub.to_bits());
1716        assert_eq!(f32::from(min_sub).to_bits(), min_sub_f.to_bits());
1717
1718        // 0.0000000000_011111 rounded to 0.0000000000 (< tie, no rounding)
1719        // 0.0000000000_100000 rounded to 0.0000000000 (tie and even, remains at even)
1720        // 0.0000000000_100001 rounded to 0.0000000001 (> tie, rounds up)
1721        assert_eq!(
1722            f16::from_f32(min_sub_f * 0.49).to_bits(),
1723            min_sub.to_bits() * 0
1724        );
1725        assert_eq!(
1726            f16::from_f32(min_sub_f * 0.50).to_bits(),
1727            min_sub.to_bits() * 0
1728        );
1729        assert_eq!(
1730            f16::from_f32(min_sub_f * 0.51).to_bits(),
1731            min_sub.to_bits() * 1
1732        );
1733
1734        // 0.0000000001_011111 rounded to 0.0000000001 (< tie, no rounding)
1735        // 0.0000000001_100000 rounded to 0.0000000010 (tie and odd, rounds up to even)
1736        // 0.0000000001_100001 rounded to 0.0000000010 (> tie, rounds up)
1737        assert_eq!(
1738            f16::from_f32(min_sub_f * 1.49).to_bits(),
1739            min_sub.to_bits() * 1
1740        );
1741        assert_eq!(
1742            f16::from_f32(min_sub_f * 1.50).to_bits(),
1743            min_sub.to_bits() * 2
1744        );
1745        assert_eq!(
1746            f16::from_f32(min_sub_f * 1.51).to_bits(),
1747            min_sub.to_bits() * 2
1748        );
1749
1750        // 0.0000000010_011111 rounded to 0.0000000010 (< tie, no rounding)
1751        // 0.0000000010_100000 rounded to 0.0000000010 (tie and even, remains at even)
1752        // 0.0000000010_100001 rounded to 0.0000000011 (> tie, rounds up)
1753        assert_eq!(
1754            f16::from_f32(min_sub_f * 2.49).to_bits(),
1755            min_sub.to_bits() * 2
1756        );
1757        assert_eq!(
1758            f16::from_f32(min_sub_f * 2.50).to_bits(),
1759            min_sub.to_bits() * 2
1760        );
1761        assert_eq!(
1762            f16::from_f32(min_sub_f * 2.51).to_bits(),
1763            min_sub.to_bits() * 3
1764        );
1765
1766        assert_eq!(
1767            f16::from_f32(2000.49f32).to_bits(),
1768            f16::from_f32(2000.0).to_bits()
1769        );
1770        assert_eq!(
1771            f16::from_f32(2000.50f32).to_bits(),
1772            f16::from_f32(2000.0).to_bits()
1773        );
1774        assert_eq!(
1775            f16::from_f32(2000.51f32).to_bits(),
1776            f16::from_f32(2001.0).to_bits()
1777        );
1778        assert_eq!(
1779            f16::from_f32(2001.49f32).to_bits(),
1780            f16::from_f32(2001.0).to_bits()
1781        );
1782        assert_eq!(
1783            f16::from_f32(2001.50f32).to_bits(),
1784            f16::from_f32(2002.0).to_bits()
1785        );
1786        assert_eq!(
1787            f16::from_f32(2001.51f32).to_bits(),
1788            f16::from_f32(2002.0).to_bits()
1789        );
1790        assert_eq!(
1791            f16::from_f32(2002.49f32).to_bits(),
1792            f16::from_f32(2002.0).to_bits()
1793        );
1794        assert_eq!(
1795            f16::from_f32(2002.50f32).to_bits(),
1796            f16::from_f32(2002.0).to_bits()
1797        );
1798        assert_eq!(
1799            f16::from_f32(2002.51f32).to_bits(),
1800            f16::from_f32(2003.0).to_bits()
1801        );
1802    }
1803
1804    #[test]
1805    #[allow(clippy::erasing_op, clippy::identity_op)]
1806    fn round_to_even_f64() {
1807        // smallest positive subnormal = 0b0.0000_0000_01 * 2^-14 = 2^-24
1808        let min_sub = f16::from_bits(1);
1809        let min_sub_f = (-24f64).exp2();
1810        assert_eq!(f16::from_f64(min_sub_f).to_bits(), min_sub.to_bits());
1811        assert_eq!(f64::from(min_sub).to_bits(), min_sub_f.to_bits());
1812
1813        // 0.0000000000_011111 rounded to 0.0000000000 (< tie, no rounding)
1814        // 0.0000000000_100000 rounded to 0.0000000000 (tie and even, remains at even)
1815        // 0.0000000000_100001 rounded to 0.0000000001 (> tie, rounds up)
1816        assert_eq!(
1817            f16::from_f64(min_sub_f * 0.49).to_bits(),
1818            min_sub.to_bits() * 0
1819        );
1820        assert_eq!(
1821            f16::from_f64(min_sub_f * 0.50).to_bits(),
1822            min_sub.to_bits() * 0
1823        );
1824        assert_eq!(
1825            f16::from_f64(min_sub_f * 0.51).to_bits(),
1826            min_sub.to_bits() * 1
1827        );
1828
1829        // 0.0000000001_011111 rounded to 0.0000000001 (< tie, no rounding)
1830        // 0.0000000001_100000 rounded to 0.0000000010 (tie and odd, rounds up to even)
1831        // 0.0000000001_100001 rounded to 0.0000000010 (> tie, rounds up)
1832        assert_eq!(
1833            f16::from_f64(min_sub_f * 1.49).to_bits(),
1834            min_sub.to_bits() * 1
1835        );
1836        assert_eq!(
1837            f16::from_f64(min_sub_f * 1.50).to_bits(),
1838            min_sub.to_bits() * 2
1839        );
1840        assert_eq!(
1841            f16::from_f64(min_sub_f * 1.51).to_bits(),
1842            min_sub.to_bits() * 2
1843        );
1844
1845        // 0.0000000010_011111 rounded to 0.0000000010 (< tie, no rounding)
1846        // 0.0000000010_100000 rounded to 0.0000000010 (tie and even, remains at even)
1847        // 0.0000000010_100001 rounded to 0.0000000011 (> tie, rounds up)
1848        assert_eq!(
1849            f16::from_f64(min_sub_f * 2.49).to_bits(),
1850            min_sub.to_bits() * 2
1851        );
1852        assert_eq!(
1853            f16::from_f64(min_sub_f * 2.50).to_bits(),
1854            min_sub.to_bits() * 2
1855        );
1856        assert_eq!(
1857            f16::from_f64(min_sub_f * 2.51).to_bits(),
1858            min_sub.to_bits() * 3
1859        );
1860
1861        assert_eq!(
1862            f16::from_f64(2000.49f64).to_bits(),
1863            f16::from_f64(2000.0).to_bits()
1864        );
1865        assert_eq!(
1866            f16::from_f64(2000.50f64).to_bits(),
1867            f16::from_f64(2000.0).to_bits()
1868        );
1869        assert_eq!(
1870            f16::from_f64(2000.51f64).to_bits(),
1871            f16::from_f64(2001.0).to_bits()
1872        );
1873        assert_eq!(
1874            f16::from_f64(2001.49f64).to_bits(),
1875            f16::from_f64(2001.0).to_bits()
1876        );
1877        assert_eq!(
1878            f16::from_f64(2001.50f64).to_bits(),
1879            f16::from_f64(2002.0).to_bits()
1880        );
1881        assert_eq!(
1882            f16::from_f64(2001.51f64).to_bits(),
1883            f16::from_f64(2002.0).to_bits()
1884        );
1885        assert_eq!(
1886            f16::from_f64(2002.49f64).to_bits(),
1887            f16::from_f64(2002.0).to_bits()
1888        );
1889        assert_eq!(
1890            f16::from_f64(2002.50f64).to_bits(),
1891            f16::from_f64(2002.0).to_bits()
1892        );
1893        assert_eq!(
1894            f16::from_f64(2002.51f64).to_bits(),
1895            f16::from_f64(2003.0).to_bits()
1896        );
1897    }
1898
1899    #[test]
1900    fn arithmetic() {
1901        assert_eq!(f16::ONE + f16::ONE, f16::from_f32(2.));
1902        assert_eq!(f16::ONE - f16::ONE, f16::ZERO);
1903        assert_eq!(f16::ONE * f16::ONE, f16::ONE);
1904        assert_eq!(f16::from_f32(2.) * f16::from_f32(2.), f16::from_f32(4.));
1905        assert_eq!(f16::ONE / f16::ONE, f16::ONE);
1906        assert_eq!(f16::from_f32(4.) / f16::from_f32(2.), f16::from_f32(2.));
1907        assert_eq!(f16::from_f32(4.) % f16::from_f32(3.), f16::from_f32(1.));
1908    }
1909
1910    #[cfg(feature = "std")]
1911    #[test]
1912    fn formatting() {
1913        let f = f16::from_f32(0.1152344);
1914
1915        assert_eq!(format!("{:.3}", f), "0.115");
1916        assert_eq!(format!("{:.4}", f), "0.1152");
1917        assert_eq!(format!("{:+.4}", f), "+0.1152");
1918        assert_eq!(format!("{:>+10.4}", f), "   +0.1152");
1919
1920        assert_eq!(format!("{:.3?}", f), "0.115");
1921        assert_eq!(format!("{:.4?}", f), "0.1152");
1922        assert_eq!(format!("{:+.4?}", f), "+0.1152");
1923        assert_eq!(format!("{:>+10.4?}", f), "   +0.1152");
1924    }
1925
1926    impl quickcheck::Arbitrary for f16 {
1927        fn arbitrary(g: &mut quickcheck::Gen) -> Self {
1928            f16(u16::arbitrary(g))
1929        }
1930    }
1931
1932    #[quickcheck]
1933    fn qc_roundtrip_f16_f32_is_identity(f: f16) -> bool {
1934        let roundtrip = f16::from_f32(f.to_f32());
1935        if f.is_nan() {
1936            roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative()
1937        } else {
1938            f.0 == roundtrip.0
1939        }
1940    }
1941
1942    #[quickcheck]
1943    fn qc_roundtrip_f16_f64_is_identity(f: f16) -> bool {
1944        let roundtrip = f16::from_f64(f.to_f64());
1945        if f.is_nan() {
1946            roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative()
1947        } else {
1948            f.0 == roundtrip.0
1949        }
1950    }
1951}