@@ -195,18 +195,29 @@ c_quot(Py_complex a, Py_complex b)
195195 const double abs_bimag = b .imag < 0 ? - b .imag : b .imag ;
196196
197197 if (abs_breal >= abs_bimag ) {
198- const double ratio = b .imag / b .real ;
199- const double denom = b .real + b .imag * ratio ;
200- r .real = (a .real + a .imag * ratio ) / denom ;
201- r .imag = (a .imag - a .real * ratio ) / denom ;
198+ /* divide tops and bottom by b.real */
199+ if (abs_breal == 0.0 ) {
200+ r .real = r .imag = NAN ;
201+ }
202+ else {
203+ const double ratio = b .imag / b .real ;
204+ const double denom = b .real + b .imag * ratio ;
205+ r .real = (a .real + a .imag * ratio ) / denom ;
206+ r .imag = (a .imag - a .real * ratio ) / denom ;
207+ }
202208 }
203- else {
209+ else if ( abs_bimag >= abs_breal ) {
204210 /* divide tops and bottom by b.imag */
205211 const double ratio = b .real / b .imag ;
206212 const double denom = b .real * ratio + b .imag ;
213+ assert (b .imag != 0.0 );
207214 r .real = (a .real * ratio + a .imag ) / denom ;
208215 r .imag = (a .imag * ratio - a .real ) / denom ;
209216 }
217+ else {
218+ /* At least one of b.real or b.imag is a NaN */
219+ r .real = r .imag = Py_NAN ;
220+ }
210221 /* Recover infinities and zeros that computed as nan+nanj. See e.g.
211222 the C11, Annex G.5.2, routine _Cdivd(). */
212223 if (isnan (r .real ) && isnan (r .imag )) {
@@ -301,17 +312,34 @@ static Py_complex
301312c_pow (Py_complex a , Py_complex b )
302313{
303314 Py_complex r ;
304- double vabs = hypot (a .real , a .imag );
305- double len = pow (vabs , b .real );
306- double at = atan2 (a .imag , a .real );
307- double phase = at * b .real ;
315+ double vabs ,len ,at ,phase ;
308316
309- if (b .imag != 0.0 ) {
310- len *= exp (- at * b .imag );
311- phase += b .imag * log (vabs );
317+ if (_Py_c_iszero (b )) {
318+ r .real = 1. ;
319+ r .imag = 0. ;
320+ }
321+ else if (_Py_c_iszero (a )) {
322+ if (b .imag != 0. || b .real < 0. ) {
323+ r .real = NAN ;
324+ r .imag = NAN ;
325+ }
326+ else {
327+ r .real = 0. ;
328+ r .imag = 0. ;
329+ }
330+ }
331+ else {
332+ vabs = hypot (a .real ,a .imag );
333+ len = pow (vabs ,b .real );
334+ at = atan2 (a .imag , a .real );
335+ phase = at * b .real ;
336+ if (b .imag != 0.0 ) {
337+ len *= exp (- at * b .imag );
338+ phase += b .imag * log (vabs );
339+ }
340+ r .real = len * cos (phase );
341+ r .imag = len * sin (phase );
312342 }
313- r .real = len * cos (phase );
314- r .imag = len * sin (phase );
315343 return r ;
316344}
317345
0 commit comments