Skip to content

Commit 5aa9e73

Browse files
committed
gh-155526: correct errno handling in complex_abs()
1 parent 219768f commit 5aa9e73

3 files changed

Lines changed: 16 additions & 7 deletions

File tree

‎Lib/test/test_complex.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import unittest
22
import sys
33
from test import support
4+
from test.support import import_helper
45
from test.support.testcase import ComplexesAreIdenticalMixin
56
from test.support.numbers import (
67
VALID_UNDERSCORE_LITERALS,
@@ -791,6 +792,12 @@ def test_abs(self):
791792

792793
self.assertRaises(OverflowError, abs, complex(DBL_MAX, DBL_MAX))
793794

795+
def test_abs_errno_handling(self):
796+
_testcapi = import_helper.import_module('_testcapi')
797+
z = complex('nan')
798+
_testcapi.set_errno(34)
799+
self.assertTrue(isnan(abs(z)))
800+
794801
def test_repr_str(self):
795802
def test(v, expected, test_fn=self.assertEqual):
796803
test_fn(repr(v), expected)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Correct ``errno`` handling in ``abs(complex)``. Patch by Sergey B
2+
Kirpichev.

‎Objects/complexobject.c‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ c_powi(Py_complex x, long n)
367367
double
368368
_Py_c_abs(Py_complex z)
369369
{
370-
/* sets errno = ERANGE on overflow; otherwise errno = 0 */
370+
/* sets errno = ERANGE on overflow */
371371
double result;
372372

373373
if (!isfinite(z.real) || !isfinite(z.imag)) {
@@ -376,23 +376,20 @@ _Py_c_abs(Py_complex z)
376376
NaN. */
377377
if (isinf(z.real)) {
378378
result = fabs(z.real);
379-
errno = 0;
380379
return result;
381380
}
382381
if (isinf(z.imag)) {
383382
result = fabs(z.imag);
384-
errno = 0;
385383
return result;
386384
}
387385
/* either the real or imaginary part is a NaN,
388386
and neither is infinite. Result should be NaN. */
389387
return Py_NAN;
390388
}
391389
result = hypot(z.real, z.imag);
392-
if (!isfinite(result))
390+
if (!isfinite(result)) {
393391
errno = ERANGE;
394-
else
395-
errno = 0;
392+
}
396393
return result;
397394
}
398395

@@ -796,7 +793,10 @@ static PyObject *
796793
complex_abs(PyObject *op)
797794
{
798795
PyComplexObject *v = _PyComplexObject_CAST(op);
799-
double result = _Py_c_abs(v->cval);
796+
double result;
797+
798+
errno = 0;
799+
result = _Py_c_abs(v->cval);
800800
if (errno == ERANGE) {
801801
PyErr_SetString(PyExc_OverflowError,
802802
"absolute value too large");

0 commit comments

Comments
 (0)