Skip to content

Commit f41d8d8

Browse files
[3.13] gh-113841: fix possible undefined division by 0 in _Py_c_pow() (GH-127211) (#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) Co-authored-by: Sergey B Kirpichev <skirpichev@gmail.com>
1 parent 511c588 commit f41d8d8

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
@@ -301,6 +301,11 @@ def test_pow(self):
301301
except OverflowError:
302302
pass
303303

304+
# gh-113841: possible undefined division by 0 in _Py_c_pow()
305+
x, y = 9j, 33j**3
306+
with self.assertRaises(OverflowError):
307+
x**y
308+
304309
def test_pow_with_small_integer_exponents(self):
305310
# Check that small integer exponents are handled identically
306311
# 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
@@ -147,7 +147,7 @@ _Py_c_pow(Py_complex a, Py_complex b)
147147
at = atan2(a.imag, a.real);
148148
phase = at*b.real;
149149
if (b.imag != 0.0) {
150-
len /= exp(at*b.imag);
150+
len *= exp(-at*b.imag);
151151
phase += b.imag*log(vabs);
152152
}
153153
r.real = len*cos(phase);

0 commit comments

Comments
 (0)