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#[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 #[inline]
52 #[must_use]
53 pub const fn from_bits(bits: u16) -> f16 {
54 f16(bits)
55 }
56
57 #[inline]
65 #[must_use]
66 pub fn from_f32(value: f32) -> f16 {
67 f16(arch::f32_to_f16(value))
68 }
69
70 #[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 #[inline]
95 #[must_use]
96 pub fn from_f64(value: f64) -> f16 {
97 f16(arch::f64_to_f16(value))
98 }
99
100 #[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 #[inline]
119 #[must_use]
120 pub const fn to_bits(self) -> u16 {
121 self.0
122 }
123
124 #[inline]
135 #[must_use]
136 pub const fn to_le_bytes(self) -> [u8; 2] {
137 self.0.to_le_bytes()
138 }
139
140 #[inline]
151 #[must_use]
152 pub const fn to_be_bytes(self) -> [u8; 2] {
153 self.0.to_be_bytes()
154 }
155
156 #[inline]
175 #[must_use]
176 pub const fn to_ne_bytes(self) -> [u8; 2] {
177 self.0.to_ne_bytes()
178 }
179
180 #[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 #[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 #[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 #[inline]
238 #[must_use]
239 pub fn to_f32(self) -> f32 {
240 arch::f16_to_f32(self.0)
241 }
242
243 #[inline]
252 #[must_use]
253 pub const fn to_f32_const(self) -> f32 {
254 arch::f16_to_f32_fallback(self.0)
255 }
256
257 #[inline]
262 #[must_use]
263 pub fn to_f64(self) -> f64 {
264 arch::f16_to_f64(self.0)
265 }
266
267 #[inline]
276 #[must_use]
277 pub const fn to_f64_const(self) -> f64 {
278 arch::f16_to_f64_fallback(self.0)
279 }
280
281 #[inline]
295 #[must_use]
296 pub const fn is_nan(self) -> bool {
297 self.0 & 0x7FFFu16 > 0x7C00u16
298 }
299
300 #[inline]
320 #[must_use]
321 pub const fn is_infinite(self) -> bool {
322 self.0 & 0x7FFFu16 == 0x7C00u16
323 }
324
325 #[inline]
344 #[must_use]
345 pub const fn is_finite(self) -> bool {
346 self.0 & 0x7C00u16 != 0x7C00u16
347 }
348
349 #[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 #[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 #[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 #[inline]
454 #[must_use]
455 pub const fn is_sign_positive(self) -> bool {
456 self.0 & 0x8000u16 == 0
457 }
458
459 #[inline]
477 #[must_use]
478 pub const fn is_sign_negative(self) -> bool {
479 self.0 & 0x8000u16 != 0
480 }
481
482 #[inline]
501 #[must_use]
502 pub const fn copysign(self, sign: f16) -> f16 {
503 f16((sign.0 & 0x8000u16) | (self.0 & 0x7FFFu16))
504 }
505
506 #[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 #[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 #[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 #[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 #[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 #[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 pub const DIGITS: u32 = 3;
718 pub const EPSILON: f16 = f16(0x1400u16);
723 pub const INFINITY: f16 = f16(0x7C00u16);
725 pub const MANTISSA_DIGITS: u32 = 11;
727 pub const MAX: f16 = f16(0x7BFF);
729 pub const MAX_10_EXP: i32 = 4;
731 pub const MAX_EXP: i32 = 16;
733 pub const MIN: f16 = f16(0xFBFF);
735 pub const MIN_10_EXP: i32 = -4;
737 pub const MIN_EXP: i32 = -13;
739 pub const MIN_POSITIVE: f16 = f16(0x0400u16);
741 pub const NAN: f16 = f16(0x7E00u16);
743 pub const NEG_INFINITY: f16 = f16(0xFC00u16);
745 pub const RADIX: u32 = 2;
747
748 pub const MIN_POSITIVE_SUBNORMAL: f16 = f16(0x0001u16);
750 pub const MAX_SUBNORMAL: f16 = f16(0x03FFu16);
752
753 pub const ONE: f16 = f16(0x3C00u16);
755 pub const ZERO: f16 = f16(0x0000u16);
757 pub const NEG_ZERO: f16 = f16(0x8000u16);
759 pub const NEG_ONE: f16 = f16(0xBC00u16);
761
762 pub const E: f16 = f16(0x4170u16);
764 pub const PI: f16 = f16(0x4248u16);
766 pub const FRAC_1_PI: f16 = f16(0x3518u16);
768 pub const FRAC_1_SQRT_2: f16 = f16(0x39A8u16);
770 pub const FRAC_2_PI: f16 = f16(0x3918u16);
772 pub const FRAC_2_SQRT_PI: f16 = f16(0x3C83u16);
774 pub const FRAC_PI_2: f16 = f16(0x3E48u16);
776 pub const FRAC_PI_3: f16 = f16(0x3C30u16);
778 pub const FRAC_PI_4: f16 = f16(0x3A48u16);
780 pub const FRAC_PI_6: f16 = f16(0x3830u16);
782 pub const FRAC_PI_8: f16 = f16(0x3648u16);
784 pub const LN_10: f16 = f16(0x409Bu16);
786 pub const LN_2: f16 = f16(0x398Cu16);
788 pub const LOG10_E: f16 = f16(0x36F3u16);
790 pub const LOG10_2: f16 = f16(0x34D1u16);
792 pub const LOG2_E: f16 = f16(0x3DC5u16);
794 pub const LOG2_10: f16 = f16(0x42A5u16);
796 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 f16::from_f32(f32::from(x))
819 }
820}
821
822impl From<u8> for f16 {
823 #[inline]
824 fn from(x: u8) -> f16 {
825 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 let digits = ((f16::MANTISSA_DIGITS as f32 - 1.0) * 2f32.log10()).floor() as u32;
1391 assert_eq!(f16::DIGITS, digits);
1392 let digits32 = ((core::f32::MANTISSA_DIGITS as f32 - 1.0) * 2f32.log10()).floor() as u32;
1394 assert_eq!(core::f32::DIGITS, digits32);
1395
1396 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 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 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 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 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 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 let log10_2 = f16::from_f32(2f32.log10());
1475 let log2_e = f16::from_f32(core::f32::consts::LOG2_E);
1476 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 let log10_2 = f16::from_f64(2f64.log10());
1535 let log2_e = f16::from_f64(core::f64::consts::LOG2_E);
1536 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 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 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 let f = f16::from_f32(7.1);
1621 let diff = (f.to_f32() - 7.1f32).abs();
1622 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 let f = f16::from_f64(7.1);
1642 let diff = (f.to_f64() - 7.1f64).abs();
1643 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 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 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 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 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 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 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 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 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}