Skip to content

Commit 838b0e9

Browse files
bpo-44954: Fix wrong result in float.fromhex corner case (GH-27834)
(cherry picked from commit 60b93d9) Co-authored-by: Mark Dickinson <mdickinson@enthought.com>
1 parent f0e2a46 commit 838b0e9

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

Lib/test/test_float.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1468,6 +1468,20 @@ def test_from_hex(self):
14681468
self.identical(fromHex('0X1.0000000000001fp0'), 1.0+2*EPS)
14691469
self.identical(fromHex('0x1.00000000000020p0'), 1.0+2*EPS)
14701470

1471+
# Regression test for a corner-case bug reported in b.p.o. 44954
1472+
self.identical(fromHex('0x.8p-1074'), 0.0)
1473+
self.identical(fromHex('0x.80p-1074'), 0.0)
1474+
self.identical(fromHex('0x.81p-1074'), TINY)
1475+
self.identical(fromHex('0x8p-1078'), 0.0)
1476+
self.identical(fromHex('0x8.0p-1078'), 0.0)
1477+
self.identical(fromHex('0x8.1p-1078'), TINY)
1478+
self.identical(fromHex('0x80p-1082'), 0.0)
1479+
self.identical(fromHex('0x81p-1082'), TINY)
1480+
self.identical(fromHex('.8p-1074'), 0.0)
1481+
self.identical(fromHex('8p-1078'), 0.0)
1482+
self.identical(fromHex('-.8p-1074'), -0.0)
1483+
self.identical(fromHex('+8p-1078'), 0.0)
1484+
14711485
def test_roundtrip(self):
14721486
def roundtrip(x):
14731487
return fromHex(toHex(x))
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed a corner case bug where the result of ``float.fromhex('0x.8p-1074')``
2+
was rounded the wrong way.

Objects/floatobject.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1463,8 +1463,8 @@ float_fromhex(PyTypeObject *type, PyObject *string)
14631463
bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
14641464
if ((digit & half_eps) != 0) {
14651465
round_up = 0;
1466-
if ((digit & (3*half_eps-1)) != 0 ||
1467-
(half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
1466+
if ((digit & (3*half_eps-1)) != 0 || (half_eps == 8 &&
1467+
key_digit+1 < ndigits && (HEX_DIGIT(key_digit+1) & 1) != 0))
14681468
round_up = 1;
14691469
else
14701470
for (i = key_digit-1; i >= 0; i--)

0 commit comments

Comments
 (0)