MCPcopy Index your code
hub / github.com/python/cpython / test_half_float

Method test_half_float

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

Source from the content-addressed store, hash-verified

1123 self.assertRaises(StopIteration, next, it)
1124
1125 def test_half_float(self):
1126 _testcapi = import_helper.import_module('_testcapi')
1127 # Little-endian examples from:
1128 # http://en.wikipedia.org/wiki/Half_precision_floating-point_format
1129 format_bits_float__cleanRoundtrip_list = [
1130 (b'\x00\x3c', 1.0),
1131 (b'\x00\xc0', -2.0),
1132 (b'\xff\x7b', 65504.0), # (max half precision)
1133 (b'\x00\x04', 2**-14), # ~= 6.10352 * 10**-5 (min pos normal)
1134 (b'\x01\x00', 2**-24), # ~= 5.96046 * 10**-8 (min pos subnormal)
1135 (b'\x00\x00', 0.0),
1136 (b'\x00\x80', -0.0),
1137 (b'\x00\x7c', float('+inf')),
1138 (b'\x00\xfc', float('-inf')),
1139 (b'\x55\x35', 0.333251953125), # ~= 1/3
1140 ]
1141
1142 for le_bits, f in format_bits_float__cleanRoundtrip_list:
1143 be_bits = le_bits[::-1]
1144 self.assertEqual(f, struct.unpack('<e', le_bits)[0])
1145 self.assertEqual(le_bits, struct.pack('<e', f))
1146 self.assertEqual(f, struct.unpack('>e', be_bits)[0])
1147 self.assertEqual(be_bits, struct.pack('>e', f))
1148 if sys.byteorder == 'little':
1149 self.assertEqual(f, struct.unpack('e', le_bits)[0])
1150 self.assertEqual(le_bits, struct.pack('e', f))
1151 else:
1152 self.assertEqual(f, struct.unpack('e', be_bits)[0])
1153 self.assertEqual(be_bits, struct.pack('e', f))
1154
1155 # Check for NaN handling:
1156 format_bits__nan_list = [
1157 ('<e', b'\x01\xfc'),
1158 ('<e', b'\x00\xfe'),
1159 ('<e', b'\xff\xff'),
1160 ('<e', b'\x01\x7c'),
1161 ('<e', b'\x00\x7e'),
1162 ('<e', b'\xff\x7f'),
1163 ]
1164
1165 for formatcode, bits in format_bits__nan_list:
1166 self.assertTrue(math.isnan(struct.unpack('<e', bits)[0]))
1167 self.assertTrue(math.isnan(struct.unpack('>e', bits[::-1])[0]))
1168
1169 # Check that packing produces a bit pattern representing a quiet NaN:
1170 # all exponent bits and the msb of the fraction should all be 1.
1171 if _testcapi.nan_msb_is_signaling:
1172 # HP PA RISC and some MIPS CPUs use 0 for quiet, see:
1173 # https://en.wikipedia.org/wiki/NaN#Encoding
1174 expected = 0x7c
1175 else:
1176 expected = 0x7e
1177
1178 packed = struct.pack('<e', math.nan)
1179 self.assertEqual(packed[1] & 0x7e, expected)
1180 packed = struct.pack('<e', -math.nan)
1181 self.assertEqual(packed[1] & 0x7e, expected)
1182

Callers

nothing calls this directly

Calls 6

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

Tested by

no test coverage detected