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};
22use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
23
24pub(crate) mod convert;
25
26#[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", rkyv(resolver = Bf16Resolver))]
43#[cfg_attr(feature = "bytemuck", derive(Zeroable, Pod))]
44#[cfg_attr(kani, derive(kani::Arbitrary))]
45#[derive(FromBytes, Immutable, IntoBytes, KnownLayout)]
46pub struct bf16(u16);
47
48impl bf16 {
49 #[inline]
51 #[must_use]
52 pub const fn from_bits(bits: u16) -> bf16 {
53 bf16(bits)
54 }
55
56 #[inline]
62 #[must_use]
63 pub fn from_f32(value: f32) -> bf16 {
64 Self::from_f32_const(value)
65 }
66
67 #[inline]
77 #[must_use]
78 pub const fn from_f32_const(value: f32) -> bf16 {
79 bf16(convert::f32_to_bf16(value))
80 }
81
82 #[inline]
89 #[must_use]
90 pub fn from_f64(value: f64) -> bf16 {
91 Self::from_f64_const(value)
92 }
93
94 #[inline]
105 #[must_use]
106 pub const fn from_f64_const(value: f64) -> bf16 {
107 bf16(convert::f64_to_bf16(value))
108 }
109
110 #[inline]
112 #[must_use]
113 pub const fn to_bits(self) -> u16 {
114 self.0
115 }
116
117 #[inline]
128 #[must_use]
129 pub const fn to_le_bytes(self) -> [u8; 2] {
130 self.0.to_le_bytes()
131 }
132
133 #[inline]
144 #[must_use]
145 pub const fn to_be_bytes(self) -> [u8; 2] {
146 self.0.to_be_bytes()
147 }
148
149 #[inline]
168 #[must_use]
169 pub const fn to_ne_bytes(self) -> [u8; 2] {
170 self.0.to_ne_bytes()
171 }
172
173 #[inline]
183 #[must_use]
184 pub const fn from_le_bytes(bytes: [u8; 2]) -> bf16 {
185 bf16::from_bits(u16::from_le_bytes(bytes))
186 }
187
188 #[inline]
198 #[must_use]
199 pub const fn from_be_bytes(bytes: [u8; 2]) -> bf16 {
200 bf16::from_bits(u16::from_be_bytes(bytes))
201 }
202
203 #[inline]
221 #[must_use]
222 pub const fn from_ne_bytes(bytes: [u8; 2]) -> bf16 {
223 bf16::from_bits(u16::from_ne_bytes(bytes))
224 }
225
226 #[inline]
230 #[must_use]
231 pub fn to_f32(self) -> f32 {
232 self.to_f32_const()
233 }
234
235 #[inline]
243 #[must_use]
244 pub const fn to_f32_const(self) -> f32 {
245 convert::bf16_to_f32(self.0)
246 }
247
248 #[inline]
252 #[must_use]
253 pub fn to_f64(self) -> f64 {
254 self.to_f64_const()
255 }
256
257 #[inline]
265 #[must_use]
266 pub const fn to_f64_const(self) -> f64 {
267 convert::bf16_to_f64(self.0)
268 }
269
270 #[inline]
284 #[must_use]
285 pub const fn is_nan(self) -> bool {
286 self.0 & 0x7FFFu16 > 0x7F80u16
287 }
288
289 #[inline]
308 #[must_use]
309 pub const fn is_infinite(self) -> bool {
310 self.0 & 0x7FFFu16 == 0x7F80u16
311 }
312
313 #[inline]
332 #[must_use]
333 pub const fn is_finite(self) -> bool {
334 self.0 & 0x7F80u16 != 0x7F80u16
335 }
336
337 #[inline]
359 #[must_use]
360 pub const fn is_normal(self) -> bool {
361 let exp = self.0 & 0x7F80u16;
362 exp != 0x7F80u16 && exp != 0
363 }
364
365 #[must_use]
383 pub const fn classify(self) -> FpCategory {
384 let exp = self.0 & 0x7F80u16;
385 let man = self.0 & 0x007Fu16;
386 match (exp, man) {
387 (0, 0) => FpCategory::Zero,
388 (0, _) => FpCategory::Subnormal,
389 (0x7F80u16, 0) => FpCategory::Infinite,
390 (0x7F80u16, _) => FpCategory::Nan,
391 _ => FpCategory::Normal,
392 }
393 }
394
395 #[must_use]
414 pub const fn signum(self) -> bf16 {
415 if self.is_nan() {
416 self
417 } else if self.0 & 0x8000u16 != 0 {
418 Self::NEG_ONE
419 } else {
420 Self::ONE
421 }
422 }
423
424 #[inline]
442 #[must_use]
443 pub const fn is_sign_positive(self) -> bool {
444 self.0 & 0x8000u16 == 0
445 }
446
447 #[inline]
465 #[must_use]
466 pub const fn is_sign_negative(self) -> bool {
467 self.0 & 0x8000u16 != 0
468 }
469
470 #[inline]
489 #[must_use]
490 pub const fn copysign(self, sign: bf16) -> bf16 {
491 bf16((sign.0 & 0x8000u16) | (self.0 & 0x7FFFu16))
492 }
493
494 #[inline]
508 #[must_use]
509 pub fn max(self, other: bf16) -> bf16 {
510 if self.is_nan() || other > self {
511 other
512 } else {
513 self
514 }
515 }
516
517 #[inline]
531 #[must_use]
532 pub fn min(self, other: bf16) -> bf16 {
533 if self.is_nan() || other < self {
534 other
535 } else {
536 self
537 }
538 }
539
540 #[inline]
560 #[must_use]
561 pub fn clamp(self, min: bf16, max: bf16) -> bf16 {
562 assert!(min <= max);
563 let mut x = self;
564 if x < min {
565 x = min;
566 }
567 if x > max {
568 x = max;
569 }
570 x
571 }
572
573 #[inline]
640 #[must_use]
641 pub fn total_cmp(&self, other: &Self) -> Ordering {
642 let mut left = self.to_bits() as i16;
643 let mut right = other.to_bits() as i16;
644 left ^= (((left >> 15) as u16) >> 1) as i16;
645 right ^= (((right >> 15) as u16) >> 1) as i16;
646 left.cmp(&right)
647 }
648
649 #[cfg(feature = "serde")]
671 pub fn serialize_as_f32<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
672 serializer.serialize_f32(self.to_f32())
673 }
674
675 #[cfg(all(feature = "serde", feature = "alloc"))]
697 pub fn serialize_as_string<S: serde::Serializer>(
698 &self,
699 serializer: S,
700 ) -> Result<S::Ok, S::Error> {
701 serializer.serialize_str(&self.to_string())
702 }
703
704 pub const DIGITS: u32 = 2;
706 pub const EPSILON: bf16 = bf16(0x3C00u16);
711 pub const INFINITY: bf16 = bf16(0x7F80u16);
713 pub const MANTISSA_DIGITS: u32 = 8;
715 pub const MAX: bf16 = bf16(0x7F7F);
717 pub const MAX_10_EXP: i32 = 38;
719 pub const MAX_EXP: i32 = 128;
721 pub const MIN: bf16 = bf16(0xFF7F);
723 pub const MIN_10_EXP: i32 = -37;
725 pub const MIN_EXP: i32 = -125;
727 pub const MIN_POSITIVE: bf16 = bf16(0x0080u16);
729 pub const NAN: bf16 = bf16(0x7FC0u16);
731 pub const NEG_INFINITY: bf16 = bf16(0xFF80u16);
733 pub const RADIX: u32 = 2;
735
736 pub const MIN_POSITIVE_SUBNORMAL: bf16 = bf16(0x0001u16);
738 pub const MAX_SUBNORMAL: bf16 = bf16(0x007Fu16);
740
741 pub const ONE: bf16 = bf16(0x3F80u16);
743 pub const ZERO: bf16 = bf16(0x0000u16);
745 pub const NEG_ZERO: bf16 = bf16(0x8000u16);
747 pub const NEG_ONE: bf16 = bf16(0xBF80u16);
749
750 pub const E: bf16 = bf16(0x402Eu16);
752 pub const PI: bf16 = bf16(0x4049u16);
754 pub const FRAC_1_PI: bf16 = bf16(0x3EA3u16);
756 pub const FRAC_1_SQRT_2: bf16 = bf16(0x3F35u16);
758 pub const FRAC_2_PI: bf16 = bf16(0x3F23u16);
760 pub const FRAC_2_SQRT_PI: bf16 = bf16(0x3F90u16);
762 pub const FRAC_PI_2: bf16 = bf16(0x3FC9u16);
764 pub const FRAC_PI_3: bf16 = bf16(0x3F86u16);
766 pub const FRAC_PI_4: bf16 = bf16(0x3F49u16);
768 pub const FRAC_PI_6: bf16 = bf16(0x3F06u16);
770 pub const FRAC_PI_8: bf16 = bf16(0x3EC9u16);
772 pub const LN_10: bf16 = bf16(0x4013u16);
774 pub const LN_2: bf16 = bf16(0x3F31u16);
776 pub const LOG10_E: bf16 = bf16(0x3EDEu16);
778 pub const LOG10_2: bf16 = bf16(0x3E9Au16);
780 pub const LOG2_E: bf16 = bf16(0x3FB9u16);
782 pub const LOG2_10: bf16 = bf16(0x4055u16);
784 pub const SQRT_2: bf16 = bf16(0x3FB5u16);
786}
787
788impl From<bf16> for f32 {
789 #[inline]
790 fn from(x: bf16) -> f32 {
791 x.to_f32()
792 }
793}
794
795impl From<bf16> for f64 {
796 #[inline]
797 fn from(x: bf16) -> f64 {
798 x.to_f64()
799 }
800}
801
802impl From<i8> for bf16 {
803 #[inline]
804 fn from(x: i8) -> bf16 {
805 bf16::from_f32(f32::from(x))
807 }
808}
809
810impl From<u8> for bf16 {
811 #[inline]
812 fn from(x: u8) -> bf16 {
813 bf16::from_f32(f32::from(x))
815 }
816}
817
818impl PartialEq for bf16 {
819 fn eq(&self, other: &bf16) -> bool {
820 if self.is_nan() || other.is_nan() {
821 false
822 } else {
823 (self.0 == other.0) || ((self.0 | other.0) & 0x7FFFu16 == 0)
824 }
825 }
826}
827
828impl PartialOrd for bf16 {
829 fn partial_cmp(&self, other: &bf16) -> Option<Ordering> {
830 if self.is_nan() || other.is_nan() {
831 None
832 } else {
833 let neg = self.0 & 0x8000u16 != 0;
834 let other_neg = other.0 & 0x8000u16 != 0;
835 match (neg, other_neg) {
836 (false, false) => Some(self.0.cmp(&other.0)),
837 (false, true) => {
838 if (self.0 | other.0) & 0x7FFFu16 == 0 {
839 Some(Ordering::Equal)
840 } else {
841 Some(Ordering::Greater)
842 }
843 }
844 (true, false) => {
845 if (self.0 | other.0) & 0x7FFFu16 == 0 {
846 Some(Ordering::Equal)
847 } else {
848 Some(Ordering::Less)
849 }
850 }
851 (true, true) => Some(other.0.cmp(&self.0)),
852 }
853 }
854 }
855
856 fn lt(&self, other: &bf16) -> bool {
857 if self.is_nan() || other.is_nan() {
858 false
859 } else {
860 let neg = self.0 & 0x8000u16 != 0;
861 let other_neg = other.0 & 0x8000u16 != 0;
862 match (neg, other_neg) {
863 (false, false) => self.0 < other.0,
864 (false, true) => false,
865 (true, false) => (self.0 | other.0) & 0x7FFFu16 != 0,
866 (true, true) => self.0 > other.0,
867 }
868 }
869 }
870
871 fn le(&self, other: &bf16) -> bool {
872 if self.is_nan() || other.is_nan() {
873 false
874 } else {
875 let neg = self.0 & 0x8000u16 != 0;
876 let other_neg = other.0 & 0x8000u16 != 0;
877 match (neg, other_neg) {
878 (false, false) => self.0 <= other.0,
879 (false, true) => (self.0 | other.0) & 0x7FFFu16 == 0,
880 (true, false) => true,
881 (true, true) => self.0 >= other.0,
882 }
883 }
884 }
885
886 fn gt(&self, other: &bf16) -> bool {
887 if self.is_nan() || other.is_nan() {
888 false
889 } else {
890 let neg = self.0 & 0x8000u16 != 0;
891 let other_neg = other.0 & 0x8000u16 != 0;
892 match (neg, other_neg) {
893 (false, false) => self.0 > other.0,
894 (false, true) => (self.0 | other.0) & 0x7FFFu16 != 0,
895 (true, false) => false,
896 (true, true) => self.0 < other.0,
897 }
898 }
899 }
900
901 fn ge(&self, other: &bf16) -> bool {
902 if self.is_nan() || other.is_nan() {
903 false
904 } else {
905 let neg = self.0 & 0x8000u16 != 0;
906 let other_neg = other.0 & 0x8000u16 != 0;
907 match (neg, other_neg) {
908 (false, false) => self.0 >= other.0,
909 (false, true) => true,
910 (true, false) => (self.0 | other.0) & 0x7FFFu16 == 0,
911 (true, true) => self.0 <= other.0,
912 }
913 }
914 }
915}
916
917#[cfg(not(target_arch = "spirv"))]
918impl FromStr for bf16 {
919 type Err = ParseFloatError;
920 fn from_str(src: &str) -> Result<bf16, ParseFloatError> {
921 f32::from_str(src).map(bf16::from_f32)
922 }
923}
924
925#[cfg(not(target_arch = "spirv"))]
926impl Debug for bf16 {
927 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
928 Debug::fmt(&self.to_f32(), f)
929 }
930}
931
932#[cfg(not(target_arch = "spirv"))]
933impl Display for bf16 {
934 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
935 Display::fmt(&self.to_f32(), f)
936 }
937}
938
939#[cfg(not(target_arch = "spirv"))]
940impl LowerExp for bf16 {
941 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
942 write!(f, "{:e}", self.to_f32())
943 }
944}
945
946#[cfg(not(target_arch = "spirv"))]
947impl UpperExp for bf16 {
948 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
949 write!(f, "{:E}", self.to_f32())
950 }
951}
952
953#[cfg(not(target_arch = "spirv"))]
954impl Binary for bf16 {
955 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
956 write!(f, "{:b}", self.0)
957 }
958}
959
960#[cfg(not(target_arch = "spirv"))]
961impl Octal for bf16 {
962 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
963 write!(f, "{:o}", self.0)
964 }
965}
966
967#[cfg(not(target_arch = "spirv"))]
968impl LowerHex for bf16 {
969 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
970 write!(f, "{:x}", self.0)
971 }
972}
973
974#[cfg(not(target_arch = "spirv"))]
975impl UpperHex for bf16 {
976 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
977 write!(f, "{:X}", self.0)
978 }
979}
980
981impl Neg for bf16 {
982 type Output = Self;
983
984 fn neg(self) -> Self::Output {
985 Self(self.0 ^ 0x8000)
986 }
987}
988
989impl Neg for &bf16 {
990 type Output = <bf16 as Neg>::Output;
991
992 #[inline]
993 fn neg(self) -> Self::Output {
994 Neg::neg(*self)
995 }
996}
997
998impl Add for bf16 {
999 type Output = Self;
1000
1001 fn add(self, rhs: Self) -> Self::Output {
1002 Self::from_f32(Self::to_f32(self) + Self::to_f32(rhs))
1003 }
1004}
1005
1006impl Add<&bf16> for bf16 {
1007 type Output = <bf16 as Add<bf16>>::Output;
1008
1009 #[inline]
1010 fn add(self, rhs: &bf16) -> Self::Output {
1011 self.add(*rhs)
1012 }
1013}
1014
1015impl Add<&bf16> for &bf16 {
1016 type Output = <bf16 as Add<bf16>>::Output;
1017
1018 #[inline]
1019 fn add(self, rhs: &bf16) -> Self::Output {
1020 (*self).add(*rhs)
1021 }
1022}
1023
1024impl Add<bf16> for &bf16 {
1025 type Output = <bf16 as Add<bf16>>::Output;
1026
1027 #[inline]
1028 fn add(self, rhs: bf16) -> Self::Output {
1029 (*self).add(rhs)
1030 }
1031}
1032
1033impl AddAssign for bf16 {
1034 #[inline]
1035 fn add_assign(&mut self, rhs: Self) {
1036 *self = (*self).add(rhs);
1037 }
1038}
1039
1040impl AddAssign<&bf16> for bf16 {
1041 #[inline]
1042 fn add_assign(&mut self, rhs: &bf16) {
1043 *self = (*self).add(rhs);
1044 }
1045}
1046
1047impl Sub for bf16 {
1048 type Output = Self;
1049
1050 fn sub(self, rhs: Self) -> Self::Output {
1051 Self::from_f32(Self::to_f32(self) - Self::to_f32(rhs))
1052 }
1053}
1054
1055impl Sub<&bf16> for bf16 {
1056 type Output = <bf16 as Sub<bf16>>::Output;
1057
1058 #[inline]
1059 fn sub(self, rhs: &bf16) -> Self::Output {
1060 self.sub(*rhs)
1061 }
1062}
1063
1064impl Sub<&bf16> for &bf16 {
1065 type Output = <bf16 as Sub<bf16>>::Output;
1066
1067 #[inline]
1068 fn sub(self, rhs: &bf16) -> Self::Output {
1069 (*self).sub(*rhs)
1070 }
1071}
1072
1073impl Sub<bf16> for &bf16 {
1074 type Output = <bf16 as Sub<bf16>>::Output;
1075
1076 #[inline]
1077 fn sub(self, rhs: bf16) -> Self::Output {
1078 (*self).sub(rhs)
1079 }
1080}
1081
1082impl SubAssign for bf16 {
1083 #[inline]
1084 fn sub_assign(&mut self, rhs: Self) {
1085 *self = (*self).sub(rhs);
1086 }
1087}
1088
1089impl SubAssign<&bf16> for bf16 {
1090 #[inline]
1091 fn sub_assign(&mut self, rhs: &bf16) {
1092 *self = (*self).sub(rhs);
1093 }
1094}
1095
1096impl Mul for bf16 {
1097 type Output = Self;
1098
1099 fn mul(self, rhs: Self) -> Self::Output {
1100 Self::from_f32(Self::to_f32(self) * Self::to_f32(rhs))
1101 }
1102}
1103
1104impl Mul<&bf16> for bf16 {
1105 type Output = <bf16 as Mul<bf16>>::Output;
1106
1107 #[inline]
1108 fn mul(self, rhs: &bf16) -> Self::Output {
1109 self.mul(*rhs)
1110 }
1111}
1112
1113impl Mul<&bf16> for &bf16 {
1114 type Output = <bf16 as Mul<bf16>>::Output;
1115
1116 #[inline]
1117 fn mul(self, rhs: &bf16) -> Self::Output {
1118 (*self).mul(*rhs)
1119 }
1120}
1121
1122impl Mul<bf16> for &bf16 {
1123 type Output = <bf16 as Mul<bf16>>::Output;
1124
1125 #[inline]
1126 fn mul(self, rhs: bf16) -> Self::Output {
1127 (*self).mul(rhs)
1128 }
1129}
1130
1131impl MulAssign for bf16 {
1132 #[inline]
1133 fn mul_assign(&mut self, rhs: Self) {
1134 *self = (*self).mul(rhs);
1135 }
1136}
1137
1138impl MulAssign<&bf16> for bf16 {
1139 #[inline]
1140 fn mul_assign(&mut self, rhs: &bf16) {
1141 *self = (*self).mul(rhs);
1142 }
1143}
1144
1145impl Div for bf16 {
1146 type Output = Self;
1147
1148 fn div(self, rhs: Self) -> Self::Output {
1149 Self::from_f32(Self::to_f32(self) / Self::to_f32(rhs))
1150 }
1151}
1152
1153impl Div<&bf16> for bf16 {
1154 type Output = <bf16 as Div<bf16>>::Output;
1155
1156 #[inline]
1157 fn div(self, rhs: &bf16) -> Self::Output {
1158 self.div(*rhs)
1159 }
1160}
1161
1162impl Div<&bf16> for &bf16 {
1163 type Output = <bf16 as Div<bf16>>::Output;
1164
1165 #[inline]
1166 fn div(self, rhs: &bf16) -> Self::Output {
1167 (*self).div(*rhs)
1168 }
1169}
1170
1171impl Div<bf16> for &bf16 {
1172 type Output = <bf16 as Div<bf16>>::Output;
1173
1174 #[inline]
1175 fn div(self, rhs: bf16) -> Self::Output {
1176 (*self).div(rhs)
1177 }
1178}
1179
1180impl DivAssign for bf16 {
1181 #[inline]
1182 fn div_assign(&mut self, rhs: Self) {
1183 *self = (*self).div(rhs);
1184 }
1185}
1186
1187impl DivAssign<&bf16> for bf16 {
1188 #[inline]
1189 fn div_assign(&mut self, rhs: &bf16) {
1190 *self = (*self).div(rhs);
1191 }
1192}
1193
1194impl Rem for bf16 {
1195 type Output = Self;
1196
1197 fn rem(self, rhs: Self) -> Self::Output {
1198 Self::from_f32(Self::to_f32(self) % Self::to_f32(rhs))
1199 }
1200}
1201
1202impl Rem<&bf16> for bf16 {
1203 type Output = <bf16 as Rem<bf16>>::Output;
1204
1205 #[inline]
1206 fn rem(self, rhs: &bf16) -> Self::Output {
1207 self.rem(*rhs)
1208 }
1209}
1210
1211impl Rem<&bf16> for &bf16 {
1212 type Output = <bf16 as Rem<bf16>>::Output;
1213
1214 #[inline]
1215 fn rem(self, rhs: &bf16) -> Self::Output {
1216 (*self).rem(*rhs)
1217 }
1218}
1219
1220impl Rem<bf16> for &bf16 {
1221 type Output = <bf16 as Rem<bf16>>::Output;
1222
1223 #[inline]
1224 fn rem(self, rhs: bf16) -> Self::Output {
1225 (*self).rem(rhs)
1226 }
1227}
1228
1229impl RemAssign for bf16 {
1230 #[inline]
1231 fn rem_assign(&mut self, rhs: Self) {
1232 *self = (*self).rem(rhs);
1233 }
1234}
1235
1236impl RemAssign<&bf16> for bf16 {
1237 #[inline]
1238 fn rem_assign(&mut self, rhs: &bf16) {
1239 *self = (*self).rem(rhs);
1240 }
1241}
1242
1243impl Product for bf16 {
1244 #[inline]
1245 fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
1246 bf16::from_f32(iter.map(|f| f.to_f32()).product())
1247 }
1248}
1249
1250impl<'a> Product<&'a bf16> for bf16 {
1251 #[inline]
1252 fn product<I: Iterator<Item = &'a bf16>>(iter: I) -> Self {
1253 bf16::from_f32(iter.map(|f| f.to_f32()).product())
1254 }
1255}
1256
1257impl Sum for bf16 {
1258 #[inline]
1259 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1260 bf16::from_f32(iter.map(|f| f.to_f32()).sum())
1261 }
1262}
1263
1264impl<'a> Sum<&'a bf16> for bf16 {
1265 #[inline]
1266 fn sum<I: Iterator<Item = &'a bf16>>(iter: I) -> Self {
1267 bf16::from_f32(iter.map(|f| f.to_f32()).sum())
1268 }
1269}
1270
1271#[cfg(feature = "serde")]
1272struct Visitor;
1273
1274#[cfg(feature = "serde")]
1275impl<'de> Deserialize<'de> for bf16 {
1276 fn deserialize<D>(deserializer: D) -> Result<bf16, D::Error>
1277 where
1278 D: serde::de::Deserializer<'de>,
1279 {
1280 deserializer.deserialize_newtype_struct("bf16", Visitor)
1281 }
1282}
1283
1284#[cfg(feature = "serde")]
1285impl<'de> serde::de::Visitor<'de> for Visitor {
1286 type Value = bf16;
1287
1288 fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
1289 write!(formatter, "tuple struct bf16")
1290 }
1291
1292 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1293 where
1294 D: serde::Deserializer<'de>,
1295 {
1296 Ok(bf16(<u16 as Deserialize>::deserialize(deserializer)?))
1297 }
1298
1299 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1300 where
1301 E: serde::de::Error,
1302 {
1303 v.parse().map_err(|_| {
1304 serde::de::Error::invalid_value(serde::de::Unexpected::Str(v), &"a float string")
1305 })
1306 }
1307
1308 fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
1309 where
1310 E: serde::de::Error,
1311 {
1312 Ok(bf16::from_f32(v))
1313 }
1314
1315 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
1316 where
1317 E: serde::de::Error,
1318 {
1319 Ok(bf16::from_f64(v))
1320 }
1321}
1322
1323#[allow(
1324 clippy::cognitive_complexity,
1325 clippy::float_cmp,
1326 clippy::neg_cmp_op_on_partial_ord
1327)]
1328#[cfg(test)]
1329mod test {
1330 use super::*;
1331 #[allow(unused_imports)]
1332 use core::cmp::Ordering;
1333 #[cfg(feature = "num-traits")]
1334 use num_traits::{AsPrimitive, FromBytes, FromPrimitive, ToBytes, ToPrimitive};
1335 use quickcheck_macros::quickcheck;
1336
1337 #[cfg(feature = "num-traits")]
1338 #[test]
1339 fn as_primitive() {
1340 let two = bf16::from_f32(2.0);
1341 assert_eq!(<i32 as AsPrimitive<bf16>>::as_(2), two);
1342 assert_eq!(<bf16 as AsPrimitive<i32>>::as_(two), 2);
1343
1344 assert_eq!(<f32 as AsPrimitive<bf16>>::as_(2.0), two);
1345 assert_eq!(<bf16 as AsPrimitive<f32>>::as_(two), 2.0);
1346
1347 assert_eq!(<f64 as AsPrimitive<bf16>>::as_(2.0), two);
1348 assert_eq!(<bf16 as AsPrimitive<f64>>::as_(two), 2.0);
1349 }
1350
1351 #[cfg(feature = "num-traits")]
1352 #[test]
1353 fn to_primitive() {
1354 let two = bf16::from_f32(2.0);
1355 assert_eq!(ToPrimitive::to_i32(&two).unwrap(), 2i32);
1356 assert_eq!(ToPrimitive::to_f32(&two).unwrap(), 2.0f32);
1357 assert_eq!(ToPrimitive::to_f64(&two).unwrap(), 2.0f64);
1358 }
1359
1360 #[cfg(feature = "num-traits")]
1361 #[test]
1362 fn from_primitive() {
1363 let two = bf16::from_f32(2.0);
1364 assert_eq!(<bf16 as FromPrimitive>::from_i32(2).unwrap(), two);
1365 assert_eq!(<bf16 as FromPrimitive>::from_f32(2.0).unwrap(), two);
1366 assert_eq!(<bf16 as FromPrimitive>::from_f64(2.0).unwrap(), two);
1367 }
1368
1369 #[cfg(feature = "num-traits")]
1370 #[test]
1371 fn to_and_from_bytes() {
1372 let two = bf16::from_f32(2.0);
1373 assert_eq!(<bf16 as ToBytes>::to_le_bytes(&two), [0, 64]);
1374 assert_eq!(<bf16 as FromBytes>::from_le_bytes(&[0, 64]), two);
1375 assert_eq!(<bf16 as ToBytes>::to_be_bytes(&two), [64, 0]);
1376 assert_eq!(<bf16 as FromBytes>::from_be_bytes(&[64, 0]), two);
1377 }
1378
1379 #[test]
1380 fn test_bf16_consts_from_f32() {
1381 let one = bf16::from_f32(1.0);
1382 let zero = bf16::from_f32(0.0);
1383 let neg_zero = bf16::from_f32(-0.0);
1384 let neg_one = bf16::from_f32(-1.0);
1385 let inf = bf16::from_f32(core::f32::INFINITY);
1386 let neg_inf = bf16::from_f32(core::f32::NEG_INFINITY);
1387 let nan = bf16::from_f32(core::f32::NAN);
1388
1389 assert_eq!(bf16::ONE, one);
1390 assert_eq!(bf16::ZERO, zero);
1391 assert!(zero.is_sign_positive());
1392 assert_eq!(bf16::NEG_ZERO, neg_zero);
1393 assert!(neg_zero.is_sign_negative());
1394 assert_eq!(bf16::NEG_ONE, neg_one);
1395 assert!(neg_one.is_sign_negative());
1396 assert_eq!(bf16::INFINITY, inf);
1397 assert_eq!(bf16::NEG_INFINITY, neg_inf);
1398 assert!(nan.is_nan());
1399 assert!(bf16::NAN.is_nan());
1400
1401 let e = bf16::from_f32(core::f32::consts::E);
1402 let pi = bf16::from_f32(core::f32::consts::PI);
1403 let frac_1_pi = bf16::from_f32(core::f32::consts::FRAC_1_PI);
1404 let frac_1_sqrt_2 = bf16::from_f32(core::f32::consts::FRAC_1_SQRT_2);
1405 let frac_2_pi = bf16::from_f32(core::f32::consts::FRAC_2_PI);
1406 let frac_2_sqrt_pi = bf16::from_f32(core::f32::consts::FRAC_2_SQRT_PI);
1407 let frac_pi_2 = bf16::from_f32(core::f32::consts::FRAC_PI_2);
1408 let frac_pi_3 = bf16::from_f32(core::f32::consts::FRAC_PI_3);
1409 let frac_pi_4 = bf16::from_f32(core::f32::consts::FRAC_PI_4);
1410 let frac_pi_6 = bf16::from_f32(core::f32::consts::FRAC_PI_6);
1411 let frac_pi_8 = bf16::from_f32(core::f32::consts::FRAC_PI_8);
1412 let ln_10 = bf16::from_f32(core::f32::consts::LN_10);
1413 let ln_2 = bf16::from_f32(core::f32::consts::LN_2);
1414 let log10_e = bf16::from_f32(core::f32::consts::LOG10_E);
1415 let log10_2 = bf16::from_f32(2f32.log10());
1417 let log2_e = bf16::from_f32(core::f32::consts::LOG2_E);
1418 let log2_10 = bf16::from_f32(10f32.log2());
1420 let sqrt_2 = bf16::from_f32(core::f32::consts::SQRT_2);
1421
1422 assert_eq!(bf16::E, e);
1423 assert_eq!(bf16::PI, pi);
1424 assert_eq!(bf16::FRAC_1_PI, frac_1_pi);
1425 assert_eq!(bf16::FRAC_1_SQRT_2, frac_1_sqrt_2);
1426 assert_eq!(bf16::FRAC_2_PI, frac_2_pi);
1427 assert_eq!(bf16::FRAC_2_SQRT_PI, frac_2_sqrt_pi);
1428 assert_eq!(bf16::FRAC_PI_2, frac_pi_2);
1429 assert_eq!(bf16::FRAC_PI_3, frac_pi_3);
1430 assert_eq!(bf16::FRAC_PI_4, frac_pi_4);
1431 assert_eq!(bf16::FRAC_PI_6, frac_pi_6);
1432 assert_eq!(bf16::FRAC_PI_8, frac_pi_8);
1433 assert_eq!(bf16::LN_10, ln_10);
1434 assert_eq!(bf16::LN_2, ln_2);
1435 assert_eq!(bf16::LOG10_E, log10_e);
1436 assert_eq!(bf16::LOG10_2, log10_2);
1437 assert_eq!(bf16::LOG2_E, log2_e);
1438 assert_eq!(bf16::LOG2_10, log2_10);
1439 assert_eq!(bf16::SQRT_2, sqrt_2);
1440 }
1441
1442 #[test]
1443 fn test_bf16_consts_from_f64() {
1444 let one = bf16::from_f64(1.0);
1445 let zero = bf16::from_f64(0.0);
1446 let neg_zero = bf16::from_f64(-0.0);
1447 let inf = bf16::from_f64(core::f64::INFINITY);
1448 let neg_inf = bf16::from_f64(core::f64::NEG_INFINITY);
1449 let nan = bf16::from_f64(core::f64::NAN);
1450
1451 assert_eq!(bf16::ONE, one);
1452 assert_eq!(bf16::ZERO, zero);
1453 assert_eq!(bf16::NEG_ZERO, neg_zero);
1454 assert_eq!(bf16::INFINITY, inf);
1455 assert_eq!(bf16::NEG_INFINITY, neg_inf);
1456 assert!(nan.is_nan());
1457 assert!(bf16::NAN.is_nan());
1458
1459 let e = bf16::from_f64(core::f64::consts::E);
1460 let pi = bf16::from_f64(core::f64::consts::PI);
1461 let frac_1_pi = bf16::from_f64(core::f64::consts::FRAC_1_PI);
1462 let frac_1_sqrt_2 = bf16::from_f64(core::f64::consts::FRAC_1_SQRT_2);
1463 let frac_2_pi = bf16::from_f64(core::f64::consts::FRAC_2_PI);
1464 let frac_2_sqrt_pi = bf16::from_f64(core::f64::consts::FRAC_2_SQRT_PI);
1465 let frac_pi_2 = bf16::from_f64(core::f64::consts::FRAC_PI_2);
1466 let frac_pi_3 = bf16::from_f64(core::f64::consts::FRAC_PI_3);
1467 let frac_pi_4 = bf16::from_f64(core::f64::consts::FRAC_PI_4);
1468 let frac_pi_6 = bf16::from_f64(core::f64::consts::FRAC_PI_6);
1469 let frac_pi_8 = bf16::from_f64(core::f64::consts::FRAC_PI_8);
1470 let ln_10 = bf16::from_f64(core::f64::consts::LN_10);
1471 let ln_2 = bf16::from_f64(core::f64::consts::LN_2);
1472 let log10_e = bf16::from_f64(core::f64::consts::LOG10_E);
1473 let log10_2 = bf16::from_f64(2f64.log10());
1475 let log2_e = bf16::from_f64(core::f64::consts::LOG2_E);
1476 let log2_10 = bf16::from_f64(10f64.log2());
1478 let sqrt_2 = bf16::from_f64(core::f64::consts::SQRT_2);
1479
1480 assert_eq!(bf16::E, e);
1481 assert_eq!(bf16::PI, pi);
1482 assert_eq!(bf16::FRAC_1_PI, frac_1_pi);
1483 assert_eq!(bf16::FRAC_1_SQRT_2, frac_1_sqrt_2);
1484 assert_eq!(bf16::FRAC_2_PI, frac_2_pi);
1485 assert_eq!(bf16::FRAC_2_SQRT_PI, frac_2_sqrt_pi);
1486 assert_eq!(bf16::FRAC_PI_2, frac_pi_2);
1487 assert_eq!(bf16::FRAC_PI_3, frac_pi_3);
1488 assert_eq!(bf16::FRAC_PI_4, frac_pi_4);
1489 assert_eq!(bf16::FRAC_PI_6, frac_pi_6);
1490 assert_eq!(bf16::FRAC_PI_8, frac_pi_8);
1491 assert_eq!(bf16::LN_10, ln_10);
1492 assert_eq!(bf16::LN_2, ln_2);
1493 assert_eq!(bf16::LOG10_E, log10_e);
1494 assert_eq!(bf16::LOG10_2, log10_2);
1495 assert_eq!(bf16::LOG2_E, log2_e);
1496 assert_eq!(bf16::LOG2_10, log2_10);
1497 assert_eq!(bf16::SQRT_2, sqrt_2);
1498 }
1499
1500 #[test]
1501 fn test_nan_conversion_to_smaller() {
1502 let nan64 = f64::from_bits(0x7FF0_0000_0000_0001u64);
1503 let neg_nan64 = f64::from_bits(0xFFF0_0000_0000_0001u64);
1504 let nan32 = f32::from_bits(0x7F80_0001u32);
1505 let neg_nan32 = f32::from_bits(0xFF80_0001u32);
1506 let nan32_from_64 = nan64 as f32;
1507 let neg_nan32_from_64 = neg_nan64 as f32;
1508 let nan16_from_64 = bf16::from_f64(nan64);
1509 let neg_nan16_from_64 = bf16::from_f64(neg_nan64);
1510 let nan16_from_32 = bf16::from_f32(nan32);
1511 let neg_nan16_from_32 = bf16::from_f32(neg_nan32);
1512
1513 assert!(nan64.is_nan() && nan64.is_sign_positive());
1514 assert!(neg_nan64.is_nan() && neg_nan64.is_sign_negative());
1515 assert!(nan32.is_nan() && nan32.is_sign_positive());
1516 assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative());
1517
1518 assert!(neg_nan32_from_64.is_nan());
1520 assert!(nan32_from_64.is_nan());
1521 assert!(nan16_from_64.is_nan());
1522 assert!(neg_nan16_from_64.is_nan());
1523 assert!(nan16_from_32.is_nan());
1524 assert!(neg_nan16_from_32.is_nan());
1525 }
1526
1527 #[test]
1528 fn test_nan_conversion_to_larger() {
1529 let nan16 = bf16::from_bits(0x7F81u16);
1530 let neg_nan16 = bf16::from_bits(0xFF81u16);
1531 let nan32 = f32::from_bits(0x7F80_0001u32);
1532 let neg_nan32 = f32::from_bits(0xFF80_0001u32);
1533 let nan32_from_16 = f32::from(nan16);
1534 let neg_nan32_from_16 = f32::from(neg_nan16);
1535 let nan64_from_16 = f64::from(nan16);
1536 let neg_nan64_from_16 = f64::from(neg_nan16);
1537 let nan64_from_32 = f64::from(nan32);
1538 let neg_nan64_from_32 = f64::from(neg_nan32);
1539
1540 assert!(nan16.is_nan() && nan16.is_sign_positive());
1541 assert!(neg_nan16.is_nan() && neg_nan16.is_sign_negative());
1542 assert!(nan32.is_nan() && nan32.is_sign_positive());
1543 assert!(neg_nan32.is_nan() && neg_nan32.is_sign_negative());
1544
1545 assert!(nan32_from_16.is_nan());
1547 assert!(neg_nan32_from_16.is_nan());
1548 assert!(nan64_from_16.is_nan());
1549 assert!(neg_nan64_from_16.is_nan());
1550 assert!(nan64_from_32.is_nan());
1551 assert!(neg_nan64_from_32.is_nan());
1552 }
1553
1554 #[test]
1555 fn test_bf16_to_f32() {
1556 let f = bf16::from_f32(7.0);
1557 assert_eq!(f.to_f32(), 7.0f32);
1558
1559 let f = bf16::from_f32(7.1);
1561 let diff = (f.to_f32() - 7.1f32).abs();
1562 assert!(diff <= 4.0 * bf16::EPSILON.to_f32());
1564
1565 let tiny32 = f32::from_bits(0x0001_0000u32);
1566 assert_eq!(bf16::from_bits(0x0001).to_f32(), tiny32);
1567 assert_eq!(bf16::from_bits(0x0005).to_f32(), 5.0 * tiny32);
1568
1569 assert_eq!(bf16::from_bits(0x0001), bf16::from_f32(tiny32));
1570 assert_eq!(bf16::from_bits(0x0005), bf16::from_f32(5.0 * tiny32));
1571 }
1572
1573 #[test]
1574 #[cfg_attr(miri, ignore)]
1575 fn test_bf16_to_f64() {
1576 let f = bf16::from_f64(7.0);
1577 assert_eq!(f.to_f64(), 7.0f64);
1578
1579 let f = bf16::from_f64(7.1);
1581 let diff = (f.to_f64() - 7.1f64).abs();
1582 assert!(diff <= 4.0 * bf16::EPSILON.to_f64());
1584
1585 let tiny64 = 2.0f64.powi(-133);
1586 assert_eq!(bf16::from_bits(0x0001).to_f64(), tiny64);
1587 assert_eq!(bf16::from_bits(0x0005).to_f64(), 5.0 * tiny64);
1588
1589 assert_eq!(bf16::from_bits(0x0001), bf16::from_f64(tiny64));
1590 assert_eq!(bf16::from_bits(0x0005), bf16::from_f64(5.0 * tiny64));
1591 }
1592
1593 #[test]
1594 fn test_comparisons() {
1595 let zero = bf16::from_f64(0.0);
1596 let one = bf16::from_f64(1.0);
1597 let neg_zero = bf16::from_f64(-0.0);
1598 let neg_one = bf16::from_f64(-1.0);
1599
1600 assert_eq!(zero.partial_cmp(&neg_zero), Some(Ordering::Equal));
1601 assert_eq!(neg_zero.partial_cmp(&zero), Some(Ordering::Equal));
1602 assert!(zero == neg_zero);
1603 assert!(neg_zero == zero);
1604 assert!(!(zero != neg_zero));
1605 assert!(!(neg_zero != zero));
1606 assert!(!(zero < neg_zero));
1607 assert!(!(neg_zero < zero));
1608 assert!(zero <= neg_zero);
1609 assert!(neg_zero <= zero);
1610 assert!(!(zero > neg_zero));
1611 assert!(!(neg_zero > zero));
1612 assert!(zero >= neg_zero);
1613 assert!(neg_zero >= zero);
1614
1615 assert_eq!(one.partial_cmp(&neg_zero), Some(Ordering::Greater));
1616 assert_eq!(neg_zero.partial_cmp(&one), Some(Ordering::Less));
1617 assert!(!(one == neg_zero));
1618 assert!(!(neg_zero == one));
1619 assert!(one != neg_zero);
1620 assert!(neg_zero != one);
1621 assert!(!(one < neg_zero));
1622 assert!(neg_zero < one);
1623 assert!(!(one <= neg_zero));
1624 assert!(neg_zero <= one);
1625 assert!(one > neg_zero);
1626 assert!(!(neg_zero > one));
1627 assert!(one >= neg_zero);
1628 assert!(!(neg_zero >= one));
1629
1630 assert_eq!(one.partial_cmp(&neg_one), Some(Ordering::Greater));
1631 assert_eq!(neg_one.partial_cmp(&one), Some(Ordering::Less));
1632 assert!(!(one == neg_one));
1633 assert!(!(neg_one == one));
1634 assert!(one != neg_one);
1635 assert!(neg_one != one);
1636 assert!(!(one < neg_one));
1637 assert!(neg_one < one);
1638 assert!(!(one <= neg_one));
1639 assert!(neg_one <= one);
1640 assert!(one > neg_one);
1641 assert!(!(neg_one > one));
1642 assert!(one >= neg_one);
1643 assert!(!(neg_one >= one));
1644 }
1645
1646 #[test]
1647 #[allow(clippy::erasing_op, clippy::identity_op)]
1648 #[cfg_attr(miri, ignore)]
1649 fn round_to_even_f32() {
1650 let min_sub = bf16::from_bits(1);
1652 let min_sub_f = (-133f32).exp2();
1653 assert_eq!(bf16::from_f32(min_sub_f).to_bits(), min_sub.to_bits());
1654 assert_eq!(f32::from(min_sub).to_bits(), min_sub_f.to_bits());
1655
1656 assert_eq!(
1660 bf16::from_f32(min_sub_f * 0.49).to_bits(),
1661 min_sub.to_bits() * 0
1662 );
1663 assert_eq!(
1664 bf16::from_f32(min_sub_f * 0.50).to_bits(),
1665 min_sub.to_bits() * 0
1666 );
1667 assert_eq!(
1668 bf16::from_f32(min_sub_f * 0.51).to_bits(),
1669 min_sub.to_bits() * 1
1670 );
1671
1672 assert_eq!(
1676 bf16::from_f32(min_sub_f * 1.49).to_bits(),
1677 min_sub.to_bits() * 1
1678 );
1679 assert_eq!(
1680 bf16::from_f32(min_sub_f * 1.50).to_bits(),
1681 min_sub.to_bits() * 2
1682 );
1683 assert_eq!(
1684 bf16::from_f32(min_sub_f * 1.51).to_bits(),
1685 min_sub.to_bits() * 2
1686 );
1687
1688 assert_eq!(
1692 bf16::from_f32(min_sub_f * 2.49).to_bits(),
1693 min_sub.to_bits() * 2
1694 );
1695 assert_eq!(
1696 bf16::from_f32(min_sub_f * 2.50).to_bits(),
1697 min_sub.to_bits() * 2
1698 );
1699 assert_eq!(
1700 bf16::from_f32(min_sub_f * 2.51).to_bits(),
1701 min_sub.to_bits() * 3
1702 );
1703
1704 assert_eq!(
1705 bf16::from_f32(250.49f32).to_bits(),
1706 bf16::from_f32(250.0).to_bits()
1707 );
1708 assert_eq!(
1709 bf16::from_f32(250.50f32).to_bits(),
1710 bf16::from_f32(250.0).to_bits()
1711 );
1712 assert_eq!(
1713 bf16::from_f32(250.51f32).to_bits(),
1714 bf16::from_f32(251.0).to_bits()
1715 );
1716 assert_eq!(
1717 bf16::from_f32(251.49f32).to_bits(),
1718 bf16::from_f32(251.0).to_bits()
1719 );
1720 assert_eq!(
1721 bf16::from_f32(251.50f32).to_bits(),
1722 bf16::from_f32(252.0).to_bits()
1723 );
1724 assert_eq!(
1725 bf16::from_f32(251.51f32).to_bits(),
1726 bf16::from_f32(252.0).to_bits()
1727 );
1728 assert_eq!(
1729 bf16::from_f32(252.49f32).to_bits(),
1730 bf16::from_f32(252.0).to_bits()
1731 );
1732 assert_eq!(
1733 bf16::from_f32(252.50f32).to_bits(),
1734 bf16::from_f32(252.0).to_bits()
1735 );
1736 assert_eq!(
1737 bf16::from_f32(252.51f32).to_bits(),
1738 bf16::from_f32(253.0).to_bits()
1739 );
1740 }
1741
1742 #[test]
1743 #[allow(clippy::erasing_op, clippy::identity_op)]
1744 #[cfg_attr(miri, ignore)]
1745 fn round_to_even_f64() {
1746 let min_sub = bf16::from_bits(1);
1748 let min_sub_f = (-133f64).exp2();
1749 assert_eq!(bf16::from_f64(min_sub_f).to_bits(), min_sub.to_bits());
1750 assert_eq!(f64::from(min_sub).to_bits(), min_sub_f.to_bits());
1751
1752 assert_eq!(
1756 bf16::from_f64(min_sub_f * 0.49).to_bits(),
1757 min_sub.to_bits() * 0
1758 );
1759 assert_eq!(
1760 bf16::from_f64(min_sub_f * 0.50).to_bits(),
1761 min_sub.to_bits() * 0
1762 );
1763 assert_eq!(
1764 bf16::from_f64(min_sub_f * 0.51).to_bits(),
1765 min_sub.to_bits() * 1
1766 );
1767
1768 assert_eq!(
1772 bf16::from_f64(min_sub_f * 1.49).to_bits(),
1773 min_sub.to_bits() * 1
1774 );
1775 assert_eq!(
1776 bf16::from_f64(min_sub_f * 1.50).to_bits(),
1777 min_sub.to_bits() * 2
1778 );
1779 assert_eq!(
1780 bf16::from_f64(min_sub_f * 1.51).to_bits(),
1781 min_sub.to_bits() * 2
1782 );
1783
1784 assert_eq!(
1788 bf16::from_f64(min_sub_f * 2.49).to_bits(),
1789 min_sub.to_bits() * 2
1790 );
1791 assert_eq!(
1792 bf16::from_f64(min_sub_f * 2.50).to_bits(),
1793 min_sub.to_bits() * 2
1794 );
1795 assert_eq!(
1796 bf16::from_f64(min_sub_f * 2.51).to_bits(),
1797 min_sub.to_bits() * 3
1798 );
1799
1800 assert_eq!(
1801 bf16::from_f64(250.49f64).to_bits(),
1802 bf16::from_f64(250.0).to_bits()
1803 );
1804 assert_eq!(
1805 bf16::from_f64(250.50f64).to_bits(),
1806 bf16::from_f64(250.0).to_bits()
1807 );
1808 assert_eq!(
1809 bf16::from_f64(250.51f64).to_bits(),
1810 bf16::from_f64(251.0).to_bits()
1811 );
1812 assert_eq!(
1813 bf16::from_f64(251.49f64).to_bits(),
1814 bf16::from_f64(251.0).to_bits()
1815 );
1816 assert_eq!(
1817 bf16::from_f64(251.50f64).to_bits(),
1818 bf16::from_f64(252.0).to_bits()
1819 );
1820 assert_eq!(
1821 bf16::from_f64(251.51f64).to_bits(),
1822 bf16::from_f64(252.0).to_bits()
1823 );
1824 assert_eq!(
1825 bf16::from_f64(252.49f64).to_bits(),
1826 bf16::from_f64(252.0).to_bits()
1827 );
1828 assert_eq!(
1829 bf16::from_f64(252.50f64).to_bits(),
1830 bf16::from_f64(252.0).to_bits()
1831 );
1832 assert_eq!(
1833 bf16::from_f64(252.51f64).to_bits(),
1834 bf16::from_f64(253.0).to_bits()
1835 );
1836 }
1837
1838 #[cfg(feature = "std")]
1839 #[test]
1840 fn formatting() {
1841 let f = bf16::from_f32(0.1152344);
1842
1843 assert_eq!(format!("{:.3}", f), "0.115");
1844 assert_eq!(format!("{:.4}", f), "0.1152");
1845 assert_eq!(format!("{:+.4}", f), "+0.1152");
1846 assert_eq!(format!("{:>+10.4}", f), " +0.1152");
1847
1848 assert_eq!(format!("{:.3?}", f), "0.115");
1849 assert_eq!(format!("{:.4?}", f), "0.1152");
1850 assert_eq!(format!("{:+.4?}", f), "+0.1152");
1851 assert_eq!(format!("{:>+10.4?}", f), " +0.1152");
1852 }
1853
1854 impl quickcheck::Arbitrary for bf16 {
1855 fn arbitrary(g: &mut quickcheck::Gen) -> Self {
1856 bf16(u16::arbitrary(g))
1857 }
1858 }
1859
1860 #[quickcheck]
1861 fn qc_roundtrip_bf16_f32_is_identity(f: bf16) -> bool {
1862 let roundtrip = bf16::from_f32(f.to_f32());
1863 if f.is_nan() {
1864 roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative()
1865 } else {
1866 f.0 == roundtrip.0
1867 }
1868 }
1869
1870 #[quickcheck]
1871 fn qc_roundtrip_bf16_f64_is_identity(f: bf16) -> bool {
1872 let roundtrip = bf16::from_f64(f.to_f64());
1873 if f.is_nan() {
1874 roundtrip.is_nan() && f.is_sign_negative() == roundtrip.is_sign_negative()
1875 } else {
1876 f.0 == roundtrip.0
1877 }
1878 }
1879
1880 #[test]
1881 fn test_max() {
1882 let a = bf16::from_f32(0.0);
1883 let b = bf16::from_f32(42.0);
1884 assert_eq!(a.max(b), b);
1885
1886 let a = bf16::from_f32(42.0);
1887 let b = bf16::from_f32(0.0);
1888 assert_eq!(a.max(b), a);
1889
1890 let a = bf16::NAN;
1891 let b = bf16::from_f32(42.0);
1892 assert_eq!(a.max(b), b);
1893
1894 let a = bf16::from_f32(42.0);
1895 let b = bf16::NAN;
1896 assert_eq!(a.max(b), a);
1897
1898 let a = bf16::NAN;
1899 let b = bf16::NAN;
1900 assert!(a.max(b).is_nan());
1901 }
1902
1903 #[test]
1904 fn test_min() {
1905 let a = bf16::from_f32(0.0);
1906 let b = bf16::from_f32(42.0);
1907 assert_eq!(a.min(b), a);
1908
1909 let a = bf16::from_f32(42.0);
1910 let b = bf16::from_f32(0.0);
1911 assert_eq!(a.min(b), b);
1912
1913 let a = bf16::NAN;
1914 let b = bf16::from_f32(42.0);
1915 assert_eq!(a.min(b), b);
1916
1917 let a = bf16::from_f32(42.0);
1918 let b = bf16::NAN;
1919 assert_eq!(a.min(b), a);
1920
1921 let a = bf16::NAN;
1922 let b = bf16::NAN;
1923 assert!(a.min(b).is_nan());
1924 }
1925}