Skip to content

Commit 8fffbb0

Browse files
[3.12] gh-113841: fix possible undefined division by 0 in _Py_c_pow() (GH-127211) (GH-127216) (GH-127530)
[3.13] gh-113841: fix possible undefined division by 0 in _Py_c_pow() (GH-127211) (GH-127216) Note, that transformed expression is not an equivalent for original one (1/exp(-x) != exp(x) in general for floating-point numbers). Though, the difference seems to be ~1ULP for good libm implementations. It's more interesting why division was used from beginning. Closest algorithm I've found (no error checks, of course;)) - it's Algorithm 190 from ACM: https://dl.acm.org/doi/10.1145/366663.366679. It uses subtraction in the exponent. (cherry picked from commit f7bb658) (cherry picked from commit f41d8d8) Co-authored-by: Sergey B Kirpichev <[email protected]>
1 parent 34fe4af commit 8fffbb0

File tree

3 files changed

+8
-1
lines changed

3 files changed

+8
-1
lines changed

Lib/test/test_complex.py

+5
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,11 @@ def test_pow(self):
300300
except OverflowError:
301301
pass
302302

303+
# gh-113841: possible undefined division by 0 in _Py_c_pow()
304+
x, y = 9j, 33j**3
305+
with self.assertRaises(OverflowError):
306+
x**y
307+
303308
def test_pow_with_small_integer_exponents(self):
304309
# Check that small integer exponents are handled identically
305310
# regardless of their type.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix possible undefined behavior division by zero in :class:`complex`'s
2+
:c:func:`_Py_c_pow`.

Objects/complexobject.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ _Py_c_pow(Py_complex a, Py_complex b)
146146
at = atan2(a.imag, a.real);
147147
phase = at*b.real;
148148
if (b.imag != 0.0) {
149-
len /= exp(at*b.imag);
149+
len *= exp(-at*b.imag);
150150
phase += b.imag*log(vabs);
151151
}
152152
r.real = len*cos(phase);

0 commit comments

Comments
 (0)