MCPcopy Index your code
hub / github.com/RustPython/RustPython / test_half_float

Method test_half_float

Lib/test/test_struct.py:918–1028  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

916 self.assertRaises(StopIteration, next, it)
917
918 def test_half_float(self):
919 _testcapi = import_helper.import_module('_testcapi')
920 # Little-endian examples from:
921 # http://en.wikipedia.org/wiki/Half_precision_floating-point_format
922 format_bits_float__cleanRoundtrip_list = [
923 (b'\x00\x3c', 1.0),
924 (b'\x00\xc0', -2.0),
925 (b'\xff\x7b', 65504.0), # (max half precision)
926 (b'\x00\x04', 2**-14), # ~= 6.10352 * 10**-5 (min pos normal)
927 (b'\x01\x00', 2**-24), # ~= 5.96046 * 10**-8 (min pos subnormal)
928 (b'\x00\x00', 0.0),
929 (b'\x00\x80', -0.0),
930 (b'\x00\x7c', float('+inf')),
931 (b'\x00\xfc', float('-inf')),
932 (b'\x55\x35', 0.333251953125), # ~= 1/3
933 ]
934
935 for le_bits, f in format_bits_float__cleanRoundtrip_list:
936 be_bits = le_bits[::-1]
937 self.assertEqual(f, struct.unpack('<e', le_bits)[0])
938 self.assertEqual(le_bits, struct.pack('<e', f))
939 self.assertEqual(f, struct.unpack('>e', be_bits)[0])
940 self.assertEqual(be_bits, struct.pack('>e', f))
941 if sys.byteorder == 'little':
942 self.assertEqual(f, struct.unpack('e', le_bits)[0])
943 self.assertEqual(le_bits, struct.pack('e', f))
944 else:
945 self.assertEqual(f, struct.unpack('e', be_bits)[0])
946 self.assertEqual(be_bits, struct.pack('e', f))
947
948 # Check for NaN handling:
949 format_bits__nan_list = [
950 ('<e', b'\x01\xfc'),
951 ('<e', b'\x00\xfe'),
952 ('<e', b'\xff\xff'),
953 ('<e', b'\x01\x7c'),
954 ('<e', b'\x00\x7e'),
955 ('<e', b'\xff\x7f'),
956 ]
957
958 for formatcode, bits in format_bits__nan_list:
959 self.assertTrue(math.isnan(struct.unpack('<e', bits)[0]))
960 self.assertTrue(math.isnan(struct.unpack('>e', bits[::-1])[0]))
961
962 # Check that packing produces a bit pattern representing a quiet NaN:
963 # all exponent bits and the msb of the fraction should all be 1.
964 if _testcapi.nan_msb_is_signaling:
965 # HP PA RISC and some MIPS CPUs use 0 for quiet, see:
966 # https://en.wikipedia.org/wiki/NaN#Encoding
967 expected = 0x7c
968 else:
969 expected = 0x7e
970
971 packed = struct.pack('<e', math.nan)
972 self.assertEqual(packed[1] & 0x7e, expected)
973 packed = struct.pack('<e', -math.nan)
974 self.assertEqual(packed[1] & 0x7e, expected)
975

Callers

nothing calls this directly

Calls 6

assertTrueMethod · 0.80
import_moduleMethod · 0.45
assertEqualMethod · 0.45
unpackMethod · 0.45
packMethod · 0.45
assertRaisesMethod · 0.45

Tested by

no test coverage detected