Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
address review: correct zero division case and add inf**1j test
  • Loading branch information
skirpichev committed Sep 2, 2026
commit ee0a74f2d0554758c45553d3fe0bcc345aa7939d
6 changes: 6 additions & 0 deletions Include/internal/pycore_complexobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ _Py_c_isfinite(Py_complex a)
return isfinite(a.real) && isfinite(a.imag);
}

static inline bool
_Py_c_iszero(Py_complex a)
{
return a.real == 0.0 && a.imag == 0.0;
}

#ifdef __cplusplus
}
#endif
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,9 @@ def test_pow(self):
r = pow(complex(INF), 2.25) # generic algorithm
self.assertEqual(r.real, INF)
self.assertTrue(isnan(r.imag))
r = pow(complex(INF), 1j)
self.assertTrue(isnan(r.real))
self.assertTrue(isnan(r.imag))

a = 3.33+4.43j
self.assertEqual(a ** 0j, 1)
Expand Down
8 changes: 4 additions & 4 deletions Objects/complexobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ _Py_c_quot(Py_complex a, Py_complex b)
{
Py_complex r = c_quot(a, b);

if (_Py_c_isnan(r) && b.real == 0 && b.imag == 0) {
if (_Py_c_isnan(r) && _Py_c_iszero(b)) {
errno = EDOM;
r.real = r.imag = 0.0; /* and set r as documented */
}
Expand All @@ -314,11 +314,11 @@ c_pow(Py_complex a, Py_complex b)
Py_complex r;
double vabs,len,at,phase;

if (b.real == 0. && b.imag == 0.) {
if (_Py_c_iszero(b)) {
r.real = 1.;
r.imag = 0.;
}
else if (a.real == 0. && a.imag == 0.) {
else if (_Py_c_iszero(a)) {
if (b.imag != 0. || b.real < 0.) {
r.real = NAN;
r.imag = NAN;
Expand Down Expand Up @@ -780,7 +780,7 @@ complex_pow(PyObject *v, PyObject *w, PyObject *z)
else {
p = c_pow(a, b);
}
if (_Py_c_isnan(p) && a.real == 0 && a.imag == 0) {
if (_Py_c_isnan(p) && _Py_c_iszero(a) && (b.imag || b.real < 0)) {
PyErr_SetString(PyExc_ZeroDivisionError,
"zero to a negative or complex power");
return NULL;
Expand Down