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