Skip to content

Commit 4f4b731

Browse files
committed
Correct handling of overflowed or infinite sums
1 parent af7613e commit 4f4b731

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

Lib/test/test_builtin.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import gc
1010
import io
1111
import locale
12+
import math
1213
import os
1314
import pickle
1415
import platform
@@ -1624,6 +1625,8 @@ def test_sum(self):
16241625
self.assertEqual(repr(sum([-0.0])), '0.0')
16251626
self.assertEqual(repr(sum([-0.0], -0.0)), '-0.0')
16261627
self.assertEqual(repr(sum([], -0.0)), '-0.0')
1628+
self.assertTrue(math.isinf(sum([float("inf"), float("inf")])))
1629+
self.assertTrue(math.isinf(sum([1e308, 1e308])))
16271630

16281631
self.assertRaises(TypeError, sum)
16291632
self.assertRaises(TypeError, sum, 42)

Python/bltinmodule.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2541,7 +2541,10 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
25412541
Py_DECREF(iter);
25422542
if (PyErr_Occurred())
25432543
return NULL;
2544-
if (c) {
2544+
/* Avoid losing the sign on a negative result,
2545+
and don't let adding the compensation convert
2546+
an infinite or overflowed sum to a NaN. */
2547+
if (c && Py_IS_FINITE(c)) {
25452548
f_result += c;
25462549
}
25472550
return PyFloat_FromDouble(f_result);

0 commit comments

Comments
 (0)