Skip to content

Commit 2bb69a5

Browse files
authored
bpo-31373: remove overly strict float range checks (#3486)
This undoes a853a8b except for the pytime.c parts. We want to continue to allow IEEE 754 doubles larger than FLT_MAX to be rounded into finite floats. Tests were added to very this behavior.
1 parent 252033d commit 2bb69a5

File tree

4 files changed

+14
-6
lines changed

4 files changed

+14
-6
lines changed

Lib/test/test_float.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,12 @@ def test_float_specials_do_unpack(self):
617617
('<f', LE_FLOAT_NAN)]:
618618
struct.unpack(fmt, data)
619619

620+
@support.requires_IEEE_754
621+
def test_serialized_float_rounding(self):
622+
from _testcapi import FLT_MAX
623+
self.assertEqual(struct.pack("<f", 3.40282356e38), struct.pack("<f", FLT_MAX))
624+
self.assertEqual(struct.pack("<f", -3.40282356e38), struct.pack("<f", -FLT_MAX))
625+
620626
class FormatTestCase(unittest.TestCase):
621627

622628
def test_format(self):

Lib/test/test_getargs2.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,12 @@ def test_f(self):
377377
r = getargs_f(NAN)
378378
self.assertNotEqual(r, r)
379379

380+
@support.requires_IEEE_754
381+
def test_f_rounding(self):
382+
from _testcapi import getargs_f
383+
self.assertEqual(getargs_f(3.40282356e38), FLT_MAX)
384+
self.assertEqual(getargs_f(-3.40282356e38), -FLT_MAX)
385+
380386
def test_d(self):
381387
from _testcapi import getargs_d
382388
self.assertEqual(getargs_d(4.25), 4.25)

Objects/floatobject.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2233,13 +2233,13 @@ _PyFloat_Pack4(double x, unsigned char *p, int le)
22332233

22342234
}
22352235
else {
2236+
float y = (float)x;
22362237
int i, incr = 1;
22372238

2238-
if (fabs(x) > FLT_MAX && !Py_IS_INFINITY(x))
2239+
if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
22392240
goto Overflow;
22402241

22412242
unsigned char s[sizeof(float)];
2242-
float y = (float)x;
22432243
memcpy(s, &y, sizeof(float));
22442244

22452245
if ((float_format == ieee_little_endian_format && !le)

Python/getargs.c

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -859,10 +859,6 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
859859
double dval = PyFloat_AsDouble(arg);
860860
if (PyErr_Occurred())
861861
RETURN_ERR_OCCURRED;
862-
else if (dval > FLT_MAX)
863-
*p = (float)INFINITY;
864-
else if (dval < -FLT_MAX)
865-
*p = (float)-INFINITY;
866862
else
867863
*p = (float) dval;
868864
break;

0 commit comments

Comments
 (0)