Skip to content

Commit 5f7d709

Browse files
gh-156886: Fix spurious ZeroDivisionError for complex powers (GH-156887)
cos() and sin() of an infinite phase set errno to EDOM, which complex_pow() reported as a zero base. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 7b4364d commit 5f7d709

3 files changed

Lines changed: 16 additions & 0 deletions

File tree

Lib/test/test_complex.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,16 @@ def test_pow(self):
366366
self.assertRaises(TypeError, pow, None, 1j)
367367
self.assertAlmostEqual(pow(1j, 0.5), 0.7071067811865476+0.7071067811865475j)
368368

369+
# gh-156886: an infinite phase is not a zero base.
370+
for base, exp in [(complex(INF), 1j),
371+
(complex(INF, 1), 1j),
372+
(1e300, 1e308j),
373+
(complex(2), complex(0, INF))]:
374+
with self.subTest(base=base, exponent=exp):
375+
r = base ** exp
376+
self.assertTrue(isnan(r.real))
377+
self.assertTrue(isnan(r.imag))
378+
369379
a = 3.33+4.43j
370380
self.assertEqual(a ** 0j, 1)
371381
self.assertEqual(a ** 0.+0.j, 1)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :exc:`ZeroDivisionError` spuriously raised for a complex power
2+
with a non-zero base when the phase of the result is infinite,
3+
e.g. ``1e300**1e308j`` or ``complex('inf')**1j``.

Objects/complexobject.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,9 @@ _Py_c_pow(Py_complex a, Py_complex b)
331331
r.real = len*cos(phase);
332332
r.imag = len*sin(phase);
333333

334+
/* Don't rely on errno set by the math functions above, for
335+
example cos() and sin() set EDOM for an infinite phase. */
336+
errno = 0;
334337
if (isfinite(a.real) && isfinite(a.imag)
335338
&& isfinite(b.real) && isfinite(b.imag))
336339
{

0 commit comments

Comments
 (0)