Skip to content

Commit

Permalink
Correct handling of overflowed or infinite sums
Browse files Browse the repository at this point in the history
  • Loading branch information
rhettinger committed Dec 23, 2022
1 parent af7613e commit 4f4b731
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
3 changes: 3 additions & 0 deletions Lib/test/test_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import gc
import io
import locale
import math
import os
import pickle
import platform
Expand Down Expand Up @@ -1624,6 +1625,8 @@ def test_sum(self):
self.assertEqual(repr(sum([-0.0])), '0.0')
self.assertEqual(repr(sum([-0.0], -0.0)), '-0.0')
self.assertEqual(repr(sum([], -0.0)), '-0.0')
self.assertTrue(math.isinf(sum([float("inf"), float("inf")])))
self.assertTrue(math.isinf(sum([1e308, 1e308])))

self.assertRaises(TypeError, sum)
self.assertRaises(TypeError, sum, 42)
Expand Down
5 changes: 4 additions & 1 deletion Python/bltinmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2541,7 +2541,10 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
Py_DECREF(iter);
if (PyErr_Occurred())
return NULL;
if (c) {
/* Avoid losing the sign on a negative result,
and don't let adding the compensation convert
an infinite or overflowed sum to a NaN. */
if (c && Py_IS_FINITE(c)) {
f_result += c;
}
return PyFloat_FromDouble(f_result);
Expand Down

0 comments on commit 4f4b731

Please sign in to comment.