Line data Source code
1 :
2 : /* Complex object implementation */
3 :
4 : /* Borrows heavily from floatobject.c */
5 :
6 : /* Submitted by Jim Hugunin */
7 :
8 : #include "Python.h"
9 : #include "pycore_call.h" // _PyObject_CallNoArgs()
10 : #include "pycore_long.h" // _PyLong_GetZero()
11 : #include "pycore_object.h" // _PyObject_Init()
12 : #include "pycore_pymath.h" // _Py_ADJUST_ERANGE2()
13 : #include "structmember.h" // PyMemberDef
14 :
15 :
16 : /*[clinic input]
17 : class complex "PyComplexObject *" "&PyComplex_Type"
18 : [clinic start generated code]*/
19 : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
20 :
21 : #include "clinic/complexobject.c.h"
22 :
23 : /* elementary operations on complex numbers */
24 :
25 : static Py_complex c_1 = {1., 0.};
26 :
27 : Py_complex
28 747 : _Py_c_sum(Py_complex a, Py_complex b)
29 : {
30 : Py_complex r;
31 747 : r.real = a.real + b.real;
32 747 : r.imag = a.imag + b.imag;
33 747 : return r;
34 : }
35 :
36 : Py_complex
37 279 : _Py_c_diff(Py_complex a, Py_complex b)
38 : {
39 : Py_complex r;
40 279 : r.real = a.real - b.real;
41 279 : r.imag = a.imag - b.imag;
42 279 : return r;
43 : }
44 :
45 : Py_complex
46 232 : _Py_c_neg(Py_complex a)
47 : {
48 : Py_complex r;
49 232 : r.real = -a.real;
50 232 : r.imag = -a.imag;
51 232 : return r;
52 : }
53 :
54 : Py_complex
55 15405 : _Py_c_prod(Py_complex a, Py_complex b)
56 : {
57 : Py_complex r;
58 15405 : r.real = a.real*b.real - a.imag*b.imag;
59 15405 : r.imag = a.real*b.imag + a.imag*b.real;
60 15405 : return r;
61 : }
62 :
63 : /* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
64 : #ifdef _M_ARM64
65 : #pragma optimize("", off)
66 : #endif
67 : Py_complex
68 58663 : _Py_c_quot(Py_complex a, Py_complex b)
69 : {
70 : /******************************************************************
71 : This was the original algorithm. It's grossly prone to spurious
72 : overflow and underflow errors. It also merrily divides by 0 despite
73 : checking for that(!). The code still serves a doc purpose here, as
74 : the algorithm following is a simple by-cases transformation of this
75 : one:
76 :
77 : Py_complex r;
78 : double d = b.real*b.real + b.imag*b.imag;
79 : if (d == 0.)
80 : errno = EDOM;
81 : r.real = (a.real*b.real + a.imag*b.imag)/d;
82 : r.imag = (a.imag*b.real - a.real*b.imag)/d;
83 : return r;
84 : ******************************************************************/
85 :
86 : /* This algorithm is better, and is pretty obvious: first divide the
87 : * numerators and denominator by whichever of {b.real, b.imag} has
88 : * larger magnitude. The earliest reference I found was to CACM
89 : * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
90 : * University). As usual, though, we're still ignoring all IEEE
91 : * endcases.
92 : */
93 : Py_complex r; /* the result */
94 58663 : const double abs_breal = b.real < 0 ? -b.real : b.real;
95 58663 : const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
96 :
97 58663 : if (abs_breal >= abs_bimag) {
98 : /* divide tops and bottom by b.real */
99 34172 : if (abs_breal == 0.0) {
100 5 : errno = EDOM;
101 5 : r.real = r.imag = 0.0;
102 : }
103 : else {
104 34167 : const double ratio = b.imag / b.real;
105 34167 : const double denom = b.real + b.imag * ratio;
106 34167 : r.real = (a.real + a.imag * ratio) / denom;
107 34167 : r.imag = (a.imag - a.real * ratio) / denom;
108 : }
109 : }
110 24491 : else if (abs_bimag >= abs_breal) {
111 : /* divide tops and bottom by b.imag */
112 24452 : const double ratio = b.real / b.imag;
113 24452 : const double denom = b.real * ratio + b.imag;
114 24452 : assert(b.imag != 0.0);
115 24452 : r.real = (a.real * ratio + a.imag) / denom;
116 24452 : r.imag = (a.imag * ratio - a.real) / denom;
117 : }
118 : else {
119 : /* At least one of b.real or b.imag is a NaN */
120 39 : r.real = r.imag = Py_NAN;
121 : }
122 58663 : return r;
123 : }
124 : #ifdef _M_ARM64
125 : #pragma optimize("", on)
126 : #endif
127 :
128 : Py_complex
129 107 : _Py_c_pow(Py_complex a, Py_complex b)
130 : {
131 : Py_complex r;
132 : double vabs,len,at,phase;
133 107 : if (b.real == 0. && b.imag == 0.) {
134 0 : r.real = 1.;
135 0 : r.imag = 0.;
136 : }
137 107 : else if (a.real == 0. && a.imag == 0.) {
138 4 : if (b.imag != 0. || b.real < 0.)
139 4 : errno = EDOM;
140 4 : r.real = 0.;
141 4 : r.imag = 0.;
142 : }
143 : else {
144 103 : vabs = hypot(a.real,a.imag);
145 103 : len = pow(vabs,b.real);
146 103 : at = atan2(a.imag, a.real);
147 103 : phase = at*b.real;
148 103 : if (b.imag != 0.0) {
149 41 : len /= exp(at*b.imag);
150 41 : phase += b.imag*log(vabs);
151 : }
152 103 : r.real = len*cos(phase);
153 103 : r.imag = len*sin(phase);
154 : }
155 107 : return r;
156 : }
157 :
158 : static Py_complex
159 143 : c_powu(Py_complex x, long n)
160 : {
161 : Py_complex r, p;
162 143 : long mask = 1;
163 143 : r = c_1;
164 143 : p = x;
165 469 : while (mask > 0 && n >= mask) {
166 326 : if (n & mask)
167 227 : r = _Py_c_prod(r,p);
168 326 : mask <<= 1;
169 326 : p = _Py_c_prod(p,p);
170 : }
171 143 : return r;
172 : }
173 :
174 : static Py_complex
175 143 : c_powi(Py_complex x, long n)
176 : {
177 143 : if (n > 0)
178 62 : return c_powu(x,n);
179 : else
180 81 : return _Py_c_quot(c_1, c_powu(x,-n));
181 :
182 : }
183 :
184 : double
185 617 : _Py_c_abs(Py_complex z)
186 : {
187 : /* sets errno = ERANGE on overflow; otherwise errno = 0 */
188 : double result;
189 :
190 617 : if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
191 : /* C99 rules: if either the real or the imaginary part is an
192 : infinity, return infinity, even if the other part is a
193 : NaN. */
194 103 : if (Py_IS_INFINITY(z.real)) {
195 44 : result = fabs(z.real);
196 44 : errno = 0;
197 44 : return result;
198 : }
199 59 : if (Py_IS_INFINITY(z.imag)) {
200 28 : result = fabs(z.imag);
201 28 : errno = 0;
202 28 : return result;
203 : }
204 : /* either the real or imaginary part is a NaN,
205 : and neither is infinite. Result should be NaN. */
206 31 : return Py_NAN;
207 : }
208 514 : result = hypot(z.real, z.imag);
209 514 : if (!Py_IS_FINITE(result))
210 2 : errno = ERANGE;
211 : else
212 512 : errno = 0;
213 514 : return result;
214 : }
215 :
216 : static PyObject *
217 9420 : complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
218 : {
219 : PyObject *op;
220 :
221 9420 : op = type->tp_alloc(type, 0);
222 9420 : if (op != NULL)
223 9420 : ((PyComplexObject *)op)->cval = cval;
224 9420 : return op;
225 : }
226 :
227 : PyObject *
228 82260 : PyComplex_FromCComplex(Py_complex cval)
229 : {
230 : /* Inline PyObject_New */
231 82260 : PyComplexObject *op = PyObject_Malloc(sizeof(PyComplexObject));
232 82260 : if (op == NULL) {
233 0 : return PyErr_NoMemory();
234 : }
235 82260 : _PyObject_Init((PyObject*)op, &PyComplex_Type);
236 82260 : op->cval = cval;
237 82260 : return (PyObject *) op;
238 : }
239 :
240 : static PyObject *
241 9420 : complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
242 : {
243 : Py_complex c;
244 9420 : c.real = real;
245 9420 : c.imag = imag;
246 9420 : return complex_subtype_from_c_complex(type, c);
247 : }
248 :
249 : PyObject *
250 17 : PyComplex_FromDoubles(double real, double imag)
251 : {
252 : Py_complex c;
253 17 : c.real = real;
254 17 : c.imag = imag;
255 17 : return PyComplex_FromCComplex(c);
256 : }
257 :
258 : double
259 361 : PyComplex_RealAsDouble(PyObject *op)
260 : {
261 361 : if (PyComplex_Check(op)) {
262 361 : return ((PyComplexObject *)op)->cval.real;
263 : }
264 : else {
265 0 : return PyFloat_AsDouble(op);
266 : }
267 : }
268 :
269 : double
270 361 : PyComplex_ImagAsDouble(PyObject *op)
271 : {
272 361 : if (PyComplex_Check(op)) {
273 361 : return ((PyComplexObject *)op)->cval.imag;
274 : }
275 : else {
276 0 : return 0.0;
277 : }
278 : }
279 :
280 : static PyObject *
281 10227 : try_complex_special_method(PyObject *op)
282 : {
283 : PyObject *f;
284 :
285 10227 : f = _PyObject_LookupSpecial(op, &_Py_ID(__complex__));
286 10227 : if (f) {
287 752 : PyObject *res = _PyObject_CallNoArgs(f);
288 752 : Py_DECREF(f);
289 752 : if (!res || PyComplex_CheckExact(res)) {
290 491 : return res;
291 : }
292 261 : if (!PyComplex_Check(res)) {
293 259 : PyErr_Format(PyExc_TypeError,
294 : "__complex__ returned non-complex (type %.200s)",
295 259 : Py_TYPE(res)->tp_name);
296 259 : Py_DECREF(res);
297 259 : return NULL;
298 : }
299 : /* Issue #29894: warn if 'res' not of exact type complex. */
300 2 : if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
301 : "__complex__ returned non-complex (type %.200s). "
302 : "The ability to return an instance of a strict subclass of complex "
303 : "is deprecated, and may be removed in a future version of Python.",
304 2 : Py_TYPE(res)->tp_name)) {
305 0 : Py_DECREF(res);
306 0 : return NULL;
307 : }
308 2 : return res;
309 : }
310 9475 : return NULL;
311 : }
312 :
313 : Py_complex
314 5433 : PyComplex_AsCComplex(PyObject *op)
315 : {
316 : Py_complex cv;
317 5433 : PyObject *newop = NULL;
318 :
319 5433 : assert(op);
320 : /* If op is already of type PyComplex_Type, return its value */
321 5433 : if (PyComplex_Check(op)) {
322 4228 : return ((PyComplexObject *)op)->cval;
323 : }
324 : /* If not, use op's __complex__ method, if it exists */
325 :
326 : /* return -1 on failure */
327 1205 : cv.real = -1.;
328 1205 : cv.imag = 0.;
329 :
330 1205 : newop = try_complex_special_method(op);
331 :
332 1205 : if (newop) {
333 102 : cv = ((PyComplexObject *)newop)->cval;
334 102 : Py_DECREF(newop);
335 102 : return cv;
336 : }
337 1103 : else if (PyErr_Occurred()) {
338 289 : return cv;
339 : }
340 : /* If neither of the above works, interpret op as a float giving the
341 : real part of the result, and fill in the imaginary part as 0. */
342 : else {
343 : /* PyFloat_AsDouble will return -1 on failure */
344 814 : cv.real = PyFloat_AsDouble(op);
345 814 : return cv;
346 : }
347 : }
348 :
349 : static PyObject *
350 1805 : complex_repr(PyComplexObject *v)
351 : {
352 1805 : int precision = 0;
353 1805 : char format_code = 'r';
354 1805 : PyObject *result = NULL;
355 :
356 : /* If these are non-NULL, they'll need to be freed. */
357 1805 : char *pre = NULL;
358 1805 : char *im = NULL;
359 :
360 : /* These do not need to be freed. re is either an alias
361 : for pre or a pointer to a constant. lead and tail
362 : are pointers to constants. */
363 1805 : const char *re = NULL;
364 1805 : const char *lead = "";
365 1805 : const char *tail = "";
366 :
367 1805 : if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
368 : /* Real part is +0: just output the imaginary part and do not
369 : include parens. */
370 764 : re = "";
371 764 : im = PyOS_double_to_string(v->cval.imag, format_code,
372 : precision, 0, NULL);
373 764 : if (!im) {
374 0 : PyErr_NoMemory();
375 0 : goto done;
376 : }
377 : } else {
378 : /* Format imaginary part with sign, real part without. Include
379 : parens in the result. */
380 1041 : pre = PyOS_double_to_string(v->cval.real, format_code,
381 : precision, 0, NULL);
382 1041 : if (!pre) {
383 0 : PyErr_NoMemory();
384 0 : goto done;
385 : }
386 1041 : re = pre;
387 :
388 1041 : im = PyOS_double_to_string(v->cval.imag, format_code,
389 : precision, Py_DTSF_SIGN, NULL);
390 1041 : if (!im) {
391 0 : PyErr_NoMemory();
392 0 : goto done;
393 : }
394 1041 : lead = "(";
395 1041 : tail = ")";
396 : }
397 1805 : result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
398 1805 : done:
399 1805 : PyMem_Free(im);
400 1805 : PyMem_Free(pre);
401 :
402 1805 : return result;
403 : }
404 :
405 : static Py_hash_t
406 8248 : complex_hash(PyComplexObject *v)
407 : {
408 : Py_uhash_t hashreal, hashimag, combined;
409 8248 : hashreal = (Py_uhash_t)_Py_HashDouble((PyObject *) v, v->cval.real);
410 8248 : if (hashreal == (Py_uhash_t)-1)
411 0 : return -1;
412 8248 : hashimag = (Py_uhash_t)_Py_HashDouble((PyObject *)v, v->cval.imag);
413 8248 : if (hashimag == (Py_uhash_t)-1)
414 0 : return -1;
415 : /* Note: if the imaginary part is 0, hashimag is 0 now,
416 : * so the following returns hashreal unchanged. This is
417 : * important because numbers of different types that
418 : * compare equal must have the same hash value, so that
419 : * hash(x + 0*j) must equal hash(x).
420 : */
421 8248 : combined = hashreal + _PyHASH_IMAG * hashimag;
422 8248 : if (combined == (Py_uhash_t)-1)
423 0 : combined = (Py_uhash_t)-2;
424 8248 : return (Py_hash_t)combined;
425 : }
426 :
427 : /* This macro may return! */
428 : #define TO_COMPLEX(obj, c) \
429 : if (PyComplex_Check(obj)) \
430 : c = ((PyComplexObject *)(obj))->cval; \
431 : else if (to_complex(&(obj), &(c)) < 0) \
432 : return (obj)
433 :
434 : static int
435 1231 : to_complex(PyObject **pobj, Py_complex *pc)
436 : {
437 1231 : PyObject *obj = *pobj;
438 :
439 1231 : pc->real = pc->imag = 0.0;
440 1231 : if (PyLong_Check(obj)) {
441 472 : pc->real = PyLong_AsDouble(obj);
442 472 : if (pc->real == -1.0 && PyErr_Occurred()) {
443 0 : *pobj = NULL;
444 0 : return -1;
445 : }
446 472 : return 0;
447 : }
448 759 : if (PyFloat_Check(obj)) {
449 754 : pc->real = PyFloat_AsDouble(obj);
450 754 : return 0;
451 : }
452 5 : Py_INCREF(Py_NotImplemented);
453 5 : *pobj = Py_NotImplemented;
454 5 : return -1;
455 : }
456 :
457 :
458 : static PyObject *
459 748 : complex_add(PyObject *v, PyObject *w)
460 : {
461 : Py_complex result;
462 : Py_complex a, b;
463 748 : TO_COMPLEX(v, a);
464 748 : TO_COMPLEX(w, b);
465 747 : result = _Py_c_sum(a, b);
466 747 : return PyComplex_FromCComplex(result);
467 : }
468 :
469 : static PyObject *
470 220 : complex_sub(PyObject *v, PyObject *w)
471 : {
472 : Py_complex result;
473 : Py_complex a, b;
474 220 : TO_COMPLEX(v, a);
475 220 : TO_COMPLEX(w, b);
476 219 : result = _Py_c_diff(a, b);
477 219 : return PyComplex_FromCComplex(result);
478 : }
479 :
480 : static PyObject *
481 14853 : complex_mul(PyObject *v, PyObject *w)
482 : {
483 : Py_complex result;
484 : Py_complex a, b;
485 14853 : TO_COMPLEX(v, a);
486 14853 : TO_COMPLEX(w, b);
487 14852 : result = _Py_c_prod(a, b);
488 14852 : return PyComplex_FromCComplex(result);
489 : }
490 :
491 : static PyObject *
492 58508 : complex_div(PyObject *v, PyObject *w)
493 : {
494 : Py_complex quot;
495 : Py_complex a, b;
496 58508 : TO_COMPLEX(v, a);
497 58508 : TO_COMPLEX(w, b);
498 58507 : errno = 0;
499 58507 : quot = _Py_c_quot(a, b);
500 58507 : if (errno == EDOM) {
501 5 : PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
502 5 : return NULL;
503 : }
504 58502 : return PyComplex_FromCComplex(quot);
505 : }
506 :
507 : static PyObject *
508 253 : complex_pow(PyObject *v, PyObject *w, PyObject *z)
509 : {
510 : Py_complex p;
511 : Py_complex a, b;
512 253 : TO_COMPLEX(v, a);
513 253 : TO_COMPLEX(w, b);
514 :
515 252 : if (z != Py_None) {
516 2 : PyErr_SetString(PyExc_ValueError, "complex modulo");
517 2 : return NULL;
518 : }
519 250 : errno = 0;
520 : // Check whether the exponent has a small integer value, and if so use
521 : // a faster and more accurate algorithm.
522 250 : if (b.imag == 0.0 && b.real == floor(b.real) && fabs(b.real) <= 100.0) {
523 143 : p = c_powi(a, (long)b.real);
524 : }
525 : else {
526 107 : p = _Py_c_pow(a, b);
527 : }
528 :
529 250 : _Py_ADJUST_ERANGE2(p.real, p.imag);
530 250 : if (errno == EDOM) {
531 4 : PyErr_SetString(PyExc_ZeroDivisionError,
532 : "0.0 to a negative or complex power");
533 4 : return NULL;
534 : }
535 246 : else if (errno == ERANGE) {
536 25 : PyErr_SetString(PyExc_OverflowError,
537 : "complex exponentiation");
538 25 : return NULL;
539 : }
540 221 : return PyComplex_FromCComplex(p);
541 : }
542 :
543 : static PyObject *
544 68 : complex_neg(PyComplexObject *v)
545 : {
546 : Py_complex neg;
547 68 : neg.real = -v->cval.real;
548 68 : neg.imag = -v->cval.imag;
549 68 : return PyComplex_FromCComplex(neg);
550 : }
551 :
552 : static PyObject *
553 15 : complex_pos(PyComplexObject *v)
554 : {
555 15 : if (PyComplex_CheckExact(v)) {
556 14 : Py_INCREF(v);
557 14 : return (PyObject *)v;
558 : }
559 : else
560 1 : return PyComplex_FromCComplex(v->cval);
561 : }
562 :
563 : static PyObject *
564 374 : complex_abs(PyComplexObject *v)
565 : {
566 : double result;
567 :
568 374 : result = _Py_c_abs(v->cval);
569 :
570 374 : if (errno == ERANGE) {
571 1 : PyErr_SetString(PyExc_OverflowError,
572 : "absolute value too large");
573 1 : return NULL;
574 : }
575 373 : return PyFloat_FromDouble(result);
576 : }
577 :
578 : static int
579 110 : complex_bool(PyComplexObject *v)
580 : {
581 110 : return v->cval.real != 0.0 || v->cval.imag != 0.0;
582 : }
583 :
584 : static PyObject *
585 35770 : complex_richcompare(PyObject *v, PyObject *w, int op)
586 : {
587 : PyObject *res;
588 : Py_complex i;
589 : int equal;
590 :
591 35770 : if (op != Py_EQ && op != Py_NE) {
592 171 : goto Unimplemented;
593 : }
594 :
595 35599 : assert(PyComplex_Check(v));
596 35599 : TO_COMPLEX(v, i);
597 :
598 35599 : if (PyLong_Check(w)) {
599 : /* Check for 0.0 imaginary part first to avoid the rich
600 : * comparison when possible.
601 : */
602 33371 : if (i.imag == 0.0) {
603 : PyObject *j, *sub_res;
604 4715 : j = PyFloat_FromDouble(i.real);
605 4715 : if (j == NULL)
606 0 : return NULL;
607 :
608 4715 : sub_res = PyObject_RichCompare(j, w, op);
609 4715 : Py_DECREF(j);
610 4715 : return sub_res;
611 : }
612 : else {
613 28656 : equal = 0;
614 : }
615 : }
616 2228 : else if (PyFloat_Check(w)) {
617 428 : equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
618 : }
619 1800 : else if (PyComplex_Check(w)) {
620 : Py_complex j;
621 :
622 1695 : TO_COMPLEX(w, j);
623 1695 : equal = (i.real == j.real && i.imag == j.imag);
624 : }
625 : else {
626 105 : goto Unimplemented;
627 : }
628 :
629 30779 : if (equal == (op == Py_EQ))
630 29074 : res = Py_True;
631 : else
632 1705 : res = Py_False;
633 :
634 30779 : Py_INCREF(res);
635 30779 : return res;
636 :
637 276 : Unimplemented:
638 276 : Py_RETURN_NOTIMPLEMENTED;
639 : }
640 :
641 : /*[clinic input]
642 : complex.conjugate
643 :
644 : Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
645 : [clinic start generated code]*/
646 :
647 : static PyObject *
648 1 : complex_conjugate_impl(PyComplexObject *self)
649 : /*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
650 : {
651 1 : Py_complex c = self->cval;
652 1 : c.imag = -c.imag;
653 1 : return PyComplex_FromCComplex(c);
654 : }
655 :
656 : /*[clinic input]
657 : complex.__getnewargs__
658 :
659 : [clinic start generated code]*/
660 :
661 : static PyObject *
662 54 : complex___getnewargs___impl(PyComplexObject *self)
663 : /*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
664 : {
665 54 : Py_complex c = self->cval;
666 54 : return Py_BuildValue("(dd)", c.real, c.imag);
667 : }
668 :
669 :
670 : /*[clinic input]
671 : complex.__format__
672 :
673 : format_spec: unicode
674 : /
675 :
676 : Convert to a string according to format_spec.
677 : [clinic start generated code]*/
678 :
679 : static PyObject *
680 112 : complex___format___impl(PyComplexObject *self, PyObject *format_spec)
681 : /*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
682 : {
683 : _PyUnicodeWriter writer;
684 : int ret;
685 112 : _PyUnicodeWriter_Init(&writer);
686 112 : ret = _PyComplex_FormatAdvancedWriter(
687 : &writer,
688 : (PyObject *)self,
689 : format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
690 112 : if (ret == -1) {
691 12 : _PyUnicodeWriter_Dealloc(&writer);
692 12 : return NULL;
693 : }
694 100 : return _PyUnicodeWriter_Finish(&writer);
695 : }
696 :
697 : /*[clinic input]
698 : complex.__complex__
699 :
700 : Convert this value to exact type complex.
701 : [clinic start generated code]*/
702 :
703 : static PyObject *
704 339 : complex___complex___impl(PyComplexObject *self)
705 : /*[clinic end generated code: output=e6b35ba3d275dc9c input=3589ada9d27db854]*/
706 : {
707 339 : if (PyComplex_CheckExact(self)) {
708 137 : Py_INCREF(self);
709 137 : return (PyObject *)self;
710 : }
711 : else {
712 202 : return PyComplex_FromCComplex(self->cval);
713 : }
714 : }
715 :
716 :
717 : static PyMethodDef complex_methods[] = {
718 : COMPLEX_CONJUGATE_METHODDEF
719 : COMPLEX___COMPLEX___METHODDEF
720 : COMPLEX___GETNEWARGS___METHODDEF
721 : COMPLEX___FORMAT___METHODDEF
722 : {NULL, NULL} /* sentinel */
723 : };
724 :
725 : static PyMemberDef complex_members[] = {
726 : {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
727 : "the real part of a complex number"},
728 : {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
729 : "the imaginary part of a complex number"},
730 : {0},
731 : };
732 :
733 : static PyObject *
734 508 : complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
735 : {
736 508 : double x=0.0, y=0.0, z;
737 508 : int got_bracket=0;
738 : const char *start;
739 : char *end;
740 :
741 : /* position on first nonblank */
742 508 : start = s;
743 700 : while (Py_ISSPACE(*s))
744 192 : s++;
745 508 : if (*s == '(') {
746 : /* Skip over possible bracket from repr(). */
747 307 : got_bracket = 1;
748 307 : s++;
749 313 : while (Py_ISSPACE(*s))
750 6 : s++;
751 : }
752 :
753 : /* a valid complex string usually takes one of the three forms:
754 :
755 : <float> - real part only
756 : <float>j - imaginary part only
757 : <float><signed-float>j - real and imaginary parts
758 :
759 : where <float> represents any numeric string that's accepted by the
760 : float constructor (including 'nan', 'inf', 'infinity', etc.), and
761 : <signed-float> is any string of the form <float> whose first
762 : character is '+' or '-'.
763 :
764 : For backwards compatibility, the extra forms
765 :
766 : <float><sign>j
767 : <sign>j
768 : j
769 :
770 : are also accepted, though support for these forms may be removed from
771 : a future version of Python.
772 : */
773 :
774 : /* first look for forms starting with <float> */
775 508 : z = PyOS_string_to_double(s, &end, NULL);
776 508 : if (z == -1.0 && PyErr_Occurred()) {
777 60 : if (PyErr_ExceptionMatches(PyExc_ValueError))
778 60 : PyErr_Clear();
779 : else
780 0 : return NULL;
781 : }
782 508 : if (end != s) {
783 : /* all 4 forms starting with <float> land here */
784 448 : s = end;
785 448 : if (*s == '+' || *s == '-') {
786 : /* <float><signed-float>j | <float><sign>j */
787 313 : x = z;
788 313 : y = PyOS_string_to_double(s, &end, NULL);
789 313 : if (y == -1.0 && PyErr_Occurred()) {
790 4 : if (PyErr_ExceptionMatches(PyExc_ValueError))
791 4 : PyErr_Clear();
792 : else
793 0 : return NULL;
794 : }
795 313 : if (end != s)
796 : /* <float><signed-float>j */
797 309 : s = end;
798 : else {
799 : /* <float><sign>j */
800 4 : y = *s == '+' ? 1.0 : -1.0;
801 4 : s++;
802 : }
803 313 : if (!(*s == 'j' || *s == 'J'))
804 2 : goto parse_error;
805 311 : s++;
806 : }
807 135 : else if (*s == 'j' || *s == 'J') {
808 : /* <float>j */
809 64 : s++;
810 64 : y = z;
811 : }
812 : else
813 : /* <float> */
814 71 : x = z;
815 : }
816 : else {
817 : /* not starting with <float>; must be <sign>j or j */
818 60 : if (*s == '+' || *s == '-') {
819 : /* <sign>j */
820 3 : y = *s == '+' ? 1.0 : -1.0;
821 3 : s++;
822 : }
823 : else
824 : /* j */
825 57 : y = 1.0;
826 60 : if (!(*s == 'j' || *s == 'J'))
827 56 : goto parse_error;
828 4 : s++;
829 : }
830 :
831 : /* trailing whitespace and closing bracket */
832 455 : while (Py_ISSPACE(*s))
833 5 : s++;
834 450 : if (got_bracket) {
835 : /* if there was an opening parenthesis, then the corresponding
836 : closing parenthesis should be right here */
837 307 : if (*s != ')')
838 1 : goto parse_error;
839 306 : s++;
840 307 : while (Py_ISSPACE(*s))
841 1 : s++;
842 : }
843 :
844 : /* we should now be at the end of the string */
845 449 : if (s-start != len)
846 27 : goto parse_error;
847 :
848 422 : return complex_subtype_from_doubles(_PyType_CAST(type), x, y);
849 :
850 86 : parse_error:
851 86 : PyErr_SetString(PyExc_ValueError,
852 : "complex() arg is a malformed string");
853 86 : return NULL;
854 : }
855 :
856 : static PyObject *
857 535 : complex_subtype_from_string(PyTypeObject *type, PyObject *v)
858 : {
859 : const char *s;
860 535 : PyObject *s_buffer = NULL, *result = NULL;
861 : Py_ssize_t len;
862 :
863 535 : if (PyUnicode_Check(v)) {
864 535 : s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
865 535 : if (s_buffer == NULL) {
866 0 : return NULL;
867 : }
868 535 : assert(PyUnicode_IS_ASCII(s_buffer));
869 : /* Simply get a pointer to existing ASCII characters. */
870 535 : s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
871 535 : assert(s != NULL);
872 : }
873 : else {
874 0 : PyErr_Format(PyExc_TypeError,
875 : "complex() argument must be a string or a number, not '%.200s'",
876 0 : Py_TYPE(v)->tp_name);
877 0 : return NULL;
878 : }
879 :
880 535 : result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
881 : complex_from_string_inner);
882 535 : Py_DECREF(s_buffer);
883 535 : return result;
884 : }
885 :
886 : /*[clinic input]
887 : @classmethod
888 : complex.__new__ as complex_new
889 : real as r: object(c_default="NULL") = 0
890 : imag as i: object(c_default="NULL") = 0
891 :
892 : Create a complex number from a real part and an optional imaginary part.
893 :
894 : This is equivalent to (real + imag*1j) where imag defaults to 0.
895 : [clinic start generated code]*/
896 :
897 : static PyObject *
898 9570 : complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
899 : /*[clinic end generated code: output=b6c7dd577b537dc1 input=f4c667f2596d4fd1]*/
900 : {
901 : PyObject *tmp;
902 9570 : PyNumberMethods *nbr, *nbi = NULL;
903 : Py_complex cr, ci;
904 9570 : int own_r = 0;
905 9570 : int cr_is_complex = 0;
906 9570 : int ci_is_complex = 0;
907 :
908 9570 : if (r == NULL) {
909 5 : r = _PyLong_GetZero();
910 : }
911 :
912 : /* Special-case for a single argument when type(arg) is complex. */
913 9570 : if (PyComplex_CheckExact(r) && i == NULL &&
914 : type == &PyComplex_Type) {
915 : /* Note that we can't know whether it's safe to return
916 : a complex *subclass* instance as-is, hence the restriction
917 : to exact complexes here. If either the input or the
918 : output is a complex subclass, it will be handled below
919 : as a non-orthogonal vector. */
920 8 : Py_INCREF(r);
921 8 : return r;
922 : }
923 9562 : if (PyUnicode_Check(r)) {
924 538 : if (i != NULL) {
925 3 : PyErr_SetString(PyExc_TypeError,
926 : "complex() can't take second arg"
927 : " if first is a string");
928 3 : return NULL;
929 : }
930 535 : return complex_subtype_from_string(type, r);
931 : }
932 9024 : if (i != NULL && PyUnicode_Check(i)) {
933 2 : PyErr_SetString(PyExc_TypeError,
934 : "complex() second arg can't be a string");
935 2 : return NULL;
936 : }
937 :
938 9022 : tmp = try_complex_special_method(r);
939 9022 : if (tmp) {
940 354 : r = tmp;
941 354 : own_r = 1;
942 : }
943 8668 : else if (PyErr_Occurred()) {
944 8 : return NULL;
945 : }
946 :
947 9014 : nbr = Py_TYPE(r)->tp_as_number;
948 9014 : if (nbr == NULL ||
949 9014 : (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
950 : {
951 5 : PyErr_Format(PyExc_TypeError,
952 : "complex() first argument must be a string or a number, "
953 : "not '%.200s'",
954 5 : Py_TYPE(r)->tp_name);
955 5 : if (own_r) {
956 0 : Py_DECREF(r);
957 : }
958 5 : return NULL;
959 : }
960 9009 : if (i != NULL) {
961 8541 : nbi = Py_TYPE(i)->tp_as_number;
962 8541 : if (nbi == NULL ||
963 8541 : (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
964 : {
965 2 : PyErr_Format(PyExc_TypeError,
966 : "complex() second argument must be a number, "
967 : "not '%.200s'",
968 2 : Py_TYPE(i)->tp_name);
969 2 : if (own_r) {
970 0 : Py_DECREF(r);
971 : }
972 2 : return NULL;
973 : }
974 : }
975 :
976 : /* If we get this far, then the "real" and "imag" parts should
977 : both be treated as numbers, and the constructor should return a
978 : complex number equal to (real + imag*1j).
979 :
980 : Note that we do NOT assume the input to already be in canonical
981 : form; the "real" and "imag" parts might themselves be complex
982 : numbers, which slightly complicates the code below. */
983 9007 : if (PyComplex_Check(r)) {
984 : /* Note that if r is of a complex subtype, we're only
985 : retaining its real & imag parts here, and the return
986 : value is (properly) of the builtin complex type. */
987 354 : cr = ((PyComplexObject*)r)->cval;
988 354 : cr_is_complex = 1;
989 354 : if (own_r) {
990 354 : Py_DECREF(r);
991 : }
992 : }
993 : else {
994 : /* The "real" part really is entirely real, and contributes
995 : nothing in the imaginary direction.
996 : Just treat it as a double. */
997 8653 : tmp = PyNumber_Float(r);
998 8653 : if (own_r) {
999 : /* r was a newly created complex number, rather
1000 : than the original "real" argument. */
1001 0 : Py_DECREF(r);
1002 : }
1003 8653 : if (tmp == NULL)
1004 6 : return NULL;
1005 8647 : assert(PyFloat_Check(tmp));
1006 8647 : cr.real = PyFloat_AsDouble(tmp);
1007 8647 : cr.imag = 0.0;
1008 8647 : Py_DECREF(tmp);
1009 : }
1010 9001 : if (i == NULL) {
1011 464 : ci.real = cr.imag;
1012 : }
1013 8537 : else if (PyComplex_Check(i)) {
1014 4 : ci = ((PyComplexObject*)i)->cval;
1015 4 : ci_is_complex = 1;
1016 : } else {
1017 : /* The "imag" part really is entirely imaginary, and
1018 : contributes nothing in the real direction.
1019 : Just treat it as a double. */
1020 8533 : tmp = PyNumber_Float(i);
1021 8533 : if (tmp == NULL)
1022 3 : return NULL;
1023 8530 : ci.real = PyFloat_AsDouble(tmp);
1024 8530 : Py_DECREF(tmp);
1025 : }
1026 : /* If the input was in canonical form, then the "real" and "imag"
1027 : parts are real numbers, so that ci.imag and cr.imag are zero.
1028 : We need this correction in case they were not real numbers. */
1029 :
1030 8998 : if (ci_is_complex) {
1031 4 : cr.real -= ci.imag;
1032 : }
1033 8998 : if (cr_is_complex && i != NULL) {
1034 5 : ci.real += cr.imag;
1035 : }
1036 8998 : return complex_subtype_from_doubles(type, cr.real, ci.real);
1037 : }
1038 :
1039 : static PyNumberMethods complex_as_number = {
1040 : (binaryfunc)complex_add, /* nb_add */
1041 : (binaryfunc)complex_sub, /* nb_subtract */
1042 : (binaryfunc)complex_mul, /* nb_multiply */
1043 : 0, /* nb_remainder */
1044 : 0, /* nb_divmod */
1045 : (ternaryfunc)complex_pow, /* nb_power */
1046 : (unaryfunc)complex_neg, /* nb_negative */
1047 : (unaryfunc)complex_pos, /* nb_positive */
1048 : (unaryfunc)complex_abs, /* nb_absolute */
1049 : (inquiry)complex_bool, /* nb_bool */
1050 : 0, /* nb_invert */
1051 : 0, /* nb_lshift */
1052 : 0, /* nb_rshift */
1053 : 0, /* nb_and */
1054 : 0, /* nb_xor */
1055 : 0, /* nb_or */
1056 : 0, /* nb_int */
1057 : 0, /* nb_reserved */
1058 : 0, /* nb_float */
1059 : 0, /* nb_inplace_add */
1060 : 0, /* nb_inplace_subtract */
1061 : 0, /* nb_inplace_multiply*/
1062 : 0, /* nb_inplace_remainder */
1063 : 0, /* nb_inplace_power */
1064 : 0, /* nb_inplace_lshift */
1065 : 0, /* nb_inplace_rshift */
1066 : 0, /* nb_inplace_and */
1067 : 0, /* nb_inplace_xor */
1068 : 0, /* nb_inplace_or */
1069 : 0, /* nb_floor_divide */
1070 : (binaryfunc)complex_div, /* nb_true_divide */
1071 : 0, /* nb_inplace_floor_divide */
1072 : 0, /* nb_inplace_true_divide */
1073 : };
1074 :
1075 : PyTypeObject PyComplex_Type = {
1076 : PyVarObject_HEAD_INIT(&PyType_Type, 0)
1077 : "complex",
1078 : sizeof(PyComplexObject),
1079 : 0,
1080 : 0, /* tp_dealloc */
1081 : 0, /* tp_vectorcall_offset */
1082 : 0, /* tp_getattr */
1083 : 0, /* tp_setattr */
1084 : 0, /* tp_as_async */
1085 : (reprfunc)complex_repr, /* tp_repr */
1086 : &complex_as_number, /* tp_as_number */
1087 : 0, /* tp_as_sequence */
1088 : 0, /* tp_as_mapping */
1089 : (hashfunc)complex_hash, /* tp_hash */
1090 : 0, /* tp_call */
1091 : 0, /* tp_str */
1092 : PyObject_GenericGetAttr, /* tp_getattro */
1093 : 0, /* tp_setattro */
1094 : 0, /* tp_as_buffer */
1095 : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1096 : complex_new__doc__, /* tp_doc */
1097 : 0, /* tp_traverse */
1098 : 0, /* tp_clear */
1099 : complex_richcompare, /* tp_richcompare */
1100 : 0, /* tp_weaklistoffset */
1101 : 0, /* tp_iter */
1102 : 0, /* tp_iternext */
1103 : complex_methods, /* tp_methods */
1104 : complex_members, /* tp_members */
1105 : 0, /* tp_getset */
1106 : 0, /* tp_base */
1107 : 0, /* tp_dict */
1108 : 0, /* tp_descr_get */
1109 : 0, /* tp_descr_set */
1110 : 0, /* tp_dictoffset */
1111 : 0, /* tp_init */
1112 : PyType_GenericAlloc, /* tp_alloc */
1113 : complex_new, /* tp_new */
1114 : PyObject_Del, /* tp_free */
1115 : };
|