Skip to content

Commit f37edf9

Browse files
committed
gh-161972: Fix cmath.log(0, base) returning (-inf+nanj) instead of raising ValueError
1 parent 797087c commit f37edf9

3 files changed

Lines changed: 28 additions & 0 deletions

File tree

‎Lib/test/test_cmath.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,25 @@ def polar_with_errno_set(z):
406406
_testcapi.set_errno(0)
407407
self.check_polar(polar_with_errno_set)
408408

409+
def test_log_zero_with_base(self):
410+
# gh-161972: cmath.log(0, base) must raise ValueError, like
411+
# cmath.log(0) and math.log(0, base) do. The domain error from
412+
# c_log(0) used to be lost when the second c_log(base) call
413+
# reset errno to 0.
414+
with self.assertRaises(ValueError):
415+
cmath.log(0)
416+
for base in (2, -1, 0, 1, 10):
417+
with self.assertRaises(ValueError, msg=f"base={base}"):
418+
cmath.log(0, base)
419+
# A base of 0 or 1 still raises for a nonzero argument.
420+
with self.assertRaises(ValueError):
421+
cmath.log(2, 0)
422+
with self.assertRaises(ValueError):
423+
cmath.log(2, 1)
424+
# Normal two-argument logs still work.
425+
self.assertEqual(cmath.log(2, 2), 1+0j)
426+
self.assertEqual(cmath.log(8, 2), 3+0j)
427+
409428
@unittest.skipIf(sys.platform.startswith("sunos"),
410429
"skipping, see gh-138573")
411430
def test_phase(self):
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :func:`cmath.log` with a base: ``cmath.log(0, base)`` now raises :exc:`ValueError` instead of returning ``(-inf+nanj)``. The domain error from the first logarithm was lost when the second call reset ``errno``.

‎Modules/cmathmodule.c‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -957,15 +957,23 @@ cmath_log_impl(PyObject *module, Py_complex x, PyObject *y_obj)
957957
/*[clinic end generated code: output=4effdb7d258e0d94 input=eb25de0757baf4a0]*/
958958
{
959959
Py_complex y;
960+
int errno_save;
960961

961962
errno = 0;
962963
x = c_log(x);
963964
if (y_obj != NULL) {
965+
/* Save the error from c_log(x): the second c_log() call resets
966+
errno to 0 on success, which would hide a domain error from
967+
the first call (gh-161972). */
968+
errno_save = errno;
964969
y = PyComplex_AsCComplex(y_obj);
965970
if (PyErr_Occurred()) {
966971
return NULL;
967972
}
968973
y = c_log(y);
974+
if (errno_save != 0) {
975+
errno = errno_save;
976+
}
969977
x = _Py_c_quot(x, y);
970978
}
971979
if (errno != 0)

0 commit comments

Comments
 (0)