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