/src/cpython/Objects/complexobject.c
Line | Count | Source |
1 | | /* Complex object implementation */ |
2 | | |
3 | | /* Borrows heavily from floatobject.c */ |
4 | | |
5 | | /* Submitted by Jim Hugunin */ |
6 | | |
7 | | #include "Python.h" |
8 | | #include "pycore_call.h" // _PyObject_CallNoArgs() |
9 | | #include "pycore_complexobject.h" // _PyComplex_FormatAdvancedWriter() |
10 | | #include "pycore_floatobject.h" // _Py_convert_int_to_double() |
11 | | #include "pycore_freelist.h" // _Py_FREELIST_FREE(), _Py_FREELIST_POP() |
12 | | #include "pycore_long.h" // _PyLong_GetZero() |
13 | | #include "pycore_object.h" // _PyObject_Init() |
14 | | #include "pycore_pymath.h" // _Py_ADJUST_ERANGE2() |
15 | | |
16 | | |
17 | 2.84k | #define _PyComplexObject_CAST(op) ((PyComplexObject *)(op)) |
18 | | |
19 | | |
20 | | /*[clinic input] |
21 | | class complex "PyComplexObject *" "&PyComplex_Type" |
22 | | [clinic start generated code]*/ |
23 | | /*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/ |
24 | | |
25 | | #include "clinic/complexobject.c.h" |
26 | | |
27 | | /* elementary operations on complex numbers */ |
28 | | |
29 | | Py_complex |
30 | | _Py_c_sum(Py_complex a, Py_complex b) |
31 | 0 | { |
32 | 0 | Py_complex r; |
33 | 0 | r.real = a.real + b.real; |
34 | 0 | r.imag = a.imag + b.imag; |
35 | 0 | return r; |
36 | 0 | } |
37 | | |
38 | | Py_complex |
39 | | _Py_cr_sum(Py_complex a, double b) |
40 | 0 | { |
41 | 0 | Py_complex r = a; |
42 | 0 | r.real += b; |
43 | 0 | return r; |
44 | 0 | } |
45 | | |
46 | | static inline Py_complex |
47 | | _Py_rc_sum(double a, Py_complex b) |
48 | 0 | { |
49 | 0 | return _Py_cr_sum(b, a); |
50 | 0 | } |
51 | | |
52 | | Py_complex |
53 | | _Py_c_diff(Py_complex a, Py_complex b) |
54 | 0 | { |
55 | 0 | Py_complex r; |
56 | 0 | r.real = a.real - b.real; |
57 | 0 | r.imag = a.imag - b.imag; |
58 | 0 | return r; |
59 | 0 | } |
60 | | |
61 | | Py_complex |
62 | | _Py_cr_diff(Py_complex a, double b) |
63 | 0 | { |
64 | 0 | Py_complex r = a; |
65 | 0 | r.real -= b; |
66 | 0 | return r; |
67 | 0 | } |
68 | | |
69 | | Py_complex |
70 | | _Py_rc_diff(double a, Py_complex b) |
71 | 0 | { |
72 | 0 | Py_complex r; |
73 | 0 | r.real = a - b.real; |
74 | 0 | r.imag = -b.imag; |
75 | 0 | return r; |
76 | 0 | } |
77 | | |
78 | | Py_complex |
79 | | _Py_c_neg(Py_complex a) |
80 | 0 | { |
81 | 0 | Py_complex r; |
82 | 0 | r.real = -a.real; |
83 | 0 | r.imag = -a.imag; |
84 | 0 | return r; |
85 | 0 | } |
86 | | |
87 | | Py_complex |
88 | | _Py_c_prod(Py_complex z, Py_complex w) |
89 | 0 | { |
90 | 0 | double a = z.real, b = z.imag, c = w.real, d = w.imag; |
91 | 0 | double ac = a*c, bd = b*d, ad = a*d, bc = b*c; |
92 | 0 | Py_complex r = {ac - bd, ad + bc}; |
93 | | |
94 | | /* Recover infinities that computed as nan+nanj. See e.g. the C11, |
95 | | Annex G.5.1, routine _Cmultd(). */ |
96 | 0 | if (isnan(r.real) && isnan(r.imag)) { |
97 | 0 | int recalc = 0; |
98 | |
|
99 | 0 | if (isinf(a) || isinf(b)) { /* z is infinite */ |
100 | | /* "Box" the infinity and change nans in the other factor to 0 */ |
101 | 0 | a = copysign(isinf(a) ? 1.0 : 0.0, a); |
102 | 0 | b = copysign(isinf(b) ? 1.0 : 0.0, b); |
103 | 0 | if (isnan(c)) { |
104 | 0 | c = copysign(0.0, c); |
105 | 0 | } |
106 | 0 | if (isnan(d)) { |
107 | 0 | d = copysign(0.0, d); |
108 | 0 | } |
109 | 0 | recalc = 1; |
110 | 0 | } |
111 | 0 | if (isinf(c) || isinf(d)) { /* w is infinite */ |
112 | | /* "Box" the infinity and change nans in the other factor to 0 */ |
113 | 0 | c = copysign(isinf(c) ? 1.0 : 0.0, c); |
114 | 0 | d = copysign(isinf(d) ? 1.0 : 0.0, d); |
115 | 0 | if (isnan(a)) { |
116 | 0 | a = copysign(0.0, a); |
117 | 0 | } |
118 | 0 | if (isnan(b)) { |
119 | 0 | b = copysign(0.0, b); |
120 | 0 | } |
121 | 0 | recalc = 1; |
122 | 0 | } |
123 | 0 | if (!recalc && (isinf(ac) || isinf(bd) || isinf(ad) || isinf(bc))) { |
124 | | /* Recover infinities from overflow by changing nans to 0 */ |
125 | 0 | if (isnan(a)) { |
126 | 0 | a = copysign(0.0, a); |
127 | 0 | } |
128 | 0 | if (isnan(b)) { |
129 | 0 | b = copysign(0.0, b); |
130 | 0 | } |
131 | 0 | if (isnan(c)) { |
132 | 0 | c = copysign(0.0, c); |
133 | 0 | } |
134 | 0 | if (isnan(d)) { |
135 | 0 | d = copysign(0.0, d); |
136 | 0 | } |
137 | 0 | recalc = 1; |
138 | 0 | } |
139 | 0 | if (recalc) { |
140 | 0 | r.real = INFINITY*(a*c - b*d); |
141 | 0 | r.imag = INFINITY*(a*d + b*c); |
142 | 0 | } |
143 | 0 | } |
144 | |
|
145 | 0 | return r; |
146 | 0 | } |
147 | | |
148 | | Py_complex |
149 | | _Py_cr_prod(Py_complex a, double b) |
150 | 0 | { |
151 | 0 | Py_complex r = a; |
152 | 0 | r.real *= b; |
153 | 0 | r.imag *= b; |
154 | 0 | return r; |
155 | 0 | } |
156 | | |
157 | | static inline Py_complex |
158 | | _Py_rc_prod(double a, Py_complex b) |
159 | 0 | { |
160 | 0 | return _Py_cr_prod(b, a); |
161 | 0 | } |
162 | | |
163 | | /* Avoid bad optimization on Windows ARM64 until the compiler is fixed */ |
164 | | #ifdef _M_ARM64 |
165 | | #pragma optimize("", off) |
166 | | #endif |
167 | | Py_complex |
168 | | _Py_c_quot(Py_complex a, Py_complex b) |
169 | 0 | { |
170 | | /****************************************************************** |
171 | | This was the original algorithm. It's grossly prone to spurious |
172 | | overflow and underflow errors. It also merrily divides by 0 despite |
173 | | checking for that(!). The code still serves a doc purpose here, as |
174 | | the algorithm following is a simple by-cases transformation of this |
175 | | one: |
176 | | |
177 | | Py_complex r; |
178 | | double d = b.real*b.real + b.imag*b.imag; |
179 | | if (d == 0.) |
180 | | errno = EDOM; |
181 | | r.real = (a.real*b.real + a.imag*b.imag)/d; |
182 | | r.imag = (a.imag*b.real - a.real*b.imag)/d; |
183 | | return r; |
184 | | ******************************************************************/ |
185 | | |
186 | | /* This algorithm is better, and is pretty obvious: first divide the |
187 | | * numerators and denominator by whichever of {b.real, b.imag} has |
188 | | * larger magnitude. The earliest reference I found was to CACM |
189 | | * Algorithm 116 (Complex Division, Robert L. Smith, Stanford |
190 | | * University). |
191 | | */ |
192 | 0 | Py_complex r; /* the result */ |
193 | 0 | const double abs_breal = b.real < 0 ? -b.real : b.real; |
194 | 0 | const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; |
195 | |
|
196 | 0 | if (abs_breal >= abs_bimag) { |
197 | | /* divide tops and bottom by b.real */ |
198 | 0 | if (abs_breal == 0.0) { |
199 | 0 | errno = EDOM; |
200 | 0 | r.real = r.imag = 0.0; |
201 | 0 | } |
202 | 0 | else { |
203 | 0 | const double ratio = b.imag / b.real; |
204 | 0 | const double denom = b.real + b.imag * ratio; |
205 | 0 | r.real = (a.real + a.imag * ratio) / denom; |
206 | 0 | r.imag = (a.imag - a.real * ratio) / denom; |
207 | 0 | } |
208 | 0 | } |
209 | 0 | else if (abs_bimag >= abs_breal) { |
210 | | /* divide tops and bottom by b.imag */ |
211 | 0 | const double ratio = b.real / b.imag; |
212 | 0 | const double denom = b.real * ratio + b.imag; |
213 | 0 | assert(b.imag != 0.0); |
214 | 0 | r.real = (a.real * ratio + a.imag) / denom; |
215 | 0 | r.imag = (a.imag * ratio - a.real) / denom; |
216 | 0 | } |
217 | 0 | else { |
218 | | /* At least one of b.real or b.imag is a NaN */ |
219 | 0 | r.real = r.imag = Py_NAN; |
220 | 0 | } |
221 | | |
222 | | /* Recover infinities and zeros that computed as nan+nanj. See e.g. |
223 | | the C11, Annex G.5.2, routine _Cdivd(). */ |
224 | 0 | if (isnan(r.real) && isnan(r.imag)) { |
225 | 0 | if ((isinf(a.real) || isinf(a.imag)) |
226 | 0 | && isfinite(b.real) && isfinite(b.imag)) |
227 | 0 | { |
228 | 0 | const double x = copysign(isinf(a.real) ? 1.0 : 0.0, a.real); |
229 | 0 | const double y = copysign(isinf(a.imag) ? 1.0 : 0.0, a.imag); |
230 | 0 | r.real = INFINITY * (x*b.real + y*b.imag); |
231 | 0 | r.imag = INFINITY * (y*b.real - x*b.imag); |
232 | 0 | } |
233 | 0 | else if ((isinf(abs_breal) || isinf(abs_bimag)) |
234 | 0 | && isfinite(a.real) && isfinite(a.imag)) |
235 | 0 | { |
236 | 0 | const double x = copysign(isinf(b.real) ? 1.0 : 0.0, b.real); |
237 | 0 | const double y = copysign(isinf(b.imag) ? 1.0 : 0.0, b.imag); |
238 | 0 | r.real = 0.0 * (a.real*x + a.imag*y); |
239 | 0 | r.imag = 0.0 * (a.imag*x - a.real*y); |
240 | 0 | } |
241 | 0 | } |
242 | |
|
243 | 0 | return r; |
244 | 0 | } |
245 | | |
246 | | Py_complex |
247 | | _Py_cr_quot(Py_complex a, double b) |
248 | 0 | { |
249 | 0 | Py_complex r = a; |
250 | 0 | if (b) { |
251 | 0 | r.real /= b; |
252 | 0 | r.imag /= b; |
253 | 0 | } |
254 | 0 | else { |
255 | 0 | errno = EDOM; |
256 | 0 | r.real = r.imag = 0.0; |
257 | 0 | } |
258 | 0 | return r; |
259 | 0 | } |
260 | | |
261 | | /* an equivalent of _Py_c_quot() function, when 1st argument is real */ |
262 | | Py_complex |
263 | | _Py_rc_quot(double a, Py_complex b) |
264 | 0 | { |
265 | 0 | Py_complex r; |
266 | 0 | const double abs_breal = b.real < 0 ? -b.real : b.real; |
267 | 0 | const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; |
268 | |
|
269 | 0 | if (abs_breal >= abs_bimag) { |
270 | 0 | if (abs_breal == 0.0) { |
271 | 0 | errno = EDOM; |
272 | 0 | r.real = r.imag = 0.0; |
273 | 0 | } |
274 | 0 | else { |
275 | 0 | const double ratio = b.imag / b.real; |
276 | 0 | const double denom = b.real + b.imag * ratio; |
277 | 0 | r.real = a / denom; |
278 | 0 | r.imag = (-a * ratio) / denom; |
279 | 0 | } |
280 | 0 | } |
281 | 0 | else if (abs_bimag >= abs_breal) { |
282 | 0 | const double ratio = b.real / b.imag; |
283 | 0 | const double denom = b.real * ratio + b.imag; |
284 | 0 | assert(b.imag != 0.0); |
285 | 0 | r.real = (a * ratio) / denom; |
286 | 0 | r.imag = (-a) / denom; |
287 | 0 | } |
288 | 0 | else { |
289 | 0 | r.real = r.imag = Py_NAN; |
290 | 0 | } |
291 | |
|
292 | 0 | if (isnan(r.real) && isnan(r.imag) && isfinite(a) |
293 | 0 | && (isinf(abs_breal) || isinf(abs_bimag))) |
294 | 0 | { |
295 | 0 | const double x = copysign(isinf(b.real) ? 1.0 : 0.0, b.real); |
296 | 0 | const double y = copysign(isinf(b.imag) ? 1.0 : 0.0, b.imag); |
297 | 0 | r.real = 0.0 * (a*x); |
298 | 0 | r.imag = 0.0 * (-a*y); |
299 | 0 | } |
300 | |
|
301 | 0 | return r; |
302 | 0 | } |
303 | | #ifdef _M_ARM64 |
304 | | #pragma optimize("", on) |
305 | | #endif |
306 | | |
307 | | Py_complex |
308 | | _Py_c_pow(Py_complex a, Py_complex b) |
309 | 0 | { |
310 | 0 | Py_complex r; |
311 | 0 | double vabs,len,at,phase; |
312 | 0 | if (b.real == 0. && b.imag == 0.) { |
313 | 0 | r.real = 1.; |
314 | 0 | r.imag = 0.; |
315 | 0 | } |
316 | 0 | else if (a.real == 0. && a.imag == 0.) { |
317 | 0 | if (b.imag != 0. || b.real < 0.) |
318 | 0 | errno = EDOM; |
319 | 0 | r.real = 0.; |
320 | 0 | r.imag = 0.; |
321 | 0 | } |
322 | 0 | else { |
323 | 0 | vabs = hypot(a.real,a.imag); |
324 | 0 | len = pow(vabs,b.real); |
325 | 0 | at = atan2(a.imag, a.real); |
326 | 0 | phase = at*b.real; |
327 | 0 | if (b.imag != 0.0) { |
328 | 0 | len *= exp(-at*b.imag); |
329 | 0 | phase += b.imag*log(vabs); |
330 | 0 | } |
331 | 0 | r.real = len*cos(phase); |
332 | 0 | r.imag = len*sin(phase); |
333 | | |
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 | 0 | errno = 0; |
337 | 0 | if (isfinite(a.real) && isfinite(a.imag) |
338 | 0 | && isfinite(b.real) && isfinite(b.imag)) |
339 | 0 | { |
340 | 0 | _Py_ADJUST_ERANGE2(r.real, r.imag); |
341 | 0 | } |
342 | 0 | } |
343 | 0 | return r; |
344 | 0 | } |
345 | | |
346 | 0 | #define INT_EXP_CUTOFF 100 |
347 | | |
348 | | static Py_complex |
349 | | c_powu(Py_complex x, long n) |
350 | 0 | { |
351 | 0 | assert(0 < n && n <= INT_EXP_CUTOFF); |
352 | 0 | while ((n & 1) == 0) { |
353 | 0 | x = _Py_c_prod(x, x); |
354 | 0 | n >>= 1; |
355 | 0 | } |
356 | 0 | Py_complex r = x; |
357 | 0 | n >>= 1; |
358 | 0 | while (n) { |
359 | 0 | x = _Py_c_prod(x, x); |
360 | 0 | if (n & 1) { |
361 | 0 | r = _Py_c_prod(r, x); |
362 | 0 | } |
363 | 0 | n >>= 1; |
364 | 0 | } |
365 | 0 | return r; |
366 | 0 | } |
367 | | |
368 | | static Py_complex |
369 | | c_powi(Py_complex x, long n) |
370 | 0 | { |
371 | 0 | if (n > 0) |
372 | 0 | return c_powu(x, n); |
373 | 0 | else if (n < 0) |
374 | 0 | return _Py_rc_quot(1.0, c_powu(x, -n)); |
375 | 0 | else |
376 | 0 | return (Py_complex){1., 0.}; |
377 | 0 | } |
378 | | |
379 | | double |
380 | | _Py_c_abs(Py_complex z) |
381 | 0 | { |
382 | | /* sets errno = ERANGE on overflow */ |
383 | 0 | double result; |
384 | 0 | int saved_errno = errno; |
385 | |
|
386 | 0 | if (!isfinite(z.real) || !isfinite(z.imag)) { |
387 | | /* C99 rules: if either the real or the imaginary part is an |
388 | | infinity, return infinity, even if the other part is a |
389 | | NaN. */ |
390 | 0 | if (isinf(z.real)) { |
391 | 0 | result = fabs(z.real); |
392 | 0 | errno = saved_errno; |
393 | 0 | return result; |
394 | 0 | } |
395 | 0 | if (isinf(z.imag)) { |
396 | 0 | result = fabs(z.imag); |
397 | 0 | errno = saved_errno; |
398 | 0 | return result; |
399 | 0 | } |
400 | | /* either the real or imaginary part is a NaN, |
401 | | and neither is infinite. Result should be NaN. */ |
402 | 0 | errno = saved_errno; |
403 | 0 | return Py_NAN; |
404 | 0 | } |
405 | 0 | result = hypot(z.real, z.imag); |
406 | 0 | if (!isfinite(result)) |
407 | 0 | errno = ERANGE; |
408 | 0 | else |
409 | 0 | errno = saved_errno; |
410 | 0 | return result; |
411 | 0 | } |
412 | | |
413 | | static PyObject * |
414 | | complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) |
415 | 0 | { |
416 | 0 | PyObject *op; |
417 | |
|
418 | 0 | op = type->tp_alloc(type, 0); |
419 | 0 | if (op != NULL) |
420 | 0 | ((PyComplexObject *)op)->cval = cval; |
421 | 0 | return op; |
422 | 0 | } |
423 | | |
424 | | PyObject * |
425 | | PyComplex_FromCComplex(Py_complex cval) |
426 | 7.69k | { |
427 | 7.69k | PyComplexObject *op = _Py_FREELIST_POP(PyComplexObject, complexes); |
428 | | |
429 | 7.69k | if (op == NULL) { |
430 | | /* Inline PyObject_New */ |
431 | 2.03k | op = PyObject_Malloc(sizeof(PyComplexObject)); |
432 | 2.03k | if (op == NULL) { |
433 | 0 | return PyErr_NoMemory(); |
434 | 0 | } |
435 | 2.03k | _PyObject_Init((PyObject*)op, &PyComplex_Type); |
436 | 2.03k | } |
437 | 7.69k | op->cval = cval; |
438 | 7.69k | return (PyObject *) op; |
439 | 7.69k | } |
440 | | |
441 | | static void |
442 | | complex_dealloc(PyObject *op) |
443 | 7.69k | { |
444 | 7.69k | assert(PyComplex_Check(op)); |
445 | 7.69k | if (PyComplex_CheckExact(op)) { |
446 | 7.69k | _Py_FREELIST_FREE(complexes, op, PyObject_Free); |
447 | 7.69k | } |
448 | 0 | else { |
449 | 0 | Py_TYPE(op)->tp_free(op); |
450 | 0 | } |
451 | 7.69k | } |
452 | | |
453 | | static PyObject * |
454 | | complex_subtype_from_doubles(PyTypeObject *type, double real, double imag) |
455 | 0 | { |
456 | 0 | Py_complex c; |
457 | 0 | c.real = real; |
458 | 0 | c.imag = imag; |
459 | 0 | return complex_subtype_from_c_complex(type, c); |
460 | 0 | } |
461 | | |
462 | | PyObject * |
463 | | PyComplex_FromDoubles(double real, double imag) |
464 | 0 | { |
465 | 0 | Py_complex c; |
466 | 0 | c.real = real; |
467 | 0 | c.imag = imag; |
468 | 0 | return PyComplex_FromCComplex(c); |
469 | 0 | } |
470 | | |
471 | | static PyObject * try_complex_special_method(PyObject *); |
472 | | |
473 | | double |
474 | | PyComplex_RealAsDouble(PyObject *op) |
475 | 1 | { |
476 | 1 | double real = -1.0; |
477 | | |
478 | 1 | if (PyComplex_Check(op)) { |
479 | 1 | real = ((PyComplexObject *)op)->cval.real; |
480 | 1 | } |
481 | 0 | else { |
482 | 0 | PyObject* newop = try_complex_special_method(op); |
483 | 0 | if (newop) { |
484 | 0 | real = ((PyComplexObject *)newop)->cval.real; |
485 | 0 | Py_DECREF(newop); |
486 | 0 | } else if (!PyErr_Occurred()) { |
487 | 0 | real = PyFloat_AsDouble(op); |
488 | 0 | } |
489 | 0 | } |
490 | | |
491 | 1 | return real; |
492 | 1 | } |
493 | | |
494 | | double |
495 | | PyComplex_ImagAsDouble(PyObject *op) |
496 | 1 | { |
497 | 1 | double imag = -1.0; |
498 | | |
499 | 1 | if (PyComplex_Check(op)) { |
500 | 1 | imag = ((PyComplexObject *)op)->cval.imag; |
501 | 1 | } |
502 | 0 | else { |
503 | 0 | PyObject* newop = try_complex_special_method(op); |
504 | 0 | if (newop) { |
505 | 0 | imag = ((PyComplexObject *)newop)->cval.imag; |
506 | 0 | Py_DECREF(newop); |
507 | 0 | } else if (!PyErr_Occurred()) { |
508 | 0 | PyFloat_AsDouble(op); |
509 | 0 | if (!PyErr_Occurred()) { |
510 | 0 | imag = 0.0; |
511 | 0 | } |
512 | 0 | } |
513 | 0 | } |
514 | | |
515 | 1 | return imag; |
516 | 1 | } |
517 | | |
518 | | static PyObject * |
519 | | try_complex_special_method(PyObject *op) |
520 | 0 | { |
521 | 0 | PyObject *f; |
522 | |
|
523 | 0 | f = _PyObject_LookupSpecial(op, &_Py_ID(__complex__)); |
524 | 0 | if (f) { |
525 | 0 | PyObject *res = _PyObject_CallNoArgs(f); |
526 | 0 | Py_DECREF(f); |
527 | 0 | if (!res || PyComplex_CheckExact(res)) { |
528 | 0 | return res; |
529 | 0 | } |
530 | 0 | if (!PyComplex_Check(res)) { |
531 | 0 | PyErr_Format(PyExc_TypeError, |
532 | 0 | "%T.__complex__() must return a complex, not %T", |
533 | 0 | op, res); |
534 | 0 | Py_DECREF(res); |
535 | 0 | return NULL; |
536 | 0 | } |
537 | | /* Issue #29894: warn if 'res' not of exact type complex. */ |
538 | 0 | if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, |
539 | 0 | "%T.__complex__() must return a complex, not %T. " |
540 | 0 | "The ability to return an instance of a strict subclass of complex " |
541 | 0 | "is deprecated, and may be removed in a future version of Python.", |
542 | 0 | op, res)) { |
543 | 0 | Py_DECREF(res); |
544 | 0 | return NULL; |
545 | 0 | } |
546 | 0 | return res; |
547 | 0 | } |
548 | 0 | return NULL; |
549 | 0 | } |
550 | | |
551 | | Py_complex |
552 | | PyComplex_AsCComplex(PyObject *op) |
553 | 2 | { |
554 | 2 | Py_complex cv; |
555 | 2 | PyObject *newop = NULL; |
556 | | |
557 | 2 | assert(op); |
558 | | /* If op is already of type PyComplex_Type, return its value */ |
559 | 2 | if (PyComplex_Check(op)) { |
560 | 2 | return ((PyComplexObject *)op)->cval; |
561 | 2 | } |
562 | | /* If not, use op's __complex__ method, if it exists */ |
563 | | |
564 | | /* return -1 on failure */ |
565 | 0 | cv.real = -1.; |
566 | 0 | cv.imag = 0.; |
567 | |
|
568 | 0 | newop = try_complex_special_method(op); |
569 | |
|
570 | 0 | if (newop) { |
571 | 0 | cv = ((PyComplexObject *)newop)->cval; |
572 | 0 | Py_DECREF(newop); |
573 | 0 | return cv; |
574 | 0 | } |
575 | 0 | else if (PyErr_Occurred()) { |
576 | 0 | return cv; |
577 | 0 | } |
578 | | /* If neither of the above works, interpret op as a float giving the |
579 | | real part of the result, and fill in the imaginary part as 0. */ |
580 | 0 | else { |
581 | | /* PyFloat_AsDouble will return -1 on failure */ |
582 | 0 | cv.real = PyFloat_AsDouble(op); |
583 | 0 | return cv; |
584 | 0 | } |
585 | 0 | } |
586 | | |
587 | | static PyObject * |
588 | | complex_repr(PyObject *op) |
589 | 2.84k | { |
590 | 2.84k | int precision = 0; |
591 | 2.84k | char format_code = 'r'; |
592 | 2.84k | PyObject *result = NULL; |
593 | 2.84k | PyComplexObject *v = _PyComplexObject_CAST(op); |
594 | | |
595 | | /* If these are non-NULL, they'll need to be freed. */ |
596 | 2.84k | char *pre = NULL; |
597 | 2.84k | char *im = NULL; |
598 | | |
599 | | /* These do not need to be freed. re is either an alias |
600 | | for pre or a pointer to a constant. lead and tail |
601 | | are pointers to constants. */ |
602 | 2.84k | const char *re = NULL; |
603 | 2.84k | const char *lead = ""; |
604 | 2.84k | const char *tail = ""; |
605 | | |
606 | 2.84k | if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) { |
607 | | /* Real part is +0: just output the imaginary part and do not |
608 | | include parens. */ |
609 | 2.84k | re = ""; |
610 | 2.84k | im = PyOS_double_to_string(v->cval.imag, format_code, |
611 | 2.84k | precision, 0, NULL); |
612 | 2.84k | if (!im) { |
613 | 0 | PyErr_NoMemory(); |
614 | 0 | goto done; |
615 | 0 | } |
616 | 2.84k | } else { |
617 | | /* Format imaginary part with sign, real part without. Include |
618 | | parens in the result. */ |
619 | 0 | pre = PyOS_double_to_string(v->cval.real, format_code, |
620 | 0 | precision, 0, NULL); |
621 | 0 | if (!pre) { |
622 | 0 | PyErr_NoMemory(); |
623 | 0 | goto done; |
624 | 0 | } |
625 | 0 | re = pre; |
626 | |
|
627 | 0 | im = PyOS_double_to_string(v->cval.imag, format_code, |
628 | 0 | precision, Py_DTSF_SIGN, NULL); |
629 | 0 | if (!im) { |
630 | 0 | PyErr_NoMemory(); |
631 | 0 | goto done; |
632 | 0 | } |
633 | 0 | lead = "("; |
634 | 0 | tail = ")"; |
635 | 0 | } |
636 | 2.84k | result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail); |
637 | 2.84k | done: |
638 | 2.84k | PyMem_Free(im); |
639 | 2.84k | PyMem_Free(pre); |
640 | | |
641 | 2.84k | return result; |
642 | 2.84k | } |
643 | | |
644 | | static Py_hash_t |
645 | | complex_hash(PyObject *op) |
646 | 3 | { |
647 | 3 | Py_uhash_t hashreal, hashimag, combined; |
648 | 3 | PyComplexObject *v = _PyComplexObject_CAST(op); |
649 | 3 | hashreal = (Py_uhash_t)_Py_HashDouble(op, v->cval.real); |
650 | 3 | if (hashreal == (Py_uhash_t)-1) |
651 | 0 | return -1; |
652 | 3 | hashimag = (Py_uhash_t)_Py_HashDouble(op, v->cval.imag); |
653 | 3 | if (hashimag == (Py_uhash_t)-1) |
654 | 0 | return -1; |
655 | | /* Note: if the imaginary part is 0, hashimag is 0 now, |
656 | | * so the following returns hashreal unchanged. This is |
657 | | * important because numbers of different types that |
658 | | * compare equal must have the same hash value, so that |
659 | | * hash(x + 0*j) must equal hash(x). |
660 | | */ |
661 | 3 | combined = hashreal + PyHASH_IMAG * hashimag; |
662 | 3 | if (combined == (Py_uhash_t)-1) |
663 | 0 | combined = (Py_uhash_t)-2; |
664 | 3 | return (Py_hash_t)combined; |
665 | 3 | } |
666 | | |
667 | | /* This macro may return! */ |
668 | | #define TO_COMPLEX(obj, c) \ |
669 | 0 | if (PyComplex_Check(obj)) \ |
670 | 0 | c = ((PyComplexObject *)(obj))->cval; \ |
671 | 0 | else if (real_to_complex(&(obj), &(c)) < 0) \ |
672 | 0 | return (obj) |
673 | | |
674 | | static int |
675 | | real_to_double(PyObject **pobj, double *dbl) |
676 | 0 | { |
677 | 0 | PyObject *obj = *pobj; |
678 | |
|
679 | 0 | if (PyFloat_Check(obj)) { |
680 | 0 | *dbl = PyFloat_AS_DOUBLE(obj); |
681 | 0 | } |
682 | 0 | else if (_Py_convert_int_to_double(pobj, dbl) < 0) { |
683 | 0 | return -1; |
684 | 0 | } |
685 | 0 | return 0; |
686 | 0 | } |
687 | | |
688 | | static int |
689 | | real_to_complex(PyObject **pobj, Py_complex *pc) |
690 | 0 | { |
691 | 0 | pc->imag = 0.0; |
692 | 0 | return real_to_double(pobj, &(pc->real)); |
693 | 0 | } |
694 | | |
695 | | /* Complex arithmetic rules implement special mixed-mode case where combining |
696 | | a pure-real (float or int) value and a complex value is performed directly |
697 | | without first coercing the real value to a complex value. |
698 | | |
699 | | Let us consider the addition as an example, assuming that ints are implicitly |
700 | | converted to floats. We have the following rules (up to variants with changed |
701 | | order of operands): |
702 | | |
703 | | complex(a, b) + complex(c, d) = complex(a + c, b + d) |
704 | | float(a) + complex(b, c) = complex(a + b, c) |
705 | | |
706 | | Similar rules are implemented for subtraction, multiplication and division. |
707 | | See C11's Annex G, sections G.5.1 and G.5.2. |
708 | | */ |
709 | | |
710 | | #define COMPLEX_BINOP(NAME, FUNC) \ |
711 | | static PyObject * \ |
712 | | complex_##NAME(PyObject *v, PyObject *w) \ |
713 | 0 | { \ |
714 | 0 | Py_complex a; \ |
715 | 0 | errno = 0; \ |
716 | 0 | if (PyComplex_Check(w)) { \ |
717 | 0 | Py_complex b = ((PyComplexObject *)w)->cval; \ |
718 | 0 | if (PyComplex_Check(v)) { \ |
719 | 0 | a = ((PyComplexObject *)v)->cval; \ |
720 | 0 | a = _Py_c_##FUNC(a, b); \ |
721 | 0 | } \ |
722 | 0 | else if (real_to_double(&v, &a.real) < 0) { \ |
723 | 0 | return v; \ |
724 | 0 | } \ |
725 | 0 | else { \ |
726 | 0 | a = _Py_rc_##FUNC(a.real, b); \ |
727 | 0 | } \ |
728 | 0 | } \ |
729 | 0 | else if (!PyComplex_Check(v)) { \ |
730 | 0 | Py_RETURN_NOTIMPLEMENTED; \ |
731 | 0 | } \ |
732 | 0 | else { \ |
733 | 0 | a = ((PyComplexObject *)v)->cval; \ |
734 | 0 | double b; \ |
735 | 0 | if (real_to_double(&w, &b) < 0) { \ |
736 | 0 | return w; \ |
737 | 0 | } \ |
738 | 0 | a = _Py_cr_##FUNC(a, b); \ |
739 | 0 | } \ |
740 | 0 | if (errno == EDOM) { \ |
741 | 0 | PyErr_SetString(PyExc_ZeroDivisionError, \ |
742 | 0 | "division by zero"); \ |
743 | 0 | return NULL; \ |
744 | 0 | } \ |
745 | 0 | return PyComplex_FromCComplex(a); \ |
746 | 0 | } |
747 | | |
748 | 0 | COMPLEX_BINOP(add, sum) |
749 | 0 | COMPLEX_BINOP(mul, prod) |
750 | 0 | COMPLEX_BINOP(sub, diff) |
751 | 0 | COMPLEX_BINOP(div, quot) |
752 | | |
753 | | static PyObject * |
754 | | complex_pow(PyObject *v, PyObject *w, PyObject *z) |
755 | 0 | { |
756 | 0 | Py_complex p; |
757 | 0 | Py_complex a, b; |
758 | 0 | TO_COMPLEX(v, a); |
759 | 0 | TO_COMPLEX(w, b); |
760 | | |
761 | 0 | if (z != Py_None) { |
762 | 0 | PyErr_SetString(PyExc_ValueError, "complex modulo"); |
763 | 0 | return NULL; |
764 | 0 | } |
765 | 0 | errno = 0; |
766 | | // Check whether the exponent has a small integer value, and if so use |
767 | | // a faster and more accurate algorithm. |
768 | 0 | if (b.imag == 0.0 && b.real == floor(b.real) |
769 | 0 | && fabs(b.real) <= INT_EXP_CUTOFF) |
770 | 0 | { |
771 | 0 | p = c_powi(a, (long)b.real); |
772 | 0 | if (isfinite(a.real) && isfinite(a.imag)) { |
773 | 0 | _Py_ADJUST_ERANGE2(p.real, p.imag); |
774 | 0 | } |
775 | 0 | } |
776 | 0 | else { |
777 | 0 | p = _Py_c_pow(a, b); |
778 | 0 | } |
779 | |
|
780 | 0 | if (errno == EDOM) { |
781 | 0 | PyErr_SetString(PyExc_ZeroDivisionError, |
782 | 0 | "zero to a negative or complex power"); |
783 | 0 | return NULL; |
784 | 0 | } |
785 | 0 | else if (errno == ERANGE) { |
786 | 0 | PyErr_SetString(PyExc_OverflowError, |
787 | 0 | "complex exponentiation"); |
788 | 0 | return NULL; |
789 | 0 | } |
790 | 0 | return PyComplex_FromCComplex(p); |
791 | 0 | } |
792 | | |
793 | | static PyObject * |
794 | | complex_neg(PyObject *op) |
795 | 0 | { |
796 | 0 | PyComplexObject *v = _PyComplexObject_CAST(op); |
797 | 0 | Py_complex neg; |
798 | 0 | neg.real = -v->cval.real; |
799 | 0 | neg.imag = -v->cval.imag; |
800 | 0 | return PyComplex_FromCComplex(neg); |
801 | 0 | } |
802 | | |
803 | | static PyObject * |
804 | | complex_pos(PyObject *op) |
805 | 0 | { |
806 | 0 | PyComplexObject *v = _PyComplexObject_CAST(op); |
807 | 0 | if (PyComplex_CheckExact(v)) { |
808 | 0 | return Py_NewRef(v); |
809 | 0 | } |
810 | 0 | return PyComplex_FromCComplex(v->cval); |
811 | 0 | } |
812 | | |
813 | | static PyObject * |
814 | | complex_abs(PyObject *op) |
815 | 0 | { |
816 | 0 | PyComplexObject *v = _PyComplexObject_CAST(op); |
817 | 0 | double result; |
818 | |
|
819 | 0 | errno = 0; |
820 | 0 | result = _Py_c_abs(v->cval); |
821 | 0 | if (errno == ERANGE) { |
822 | 0 | PyErr_SetString(PyExc_OverflowError, |
823 | 0 | "absolute value too large"); |
824 | 0 | return NULL; |
825 | 0 | } |
826 | 0 | return PyFloat_FromDouble(result); |
827 | 0 | } |
828 | | |
829 | | static int |
830 | | complex_bool(PyObject *op) |
831 | 0 | { |
832 | 0 | PyComplexObject *v = _PyComplexObject_CAST(op); |
833 | 0 | return v->cval.real != 0.0 || v->cval.imag != 0.0; |
834 | 0 | } |
835 | | |
836 | | static PyObject * |
837 | | complex_richcompare(PyObject *v, PyObject *w, int op) |
838 | 0 | { |
839 | 0 | PyObject *res; |
840 | 0 | Py_complex i; |
841 | 0 | int equal; |
842 | |
|
843 | 0 | if (op != Py_EQ && op != Py_NE) { |
844 | 0 | goto Unimplemented; |
845 | 0 | } |
846 | | |
847 | 0 | assert(PyComplex_Check(v)); |
848 | 0 | TO_COMPLEX(v, i); |
849 | | |
850 | 0 | if (PyLong_Check(w)) { |
851 | | /* Check for 0.0 imaginary part first to avoid the rich |
852 | | * comparison when possible. |
853 | | */ |
854 | 0 | if (i.imag == 0.0) { |
855 | 0 | PyObject *j, *sub_res; |
856 | 0 | j = PyFloat_FromDouble(i.real); |
857 | 0 | if (j == NULL) |
858 | 0 | return NULL; |
859 | | |
860 | 0 | sub_res = PyObject_RichCompare(j, w, op); |
861 | 0 | Py_DECREF(j); |
862 | 0 | return sub_res; |
863 | 0 | } |
864 | 0 | else { |
865 | 0 | equal = 0; |
866 | 0 | } |
867 | 0 | } |
868 | 0 | else if (PyFloat_Check(w)) { |
869 | 0 | equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0); |
870 | 0 | } |
871 | 0 | else if (PyComplex_Check(w)) { |
872 | 0 | Py_complex j; |
873 | |
|
874 | 0 | TO_COMPLEX(w, j); |
875 | 0 | equal = (i.real == j.real && i.imag == j.imag); |
876 | 0 | } |
877 | 0 | else { |
878 | 0 | goto Unimplemented; |
879 | 0 | } |
880 | | |
881 | 0 | if (equal == (op == Py_EQ)) |
882 | 0 | res = Py_True; |
883 | 0 | else |
884 | 0 | res = Py_False; |
885 | |
|
886 | 0 | return Py_NewRef(res); |
887 | | |
888 | 0 | Unimplemented: |
889 | 0 | Py_RETURN_NOTIMPLEMENTED; |
890 | 0 | } |
891 | | |
892 | | /*[clinic input] |
893 | | @permit_long_summary |
894 | | complex.conjugate |
895 | | |
896 | | Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j. |
897 | | [clinic start generated code]*/ |
898 | | |
899 | | static PyObject * |
900 | | complex_conjugate_impl(PyComplexObject *self) |
901 | | /*[clinic end generated code: output=5059ef162edfc68e input=71b8ab003e1cec95]*/ |
902 | 0 | { |
903 | 0 | Py_complex c = self->cval; |
904 | 0 | c.imag = -c.imag; |
905 | 0 | return PyComplex_FromCComplex(c); |
906 | 0 | } |
907 | | |
908 | | /*[clinic input] |
909 | | complex.__getnewargs__ |
910 | | |
911 | | [clinic start generated code]*/ |
912 | | |
913 | | static PyObject * |
914 | | complex___getnewargs___impl(PyComplexObject *self) |
915 | | /*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/ |
916 | 0 | { |
917 | 0 | Py_complex c = self->cval; |
918 | 0 | return Py_BuildValue("(dd)", c.real, c.imag); |
919 | 0 | } |
920 | | |
921 | | |
922 | | /*[clinic input] |
923 | | complex.__format__ |
924 | | |
925 | | format_spec: unicode |
926 | | / |
927 | | |
928 | | Convert to a string according to format_spec. |
929 | | [clinic start generated code]*/ |
930 | | |
931 | | static PyObject * |
932 | | complex___format___impl(PyComplexObject *self, PyObject *format_spec) |
933 | | /*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/ |
934 | 0 | { |
935 | 0 | _PyUnicodeWriter writer; |
936 | 0 | int ret; |
937 | 0 | _PyUnicodeWriter_Init(&writer); |
938 | 0 | ret = _PyComplex_FormatAdvancedWriter( |
939 | 0 | &writer, |
940 | 0 | (PyObject *)self, |
941 | 0 | format_spec, 0, PyUnicode_GET_LENGTH(format_spec)); |
942 | 0 | if (ret == -1) { |
943 | 0 | _PyUnicodeWriter_Dealloc(&writer); |
944 | 0 | return NULL; |
945 | 0 | } |
946 | 0 | return _PyUnicodeWriter_Finish(&writer); |
947 | 0 | } |
948 | | |
949 | | /*[clinic input] |
950 | | complex.__complex__ |
951 | | |
952 | | Convert this value to exact type complex. |
953 | | [clinic start generated code]*/ |
954 | | |
955 | | static PyObject * |
956 | | complex___complex___impl(PyComplexObject *self) |
957 | | /*[clinic end generated code: output=e6b35ba3d275dc9c input=3589ada9d27db854]*/ |
958 | 0 | { |
959 | 0 | if (PyComplex_CheckExact(self)) { |
960 | 0 | return Py_NewRef(self); |
961 | 0 | } |
962 | 0 | else { |
963 | 0 | return PyComplex_FromCComplex(self->cval); |
964 | 0 | } |
965 | 0 | } |
966 | | |
967 | | |
968 | | static PyObject * |
969 | | complex_from_string_inner(const char *s, Py_ssize_t len, void *type) |
970 | 0 | { |
971 | 0 | double x=0.0, y=0.0, z; |
972 | 0 | int got_bracket=0; |
973 | 0 | const char *start; |
974 | 0 | char *end; |
975 | | |
976 | | /* position on first nonblank */ |
977 | 0 | start = s; |
978 | 0 | while (Py_ISSPACE(*s)) |
979 | 0 | s++; |
980 | 0 | if (*s == '(') { |
981 | | /* Skip over possible bracket from repr(). */ |
982 | 0 | got_bracket = 1; |
983 | 0 | s++; |
984 | 0 | while (Py_ISSPACE(*s)) |
985 | 0 | s++; |
986 | 0 | } |
987 | | |
988 | | /* a valid complex string usually takes one of the three forms: |
989 | | |
990 | | <float> - real part only |
991 | | <float>j - imaginary part only |
992 | | <float><signed-float>j - real and imaginary parts |
993 | | |
994 | | where <float> represents any numeric string that's accepted by the |
995 | | float constructor (including 'nan', 'inf', 'infinity', etc.), and |
996 | | <signed-float> is any string of the form <float> whose first |
997 | | character is '+' or '-'. |
998 | | |
999 | | For backwards compatibility, the extra forms |
1000 | | |
1001 | | <float><sign>j |
1002 | | <sign>j |
1003 | | j |
1004 | | |
1005 | | are also accepted, though support for these forms may be removed from |
1006 | | a future version of Python. |
1007 | | */ |
1008 | | |
1009 | | /* first look for forms starting with <float> */ |
1010 | 0 | z = PyOS_string_to_double(s, &end, NULL); |
1011 | 0 | if (z == -1.0 && PyErr_Occurred()) { |
1012 | 0 | if (PyErr_ExceptionMatches(PyExc_ValueError)) |
1013 | 0 | PyErr_Clear(); |
1014 | 0 | else |
1015 | 0 | return NULL; |
1016 | 0 | } |
1017 | 0 | if (end != s) { |
1018 | | /* all 4 forms starting with <float> land here */ |
1019 | 0 | s = end; |
1020 | 0 | if (*s == '+' || *s == '-') { |
1021 | | /* <float><signed-float>j | <float><sign>j */ |
1022 | 0 | x = z; |
1023 | 0 | y = PyOS_string_to_double(s, &end, NULL); |
1024 | 0 | if (y == -1.0 && PyErr_Occurred()) { |
1025 | 0 | if (PyErr_ExceptionMatches(PyExc_ValueError)) |
1026 | 0 | PyErr_Clear(); |
1027 | 0 | else |
1028 | 0 | return NULL; |
1029 | 0 | } |
1030 | 0 | if (end != s) |
1031 | | /* <float><signed-float>j */ |
1032 | 0 | s = end; |
1033 | 0 | else { |
1034 | | /* <float><sign>j */ |
1035 | 0 | y = *s == '+' ? 1.0 : -1.0; |
1036 | 0 | s++; |
1037 | 0 | } |
1038 | 0 | if (!(*s == 'j' || *s == 'J')) |
1039 | 0 | goto parse_error; |
1040 | 0 | s++; |
1041 | 0 | } |
1042 | 0 | else if (*s == 'j' || *s == 'J') { |
1043 | | /* <float>j */ |
1044 | 0 | s++; |
1045 | 0 | y = z; |
1046 | 0 | } |
1047 | 0 | else |
1048 | | /* <float> */ |
1049 | 0 | x = z; |
1050 | 0 | } |
1051 | 0 | else { |
1052 | | /* not starting with <float>; must be <sign>j or j */ |
1053 | 0 | if (*s == '+' || *s == '-') { |
1054 | | /* <sign>j */ |
1055 | 0 | y = *s == '+' ? 1.0 : -1.0; |
1056 | 0 | s++; |
1057 | 0 | } |
1058 | 0 | else |
1059 | | /* j */ |
1060 | 0 | y = 1.0; |
1061 | 0 | if (!(*s == 'j' || *s == 'J')) |
1062 | 0 | goto parse_error; |
1063 | 0 | s++; |
1064 | 0 | } |
1065 | | |
1066 | | /* trailing whitespace and closing bracket */ |
1067 | 0 | while (Py_ISSPACE(*s)) |
1068 | 0 | s++; |
1069 | 0 | if (got_bracket) { |
1070 | | /* if there was an opening parenthesis, then the corresponding |
1071 | | closing parenthesis should be right here */ |
1072 | 0 | if (*s != ')') |
1073 | 0 | goto parse_error; |
1074 | 0 | s++; |
1075 | 0 | while (Py_ISSPACE(*s)) |
1076 | 0 | s++; |
1077 | 0 | } |
1078 | | |
1079 | | /* we should now be at the end of the string */ |
1080 | 0 | if (s-start != len) |
1081 | 0 | goto parse_error; |
1082 | | |
1083 | 0 | return complex_subtype_from_doubles(_PyType_CAST(type), x, y); |
1084 | | |
1085 | 0 | parse_error: |
1086 | 0 | PyErr_SetString(PyExc_ValueError, |
1087 | 0 | "complex() arg is a malformed string"); |
1088 | 0 | return NULL; |
1089 | 0 | } |
1090 | | |
1091 | | static PyObject * |
1092 | | complex_subtype_from_string(PyTypeObject *type, PyObject *v) |
1093 | 0 | { |
1094 | 0 | const char *s; |
1095 | 0 | PyObject *s_buffer = NULL, *result = NULL; |
1096 | 0 | Py_ssize_t len; |
1097 | |
|
1098 | 0 | if (PyUnicode_Check(v)) { |
1099 | 0 | s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v); |
1100 | 0 | if (s_buffer == NULL) { |
1101 | 0 | return NULL; |
1102 | 0 | } |
1103 | 0 | assert(PyUnicode_IS_ASCII(s_buffer)); |
1104 | | /* Simply get a pointer to existing ASCII characters. */ |
1105 | 0 | s = PyUnicode_AsUTF8AndSize(s_buffer, &len); |
1106 | 0 | assert(s != NULL); |
1107 | 0 | } |
1108 | 0 | else { |
1109 | 0 | PyErr_Format(PyExc_TypeError, |
1110 | 0 | "complex() argument must be a string or a number, not %T", |
1111 | 0 | v); |
1112 | 0 | return NULL; |
1113 | 0 | } |
1114 | | |
1115 | 0 | result = _Py_string_to_number_with_underscores(s, len, "complex", v, type, |
1116 | 0 | complex_from_string_inner); |
1117 | 0 | Py_DECREF(s_buffer); |
1118 | 0 | return result; |
1119 | 0 | } |
1120 | | |
1121 | | /* The constructor should only accept a string as a positional argument, |
1122 | | * not as by the 'real' keyword. But Argument Clinic does not allow |
1123 | | * to distinguish between argument passed positionally and by keyword. |
1124 | | * So the constructor must be split into two parts: actual_complex_new() |
1125 | | * handles the case of no arguments and one positional argument, and calls |
1126 | | * complex_new(), implemented with Argument Clinic, to handle the remaining |
1127 | | * cases: 'real' and 'imag' arguments. This separation is well suited |
1128 | | * for different constructor roles: converting a string or number to a complex |
1129 | | * number and constructing a complex number from real and imaginary parts. |
1130 | | */ |
1131 | | static PyObject * |
1132 | | actual_complex_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) |
1133 | 0 | { |
1134 | 0 | PyObject *res = NULL; |
1135 | 0 | PyNumberMethods *nbr; |
1136 | |
|
1137 | 0 | if (PyTuple_GET_SIZE(args) > 1 || (kwargs != NULL && PyDict_GET_SIZE(kwargs))) { |
1138 | 0 | return complex_new(type, args, kwargs); |
1139 | 0 | } |
1140 | 0 | if (!PyTuple_GET_SIZE(args)) { |
1141 | 0 | return complex_subtype_from_doubles(type, 0, 0); |
1142 | 0 | } |
1143 | | |
1144 | 0 | PyObject *arg = PyTuple_GET_ITEM(args, 0); |
1145 | | /* Special-case for a single argument when type(arg) is complex. */ |
1146 | 0 | if (PyComplex_CheckExact(arg) && type == &PyComplex_Type) { |
1147 | | /* Note that we can't know whether it's safe to return |
1148 | | a complex *subclass* instance as-is, hence the restriction |
1149 | | to exact complexes here. If either the input or the |
1150 | | output is a complex subclass, it will be handled below |
1151 | | as a non-orthogonal vector. */ |
1152 | 0 | return Py_NewRef(arg); |
1153 | 0 | } |
1154 | 0 | if (PyUnicode_Check(arg)) { |
1155 | 0 | return complex_subtype_from_string(type, arg); |
1156 | 0 | } |
1157 | 0 | PyObject *tmp = try_complex_special_method(arg); |
1158 | 0 | if (tmp) { |
1159 | 0 | Py_complex c = ((PyComplexObject*)tmp)->cval; |
1160 | 0 | res = complex_subtype_from_doubles(type, c.real, c.imag); |
1161 | 0 | Py_DECREF(tmp); |
1162 | 0 | } |
1163 | 0 | else if (PyErr_Occurred()) { |
1164 | 0 | return NULL; |
1165 | 0 | } |
1166 | 0 | else if (PyComplex_Check(arg)) { |
1167 | | /* Note that if arg is of a complex subtype, we're only |
1168 | | retaining its real & imag parts here, and the return |
1169 | | value is (properly) of the builtin complex type. */ |
1170 | 0 | Py_complex c = ((PyComplexObject*)arg)->cval; |
1171 | 0 | res = complex_subtype_from_doubles(type, c.real, c.imag); |
1172 | 0 | } |
1173 | 0 | else if ((nbr = Py_TYPE(arg)->tp_as_number) != NULL && |
1174 | 0 | (nbr->nb_float != NULL || nbr->nb_index != NULL)) |
1175 | 0 | { |
1176 | | /* The argument really is entirely real, and contributes |
1177 | | nothing in the imaginary direction. |
1178 | | Just treat it as a double. */ |
1179 | 0 | double r = PyFloat_AsDouble(arg); |
1180 | 0 | if (r != -1.0 || !PyErr_Occurred()) { |
1181 | 0 | res = complex_subtype_from_doubles(type, r, 0); |
1182 | 0 | } |
1183 | 0 | } |
1184 | 0 | else { |
1185 | 0 | PyErr_Format(PyExc_TypeError, |
1186 | 0 | "complex() argument must be a string or a number, not %T", |
1187 | 0 | arg); |
1188 | 0 | } |
1189 | 0 | return res; |
1190 | 0 | } |
1191 | | |
1192 | | /*[clinic input] |
1193 | | @classmethod |
1194 | | complex.__new__ as complex_new |
1195 | | real as r: object(c_default="NULL") = 0 |
1196 | | imag as i: object(c_default="NULL") = 0 |
1197 | | |
1198 | | Create a complex number from a string or numbers. |
1199 | | |
1200 | | If a string is given, parse it as a complex number. |
1201 | | If a single number is given, convert it to a complex number. |
1202 | | If the 'real' or 'imag' arguments are given, create a complex number |
1203 | | with the specified real and imaginary components. |
1204 | | [clinic start generated code]*/ |
1205 | | |
1206 | | static PyObject * |
1207 | | complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i) |
1208 | | /*[clinic end generated code: output=b6c7dd577b537dc1 input=ff4268dc540958a4]*/ |
1209 | 0 | { |
1210 | 0 | PyObject *tmp; |
1211 | 0 | PyNumberMethods *nbr, *nbi = NULL; |
1212 | 0 | Py_complex cr, ci; |
1213 | 0 | int own_r = 0; |
1214 | 0 | int cr_is_complex = 0; |
1215 | 0 | int ci_is_complex = 0; |
1216 | |
|
1217 | 0 | if (r == NULL) { |
1218 | 0 | r = _PyLong_GetZero(); |
1219 | 0 | } |
1220 | 0 | PyObject *orig_r = r; |
1221 | | |
1222 | | /* DEPRECATED: The call of try_complex_special_method() for the "real" |
1223 | | * part will be dropped after the end of the deprecation period. */ |
1224 | 0 | tmp = try_complex_special_method(r); |
1225 | 0 | if (tmp) { |
1226 | 0 | r = tmp; |
1227 | 0 | own_r = 1; |
1228 | 0 | } |
1229 | 0 | else if (PyErr_Occurred()) { |
1230 | 0 | return NULL; |
1231 | 0 | } |
1232 | | |
1233 | 0 | nbr = Py_TYPE(r)->tp_as_number; |
1234 | 0 | if (nbr == NULL || |
1235 | 0 | (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r))) |
1236 | 0 | { |
1237 | 0 | PyErr_Format(PyExc_TypeError, |
1238 | 0 | "complex() argument 'real' must be a real number, not %T", |
1239 | 0 | r); |
1240 | 0 | if (own_r) { |
1241 | 0 | Py_DECREF(r); |
1242 | 0 | } |
1243 | 0 | return NULL; |
1244 | 0 | } |
1245 | 0 | if (i != NULL) { |
1246 | 0 | nbi = Py_TYPE(i)->tp_as_number; |
1247 | 0 | if (nbi == NULL || |
1248 | 0 | (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i))) |
1249 | 0 | { |
1250 | 0 | PyErr_Format(PyExc_TypeError, |
1251 | 0 | "complex() argument 'imag' must be a real number, not %T", |
1252 | 0 | i); |
1253 | 0 | if (own_r) { |
1254 | 0 | Py_DECREF(r); |
1255 | 0 | } |
1256 | 0 | return NULL; |
1257 | 0 | } |
1258 | 0 | } |
1259 | | |
1260 | | /* If we get this far, then the "real" and "imag" parts should |
1261 | | both be treated as numbers, and the constructor should return a |
1262 | | complex number equal to (real + imag*1j). |
1263 | | |
1264 | | The following is DEPRECATED: |
1265 | | Note that we do NOT assume the input to already be in canonical |
1266 | | form; the "real" and "imag" parts might themselves be complex |
1267 | | numbers, which slightly complicates the code below. */ |
1268 | 0 | if (PyComplex_Check(r)) { |
1269 | | /* Note that if r is of a complex subtype, we're only |
1270 | | retaining its real & imag parts here, and the return |
1271 | | value is (properly) of the builtin complex type. */ |
1272 | 0 | cr = ((PyComplexObject*)r)->cval; |
1273 | 0 | cr_is_complex = 1; |
1274 | 0 | if (own_r) { |
1275 | | /* r was a newly created complex number, rather |
1276 | | than the original "real" argument. */ |
1277 | 0 | Py_DECREF(r); |
1278 | 0 | } |
1279 | 0 | nbr = Py_TYPE(orig_r)->tp_as_number; |
1280 | 0 | if (nbr == NULL || |
1281 | 0 | (nbr->nb_float == NULL && nbr->nb_index == NULL)) |
1282 | 0 | { |
1283 | 0 | if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, |
1284 | 0 | "complex() argument 'real' must be a real number, not %T", |
1285 | 0 | orig_r)) { |
1286 | 0 | return NULL; |
1287 | 0 | } |
1288 | 0 | } |
1289 | 0 | } |
1290 | 0 | else { |
1291 | | /* The "real" part really is entirely real, and contributes |
1292 | | nothing in the imaginary direction. |
1293 | | Just treat it as a double. */ |
1294 | 0 | tmp = PyNumber_Float(r); |
1295 | 0 | assert(!own_r); |
1296 | 0 | if (tmp == NULL) |
1297 | 0 | return NULL; |
1298 | 0 | assert(PyFloat_Check(tmp)); |
1299 | 0 | cr.real = PyFloat_AsDouble(tmp); |
1300 | 0 | cr.imag = 0.0; |
1301 | 0 | Py_DECREF(tmp); |
1302 | 0 | } |
1303 | 0 | if (i == NULL) { |
1304 | 0 | ci.real = cr.imag; |
1305 | 0 | } |
1306 | 0 | else if (PyComplex_Check(i)) { |
1307 | 0 | if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, |
1308 | 0 | "complex() argument 'imag' must be a real number, not %T", |
1309 | 0 | i)) { |
1310 | 0 | return NULL; |
1311 | 0 | } |
1312 | 0 | ci = ((PyComplexObject*)i)->cval; |
1313 | 0 | ci_is_complex = 1; |
1314 | 0 | } else { |
1315 | | /* The "imag" part really is entirely imaginary, and |
1316 | | contributes nothing in the real direction. |
1317 | | Just treat it as a double. */ |
1318 | 0 | tmp = PyNumber_Float(i); |
1319 | 0 | if (tmp == NULL) |
1320 | 0 | return NULL; |
1321 | 0 | ci.real = PyFloat_AsDouble(tmp); |
1322 | 0 | Py_DECREF(tmp); |
1323 | 0 | } |
1324 | | /* If the input was in canonical form, then the "real" and "imag" |
1325 | | parts are real numbers, so that ci.imag and cr.imag are zero. |
1326 | | We need this correction in case they were not real numbers. */ |
1327 | | |
1328 | 0 | if (ci_is_complex) { |
1329 | 0 | cr.real -= ci.imag; |
1330 | 0 | } |
1331 | 0 | if (cr_is_complex && i != NULL) { |
1332 | 0 | ci.real += cr.imag; |
1333 | 0 | } |
1334 | 0 | return complex_subtype_from_doubles(type, cr.real, ci.real); |
1335 | 0 | } |
1336 | | |
1337 | | /*[clinic input] |
1338 | | @classmethod |
1339 | | complex.from_number |
1340 | | |
1341 | | number: object |
1342 | | / |
1343 | | |
1344 | | Convert number to a complex floating-point number. |
1345 | | [clinic start generated code]*/ |
1346 | | |
1347 | | static PyObject * |
1348 | | complex_from_number_impl(PyTypeObject *type, PyObject *number) |
1349 | | /*[clinic end generated code: output=7248bb593e1871e1 input=3f8bdd3a2bc3facd]*/ |
1350 | 0 | { |
1351 | 0 | if (PyComplex_CheckExact(number) && type == &PyComplex_Type) { |
1352 | 0 | Py_INCREF(number); |
1353 | 0 | return number; |
1354 | 0 | } |
1355 | 0 | Py_complex cv = PyComplex_AsCComplex(number); |
1356 | 0 | if (cv.real == -1.0 && PyErr_Occurred()) { |
1357 | 0 | return NULL; |
1358 | 0 | } |
1359 | 0 | PyObject *result = PyComplex_FromCComplex(cv); |
1360 | 0 | if (type != &PyComplex_Type && result != NULL) { |
1361 | 0 | Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result)); |
1362 | 0 | } |
1363 | 0 | return result; |
1364 | 0 | } |
1365 | | |
1366 | | static PyMethodDef complex_methods[] = { |
1367 | | COMPLEX_FROM_NUMBER_METHODDEF |
1368 | | COMPLEX_CONJUGATE_METHODDEF |
1369 | | COMPLEX___COMPLEX___METHODDEF |
1370 | | COMPLEX___GETNEWARGS___METHODDEF |
1371 | | COMPLEX___FORMAT___METHODDEF |
1372 | | {NULL, NULL} /* sentinel */ |
1373 | | }; |
1374 | | |
1375 | | static PyMemberDef complex_members[] = { |
1376 | | {"real", Py_T_DOUBLE, offsetof(PyComplexObject, cval.real), Py_READONLY, |
1377 | | "the real part of a complex number"}, |
1378 | | {"imag", Py_T_DOUBLE, offsetof(PyComplexObject, cval.imag), Py_READONLY, |
1379 | | "the imaginary part of a complex number"}, |
1380 | | {0}, |
1381 | | }; |
1382 | | |
1383 | | static PyNumberMethods complex_as_number = { |
1384 | | complex_add, /* nb_add */ |
1385 | | complex_sub, /* nb_subtract */ |
1386 | | complex_mul, /* nb_multiply */ |
1387 | | 0, /* nb_remainder */ |
1388 | | 0, /* nb_divmod */ |
1389 | | complex_pow, /* nb_power */ |
1390 | | complex_neg, /* nb_negative */ |
1391 | | complex_pos, /* nb_positive */ |
1392 | | complex_abs, /* nb_absolute */ |
1393 | | complex_bool, /* nb_bool */ |
1394 | | 0, /* nb_invert */ |
1395 | | 0, /* nb_lshift */ |
1396 | | 0, /* nb_rshift */ |
1397 | | 0, /* nb_and */ |
1398 | | 0, /* nb_xor */ |
1399 | | 0, /* nb_or */ |
1400 | | 0, /* nb_int */ |
1401 | | 0, /* nb_reserved */ |
1402 | | 0, /* nb_float */ |
1403 | | 0, /* nb_inplace_add */ |
1404 | | 0, /* nb_inplace_subtract */ |
1405 | | 0, /* nb_inplace_multiply*/ |
1406 | | 0, /* nb_inplace_remainder */ |
1407 | | 0, /* nb_inplace_power */ |
1408 | | 0, /* nb_inplace_lshift */ |
1409 | | 0, /* nb_inplace_rshift */ |
1410 | | 0, /* nb_inplace_and */ |
1411 | | 0, /* nb_inplace_xor */ |
1412 | | 0, /* nb_inplace_or */ |
1413 | | 0, /* nb_floor_divide */ |
1414 | | complex_div, /* nb_true_divide */ |
1415 | | 0, /* nb_inplace_floor_divide */ |
1416 | | 0, /* nb_inplace_true_divide */ |
1417 | | }; |
1418 | | |
1419 | | PyTypeObject PyComplex_Type = { |
1420 | | PyVarObject_HEAD_INIT(&PyType_Type, 0) |
1421 | | "complex", |
1422 | | sizeof(PyComplexObject), |
1423 | | 0, |
1424 | | complex_dealloc, /* tp_dealloc */ |
1425 | | 0, /* tp_vectorcall_offset */ |
1426 | | 0, /* tp_getattr */ |
1427 | | 0, /* tp_setattr */ |
1428 | | 0, /* tp_as_async */ |
1429 | | complex_repr, /* tp_repr */ |
1430 | | &complex_as_number, /* tp_as_number */ |
1431 | | 0, /* tp_as_sequence */ |
1432 | | 0, /* tp_as_mapping */ |
1433 | | complex_hash, /* tp_hash */ |
1434 | | 0, /* tp_call */ |
1435 | | 0, /* tp_str */ |
1436 | | PyObject_GenericGetAttr, /* tp_getattro */ |
1437 | | 0, /* tp_setattro */ |
1438 | | 0, /* tp_as_buffer */ |
1439 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ |
1440 | | complex_new__doc__, /* tp_doc */ |
1441 | | 0, /* tp_traverse */ |
1442 | | 0, /* tp_clear */ |
1443 | | complex_richcompare, /* tp_richcompare */ |
1444 | | 0, /* tp_weaklistoffset */ |
1445 | | 0, /* tp_iter */ |
1446 | | 0, /* tp_iternext */ |
1447 | | complex_methods, /* tp_methods */ |
1448 | | complex_members, /* tp_members */ |
1449 | | 0, /* tp_getset */ |
1450 | | 0, /* tp_base */ |
1451 | | 0, /* tp_dict */ |
1452 | | 0, /* tp_descr_get */ |
1453 | | 0, /* tp_descr_set */ |
1454 | | 0, /* tp_dictoffset */ |
1455 | | 0, /* tp_init */ |
1456 | | PyType_GenericAlloc, /* tp_alloc */ |
1457 | | actual_complex_new, /* tp_new */ |
1458 | | PyObject_Free, /* tp_free */ |
1459 | | .tp_version_tag = _Py_TYPE_VERSION_COMPLEX, |
1460 | | }; |