Tagging 3.0a4.
[python/dscho.git] / Objects / complexobject.c
blob90b970eea9eafe4f77642b846d446e975de39c0b
2 /* Complex object implementation */
4 /* Borrows heavily from floatobject.c */
6 /* Submitted by Jim Hugunin */
8 #include "Python.h"
9 #include "structmember.h"
11 #ifdef HAVE_IEEEFP_H
12 #include <ieeefp.h>
13 #endif
15 #ifndef WITHOUT_COMPLEX
17 /* Precisions used by repr() and str(), respectively.
19 The repr() precision (17 significant decimal digits) is the minimal number
20 that is guaranteed to have enough precision so that if the number is read
21 back in the exact same binary value is recreated. This is true for IEEE
22 floating point by design, and also happens to work for all other modern
23 hardware.
25 The str() precision is chosen so that in most cases, the rounding noise
26 created by various operations is suppressed, while giving plenty of
27 precision for practical use.
30 #define PREC_REPR 17
31 #define PREC_STR 12
33 /* elementary operations on complex numbers */
35 static Py_complex c_1 = {1., 0.};
37 Py_complex
38 c_sum(Py_complex a, Py_complex b)
40 Py_complex r;
41 r.real = a.real + b.real;
42 r.imag = a.imag + b.imag;
43 return r;
46 Py_complex
47 c_diff(Py_complex a, Py_complex b)
49 Py_complex r;
50 r.real = a.real - b.real;
51 r.imag = a.imag - b.imag;
52 return r;
55 Py_complex
56 c_neg(Py_complex a)
58 Py_complex r;
59 r.real = -a.real;
60 r.imag = -a.imag;
61 return r;
64 Py_complex
65 c_prod(Py_complex a, Py_complex b)
67 Py_complex r;
68 r.real = a.real*b.real - a.imag*b.imag;
69 r.imag = a.real*b.imag + a.imag*b.real;
70 return r;
73 Py_complex
74 c_quot(Py_complex a, Py_complex b)
76 /******************************************************************
77 This was the original algorithm. It's grossly prone to spurious
78 overflow and underflow errors. It also merrily divides by 0 despite
79 checking for that(!). The code still serves a doc purpose here, as
80 the algorithm following is a simple by-cases transformation of this
81 one:
83 Py_complex r;
84 double d = b.real*b.real + b.imag*b.imag;
85 if (d == 0.)
86 errno = EDOM;
87 r.real = (a.real*b.real + a.imag*b.imag)/d;
88 r.imag = (a.imag*b.real - a.real*b.imag)/d;
89 return r;
90 ******************************************************************/
92 /* This algorithm is better, and is pretty obvious: first divide the
93 * numerators and denominator by whichever of {b.real, b.imag} has
94 * larger magnitude. The earliest reference I found was to CACM
95 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
96 * University). As usual, though, we're still ignoring all IEEE
97 * endcases.
99 Py_complex r; /* the result */
100 const double abs_breal = b.real < 0 ? -b.real : b.real;
101 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
103 if (abs_breal >= abs_bimag) {
104 /* divide tops and bottom by b.real */
105 if (abs_breal == 0.0) {
106 errno = EDOM;
107 r.real = r.imag = 0.0;
109 else {
110 const double ratio = b.imag / b.real;
111 const double denom = b.real + b.imag * ratio;
112 r.real = (a.real + a.imag * ratio) / denom;
113 r.imag = (a.imag - a.real * ratio) / denom;
116 else {
117 /* divide tops and bottom by b.imag */
118 const double ratio = b.real / b.imag;
119 const double denom = b.real * ratio + b.imag;
120 assert(b.imag != 0.0);
121 r.real = (a.real * ratio + a.imag) / denom;
122 r.imag = (a.imag * ratio - a.real) / denom;
124 return r;
127 Py_complex
128 c_pow(Py_complex a, Py_complex b)
130 Py_complex r;
131 double vabs,len,at,phase;
132 if (b.real == 0. && b.imag == 0.) {
133 r.real = 1.;
134 r.imag = 0.;
136 else if (a.real == 0. && a.imag == 0.) {
137 if (b.imag != 0. || b.real < 0.)
138 errno = EDOM;
139 r.real = 0.;
140 r.imag = 0.;
142 else {
143 vabs = hypot(a.real,a.imag);
144 len = pow(vabs,b.real);
145 at = atan2(a.imag, a.real);
146 phase = at*b.real;
147 if (b.imag != 0.0) {
148 len /= exp(at*b.imag);
149 phase += b.imag*log(vabs);
151 r.real = len*cos(phase);
152 r.imag = len*sin(phase);
154 return r;
157 static Py_complex
158 c_powu(Py_complex x, long n)
160 Py_complex r, p;
161 long mask = 1;
162 r = c_1;
163 p = x;
164 while (mask > 0 && n >= mask) {
165 if (n & mask)
166 r = c_prod(r,p);
167 mask <<= 1;
168 p = c_prod(p,p);
170 return r;
173 static Py_complex
174 c_powi(Py_complex x, long n)
176 Py_complex cn;
178 if (n > 100 || n < -100) {
179 cn.real = (double) n;
180 cn.imag = 0.;
181 return c_pow(x,cn);
183 else if (n > 0)
184 return c_powu(x,n);
185 else
186 return c_quot(c_1,c_powu(x,-n));
190 static PyObject *
191 complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
193 PyObject *op;
195 op = type->tp_alloc(type, 0);
196 if (op != NULL)
197 ((PyComplexObject *)op)->cval = cval;
198 return op;
201 PyObject *
202 PyComplex_FromCComplex(Py_complex cval)
204 register PyComplexObject *op;
206 /* Inline PyObject_New */
207 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
208 if (op == NULL)
209 return PyErr_NoMemory();
210 PyObject_INIT(op, &PyComplex_Type);
211 op->cval = cval;
212 return (PyObject *) op;
215 static PyObject *
216 complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
218 Py_complex c;
219 c.real = real;
220 c.imag = imag;
221 return complex_subtype_from_c_complex(type, c);
224 PyObject *
225 PyComplex_FromDoubles(double real, double imag)
227 Py_complex c;
228 c.real = real;
229 c.imag = imag;
230 return PyComplex_FromCComplex(c);
233 double
234 PyComplex_RealAsDouble(PyObject *op)
236 if (PyComplex_Check(op)) {
237 return ((PyComplexObject *)op)->cval.real;
239 else {
240 return PyFloat_AsDouble(op);
244 double
245 PyComplex_ImagAsDouble(PyObject *op)
247 if (PyComplex_Check(op)) {
248 return ((PyComplexObject *)op)->cval.imag;
250 else {
251 return 0.0;
255 Py_complex
256 PyComplex_AsCComplex(PyObject *op)
258 Py_complex cv;
259 PyObject *newop = NULL;
260 static PyObject *complex_str = NULL;
262 assert(op);
263 /* If op is already of type PyComplex_Type, return its value */
264 if (PyComplex_Check(op)) {
265 return ((PyComplexObject *)op)->cval;
267 /* If not, use op's __complex__ method, if it exists */
269 /* return -1 on failure */
270 cv.real = -1.;
271 cv.imag = 0.;
273 if (complex_str == NULL) {
274 if (!(complex_str = PyUnicode_FromString("__complex__")))
275 return cv;
279 PyObject *complexfunc;
280 complexfunc = _PyType_Lookup(op->ob_type, complex_str);
281 /* complexfunc is a borrowed reference */
282 if (complexfunc) {
283 newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL);
284 if (!newop)
285 return cv;
289 if (newop) {
290 if (!PyComplex_Check(newop)) {
291 PyErr_SetString(PyExc_TypeError,
292 "__complex__ should return a complex object");
293 Py_DECREF(newop);
294 return cv;
296 cv = ((PyComplexObject *)newop)->cval;
297 Py_DECREF(newop);
298 return cv;
300 /* If neither of the above works, interpret op as a float giving the
301 real part of the result, and fill in the imaginary part as 0. */
302 else {
303 /* PyFloat_AsDouble will return -1 on failure */
304 cv.real = PyFloat_AsDouble(op);
305 return cv;
309 static void
310 complex_dealloc(PyObject *op)
312 op->ob_type->tp_free(op);
316 static void
317 complex_to_buf(char *buf, int bufsz, PyComplexObject *v, int precision)
319 char format[32];
320 if (v->cval.real == 0.) {
321 if (!Py_IS_FINITE(v->cval.imag)) {
322 if (Py_IS_NAN(v->cval.imag))
323 strncpy(buf, "nan*j", 6);
324 /* else if (copysign(1, v->cval.imag) == 1) */
325 else if (v->cval.imag > 0)
326 strncpy(buf, "inf*j", 6);
327 else
328 strncpy(buf, "-inf*j", 7);
330 else {
331 PyOS_snprintf(format, sizeof(format), "%%.%ig", precision);
332 PyOS_ascii_formatd(buf, bufsz - 1, format, v->cval.imag);
333 strncat(buf, "j", 1);
335 } else {
336 char re[64], im[64];
337 /* Format imaginary part with sign, real part without */
338 if (!Py_IS_FINITE(v->cval.real)) {
339 if (Py_IS_NAN(v->cval.real))
340 strncpy(re, "nan", 4);
341 /* else if (copysign(1, v->cval.real) == 1) */
342 else if (v->cval.real > 0)
343 strncpy(re, "inf", 4);
344 else
345 strncpy(re, "-inf", 5);
347 else {
348 PyOS_snprintf(format, sizeof(format), "%%.%ig", precision);
349 PyOS_ascii_formatd(re, sizeof(re), format, v->cval.real);
351 if (!Py_IS_FINITE(v->cval.imag)) {
352 if (Py_IS_NAN(v->cval.imag))
353 strncpy(im, "+nan*", 6);
354 /* else if (copysign(1, v->cval.imag) == 1) */
355 else if (v->cval.imag > 0)
356 strncpy(im, "+inf*", 6);
357 else
358 strncpy(im, "-inf*", 6);
360 else {
361 PyOS_snprintf(format, sizeof(format), "%%+.%ig", precision);
362 PyOS_ascii_formatd(im, sizeof(im), format, v->cval.imag);
364 PyOS_snprintf(buf, bufsz, "(%s%sj)", re, im);
368 static PyObject *
369 complex_repr(PyComplexObject *v)
371 char buf[100];
372 complex_to_buf(buf, sizeof(buf), v, PREC_REPR);
373 return PyUnicode_FromString(buf);
376 static PyObject *
377 complex_str(PyComplexObject *v)
379 char buf[100];
380 complex_to_buf(buf, sizeof(buf), v, PREC_STR);
381 return PyUnicode_FromString(buf);
384 static long
385 complex_hash(PyComplexObject *v)
387 long hashreal, hashimag, combined;
388 hashreal = _Py_HashDouble(v->cval.real);
389 if (hashreal == -1)
390 return -1;
391 hashimag = _Py_HashDouble(v->cval.imag);
392 if (hashimag == -1)
393 return -1;
394 /* Note: if the imaginary part is 0, hashimag is 0 now,
395 * so the following returns hashreal unchanged. This is
396 * important because numbers of different types that
397 * compare equal must have the same hash value, so that
398 * hash(x + 0*j) must equal hash(x).
400 combined = hashreal + 1000003 * hashimag;
401 if (combined == -1)
402 combined = -2;
403 return combined;
406 /* This macro may return! */
407 #define TO_COMPLEX(obj, c) \
408 if (PyComplex_Check(obj)) \
409 c = ((PyComplexObject *)(obj))->cval; \
410 else if (to_complex(&(obj), &(c)) < 0) \
411 return (obj)
413 static int
414 to_complex(PyObject **pobj, Py_complex *pc)
416 PyObject *obj = *pobj;
418 pc->real = pc->imag = 0.0;
419 if (PyLong_Check(obj)) {
420 pc->real = PyLong_AsDouble(obj);
421 if (pc->real == -1.0 && PyErr_Occurred()) {
422 *pobj = NULL;
423 return -1;
425 return 0;
427 if (PyFloat_Check(obj)) {
428 pc->real = PyFloat_AsDouble(obj);
429 return 0;
431 Py_INCREF(Py_NotImplemented);
432 *pobj = Py_NotImplemented;
433 return -1;
437 static PyObject *
438 complex_add(PyObject *v, PyObject *w)
440 Py_complex result;
441 Py_complex a, b;
442 TO_COMPLEX(v, a);
443 TO_COMPLEX(w, b);
444 PyFPE_START_PROTECT("complex_add", return 0)
445 result = c_sum(a, b);
446 PyFPE_END_PROTECT(result)
447 return PyComplex_FromCComplex(result);
450 static PyObject *
451 complex_sub(PyObject *v, PyObject *w)
453 Py_complex result;
454 Py_complex a, b;
455 TO_COMPLEX(v, a);
456 TO_COMPLEX(w, b);
457 PyFPE_START_PROTECT("complex_sub", return 0)
458 result = c_diff(a, b);
459 PyFPE_END_PROTECT(result)
460 return PyComplex_FromCComplex(result);
463 static PyObject *
464 complex_mul(PyObject *v, PyObject *w)
466 Py_complex result;
467 Py_complex a, b;
468 TO_COMPLEX(v, a);
469 TO_COMPLEX(w, b);
470 PyFPE_START_PROTECT("complex_mul", return 0)
471 result = c_prod(a, b);
472 PyFPE_END_PROTECT(result)
473 return PyComplex_FromCComplex(result);
476 static PyObject *
477 complex_div(PyObject *v, PyObject *w)
479 Py_complex quot;
480 Py_complex a, b;
481 TO_COMPLEX(v, a);
482 TO_COMPLEX(w, b);
483 PyFPE_START_PROTECT("complex_div", return 0)
484 errno = 0;
485 quot = c_quot(a, b);
486 PyFPE_END_PROTECT(quot)
487 if (errno == EDOM) {
488 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
489 return NULL;
491 return PyComplex_FromCComplex(quot);
494 static PyObject *
495 complex_remainder(PyObject *v, PyObject *w)
497 PyErr_SetString(PyExc_TypeError,
498 "can't mod complex numbers.");
499 return NULL;
503 static PyObject *
504 complex_divmod(PyObject *v, PyObject *w)
506 PyErr_SetString(PyExc_TypeError,
507 "can't take floor or mod of complex number.");
508 return NULL;
511 static PyObject *
512 complex_pow(PyObject *v, PyObject *w, PyObject *z)
514 Py_complex p;
515 Py_complex exponent;
516 long int_exponent;
517 Py_complex a, b;
518 TO_COMPLEX(v, a);
519 TO_COMPLEX(w, b);
521 if (z != Py_None) {
522 PyErr_SetString(PyExc_ValueError, "complex modulo");
523 return NULL;
525 PyFPE_START_PROTECT("complex_pow", return 0)
526 errno = 0;
527 exponent = b;
528 int_exponent = (long)exponent.real;
529 if (exponent.imag == 0. && exponent.real == int_exponent)
530 p = c_powi(a, int_exponent);
531 else
532 p = c_pow(a, exponent);
534 PyFPE_END_PROTECT(p)
535 Py_ADJUST_ERANGE2(p.real, p.imag);
536 if (errno == EDOM) {
537 PyErr_SetString(PyExc_ZeroDivisionError,
538 "0.0 to a negative or complex power");
539 return NULL;
541 else if (errno == ERANGE) {
542 PyErr_SetString(PyExc_OverflowError,
543 "complex exponentiation");
544 return NULL;
546 return PyComplex_FromCComplex(p);
549 static PyObject *
550 complex_int_div(PyObject *v, PyObject *w)
552 PyErr_SetString(PyExc_TypeError,
553 "can't take floor of complex number.");
554 return NULL;
557 static PyObject *
558 complex_neg(PyComplexObject *v)
560 Py_complex neg;
561 neg.real = -v->cval.real;
562 neg.imag = -v->cval.imag;
563 return PyComplex_FromCComplex(neg);
566 static PyObject *
567 complex_pos(PyComplexObject *v)
569 if (PyComplex_CheckExact(v)) {
570 Py_INCREF(v);
571 return (PyObject *)v;
573 else
574 return PyComplex_FromCComplex(v->cval);
577 static PyObject *
578 complex_abs(PyComplexObject *v)
580 double result;
581 PyFPE_START_PROTECT("complex_abs", return 0)
582 result = hypot(v->cval.real,v->cval.imag);
583 PyFPE_END_PROTECT(result)
584 return PyFloat_FromDouble(result);
587 static int
588 complex_bool(PyComplexObject *v)
590 return v->cval.real != 0.0 || v->cval.imag != 0.0;
593 static PyObject *
594 complex_richcompare(PyObject *v, PyObject *w, int op)
596 PyObject *res;
597 Py_complex i, j;
598 TO_COMPLEX(v, i);
599 TO_COMPLEX(w, j);
601 if (op != Py_EQ && op != Py_NE) {
602 /* XXX Should eventually return NotImplemented */
603 PyErr_SetString(PyExc_TypeError,
604 "no ordering relation is defined for complex numbers");
605 return NULL;
608 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
609 res = Py_True;
610 else
611 res = Py_False;
613 Py_INCREF(res);
614 return res;
617 static PyObject *
618 complex_int(PyObject *v)
620 PyErr_SetString(PyExc_TypeError,
621 "can't convert complex to int; use int(abs(z))");
622 return NULL;
625 static PyObject *
626 complex_long(PyObject *v)
628 PyErr_SetString(PyExc_TypeError,
629 "can't convert complex to long; use long(abs(z))");
630 return NULL;
633 static PyObject *
634 complex_float(PyObject *v)
636 PyErr_SetString(PyExc_TypeError,
637 "can't convert complex to float; use abs(z)");
638 return NULL;
641 static PyObject *
642 complex_conjugate(PyObject *self)
644 Py_complex c;
645 c = ((PyComplexObject *)self)->cval;
646 c.imag = -c.imag;
647 return PyComplex_FromCComplex(c);
650 PyDoc_STRVAR(complex_conjugate_doc,
651 "complex.conjugate() -> complex\n"
652 "\n"
653 "Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
655 static PyObject *
656 complex_getnewargs(PyComplexObject *v)
658 return Py_BuildValue("(D)", &v->cval);
661 static PyMethodDef complex_methods[] = {
662 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
663 complex_conjugate_doc},
664 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
665 {NULL, NULL} /* sentinel */
668 static PyMemberDef complex_members[] = {
669 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
670 "the real part of a complex number"},
671 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
672 "the imaginary part of a complex number"},
673 {0},
676 static PyObject *
677 complex_subtype_from_string(PyTypeObject *type, PyObject *v)
679 const char *s, *start;
680 char *end;
681 double x=0.0, y=0.0, z;
682 int got_re=0, got_im=0, got_bracket=0, done=0;
683 int digit_or_dot;
684 int sw_error=0;
685 int sign;
686 char buffer[256]; /* For errors */
687 char s_buffer[256];
688 Py_ssize_t len;
690 if (PyUnicode_Check(v)) {
691 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
692 PyErr_SetString(PyExc_ValueError,
693 "complex() literal too large to convert");
694 return NULL;
696 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
697 PyUnicode_GET_SIZE(v),
698 s_buffer,
699 NULL))
700 return NULL;
701 s = s_buffer;
702 len = strlen(s);
704 else if (PyObject_AsCharBuffer(v, &s, &len)) {
705 PyErr_SetString(PyExc_TypeError,
706 "complex() arg is not a string");
707 return NULL;
710 /* position on first nonblank */
711 start = s;
712 while (*s && isspace(Py_CHARMASK(*s)))
713 s++;
714 if (s[0] == '\0') {
715 PyErr_SetString(PyExc_ValueError,
716 "complex() arg is an empty string");
717 return NULL;
719 if (s[0] == '(') {
720 /* Skip over possible bracket from repr(). */
721 got_bracket = 1;
722 s++;
723 while (*s && isspace(Py_CHARMASK(*s)))
724 s++;
727 z = -1.0;
728 sign = 1;
729 do {
731 switch (*s) {
733 case '\0':
734 if (s-start != len) {
735 PyErr_SetString(
736 PyExc_ValueError,
737 "complex() arg contains a null byte");
738 return NULL;
740 if(!done) sw_error=1;
741 break;
743 case ')':
744 if (!got_bracket || !(got_re || got_im)) {
745 sw_error=1;
746 break;
748 got_bracket=0;
749 done=1;
750 s++;
751 while (*s && isspace(Py_CHARMASK(*s)))
752 s++;
753 if (*s) sw_error=1;
754 break;
756 case '-':
757 sign = -1;
758 /* Fallthrough */
759 case '+':
760 if (done) sw_error=1;
761 s++;
762 if ( *s=='\0'||*s=='+'||*s=='-'||*s==')'||
763 isspace(Py_CHARMASK(*s)) ) sw_error=1;
764 break;
766 case 'J':
767 case 'j':
768 if (got_im || done) {
769 sw_error = 1;
770 break;
772 if (z<0.0) {
773 y=sign;
775 else{
776 y=sign*z;
778 got_im=1;
779 s++;
780 if (*s!='+' && *s!='-' )
781 done=1;
782 break;
784 default:
785 if (isspace(Py_CHARMASK(*s))) {
786 while (*s && isspace(Py_CHARMASK(*s)))
787 s++;
788 if (*s && *s != ')')
789 sw_error=1;
790 else
791 done = 1;
792 break;
794 digit_or_dot =
795 (*s=='.' || isdigit(Py_CHARMASK(*s)));
796 if (done||!digit_or_dot) {
797 sw_error=1;
798 break;
800 errno = 0;
801 PyFPE_START_PROTECT("strtod", return 0)
802 z = PyOS_ascii_strtod(s, &end) ;
803 PyFPE_END_PROTECT(z)
804 if (errno != 0) {
805 PyOS_snprintf(buffer, sizeof(buffer),
806 "float() out of range: %.150s", s);
807 PyErr_SetString(
808 PyExc_ValueError,
809 buffer);
810 return NULL;
812 s=end;
813 if (*s=='J' || *s=='j') {
815 break;
817 if (got_re) {
818 sw_error=1;
819 break;
822 /* accept a real part */
823 x=sign*z;
824 got_re=1;
825 if (got_im) done=1;
826 z = -1.0;
827 sign = 1;
828 break;
830 } /* end of switch */
832 } while (s - start < len && !sw_error);
834 if (sw_error || got_bracket) {
835 PyErr_SetString(PyExc_ValueError,
836 "complex() arg is a malformed string");
837 return NULL;
840 return complex_subtype_from_doubles(type, x, y);
843 static PyObject *
844 complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
846 PyObject *r, *i, *tmp, *f;
847 PyNumberMethods *nbr, *nbi = NULL;
848 Py_complex cr, ci;
849 int own_r = 0;
850 int cr_is_complex = 0;
851 int ci_is_complex = 0;
852 static PyObject *complexstr;
853 static char *kwlist[] = {"real", "imag", 0};
855 r = Py_False;
856 i = NULL;
857 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
858 &r, &i))
859 return NULL;
861 /* Special-case for a single argument when type(arg) is complex. */
862 if (PyComplex_CheckExact(r) && i == NULL &&
863 type == &PyComplex_Type) {
864 /* Note that we can't know whether it's safe to return
865 a complex *subclass* instance as-is, hence the restriction
866 to exact complexes here. If either the input or the
867 output is a complex subclass, it will be handled below
868 as a non-orthogonal vector. */
869 Py_INCREF(r);
870 return r;
872 if (PyUnicode_Check(r)) {
873 if (i != NULL) {
874 PyErr_SetString(PyExc_TypeError,
875 "complex() can't take second arg"
876 " if first is a string");
877 return NULL;
879 return complex_subtype_from_string(type, r);
881 if (i != NULL && PyUnicode_Check(i)) {
882 PyErr_SetString(PyExc_TypeError,
883 "complex() second arg can't be a string");
884 return NULL;
887 /* XXX Hack to support classes with __complex__ method */
888 if (complexstr == NULL) {
889 complexstr = PyUnicode_InternFromString("__complex__");
890 if (complexstr == NULL)
891 return NULL;
893 f = PyObject_GetAttr(r, complexstr);
894 if (f == NULL)
895 PyErr_Clear();
896 else {
897 PyObject *args = PyTuple_New(0);
898 if (args == NULL)
899 return NULL;
900 r = PyEval_CallObject(f, args);
901 Py_DECREF(args);
902 Py_DECREF(f);
903 if (r == NULL)
904 return NULL;
905 own_r = 1;
907 nbr = r->ob_type->tp_as_number;
908 if (i != NULL)
909 nbi = i->ob_type->tp_as_number;
910 if (nbr == NULL || nbr->nb_float == NULL ||
911 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
912 PyErr_SetString(PyExc_TypeError,
913 "complex() argument must be a string or a number");
914 if (own_r) {
915 Py_DECREF(r);
917 return NULL;
920 /* If we get this far, then the "real" and "imag" parts should
921 both be treated as numbers, and the constructor should return a
922 complex number equal to (real + imag*1j).
924 Note that we do NOT assume the input to already be in canonical
925 form; the "real" and "imag" parts might themselves be complex
926 numbers, which slightly complicates the code below. */
927 if (PyComplex_Check(r)) {
928 /* Note that if r is of a complex subtype, we're only
929 retaining its real & imag parts here, and the return
930 value is (properly) of the builtin complex type. */
931 cr = ((PyComplexObject*)r)->cval;
932 cr_is_complex = 1;
933 if (own_r) {
934 Py_DECREF(r);
937 else {
938 /* The "real" part really is entirely real, and contributes
939 nothing in the imaginary direction.
940 Just treat it as a double. */
941 tmp = PyNumber_Float(r);
942 if (own_r) {
943 /* r was a newly created complex number, rather
944 than the original "real" argument. */
945 Py_DECREF(r);
947 if (tmp == NULL)
948 return NULL;
949 if (!PyFloat_Check(tmp)) {
950 PyErr_SetString(PyExc_TypeError,
951 "float(r) didn't return a float");
952 Py_DECREF(tmp);
953 return NULL;
955 cr.real = PyFloat_AsDouble(tmp);
956 cr.imag = 0.0; /* Shut up compiler warning */
957 Py_DECREF(tmp);
959 if (i == NULL) {
960 ci.real = 0.0;
962 else if (PyComplex_Check(i)) {
963 ci = ((PyComplexObject*)i)->cval;
964 ci_is_complex = 1;
965 } else {
966 /* The "imag" part really is entirely imaginary, and
967 contributes nothing in the real direction.
968 Just treat it as a double. */
969 tmp = (*nbi->nb_float)(i);
970 if (tmp == NULL)
971 return NULL;
972 ci.real = PyFloat_AsDouble(tmp);
973 Py_DECREF(tmp);
975 /* If the input was in canonical form, then the "real" and "imag"
976 parts are real numbers, so that ci.imag and cr.imag are zero.
977 We need this correction in case they were not real numbers. */
979 if (ci_is_complex) {
980 cr.real -= ci.imag;
982 if (cr_is_complex) {
983 ci.real += cr.imag;
985 return complex_subtype_from_doubles(type, cr.real, ci.real);
988 PyDoc_STRVAR(complex_doc,
989 "complex(real[, imag]) -> complex number\n"
990 "\n"
991 "Create a complex number from a real part and an optional imaginary part.\n"
992 "This is equivalent to (real + imag*1j) where imag defaults to 0.");
994 static PyNumberMethods complex_as_number = {
995 (binaryfunc)complex_add, /* nb_add */
996 (binaryfunc)complex_sub, /* nb_subtract */
997 (binaryfunc)complex_mul, /* nb_multiply */
998 (binaryfunc)complex_remainder, /* nb_remainder */
999 (binaryfunc)complex_divmod, /* nb_divmod */
1000 (ternaryfunc)complex_pow, /* nb_power */
1001 (unaryfunc)complex_neg, /* nb_negative */
1002 (unaryfunc)complex_pos, /* nb_positive */
1003 (unaryfunc)complex_abs, /* nb_absolute */
1004 (inquiry)complex_bool, /* nb_bool */
1005 0, /* nb_invert */
1006 0, /* nb_lshift */
1007 0, /* nb_rshift */
1008 0, /* nb_and */
1009 0, /* nb_xor */
1010 0, /* nb_or */
1011 0, /* nb_reserved */
1012 complex_int, /* nb_int */
1013 complex_long, /* nb_long */
1014 complex_float, /* nb_float */
1015 0, /* nb_oct */
1016 0, /* nb_hex */
1017 0, /* nb_inplace_add */
1018 0, /* nb_inplace_subtract */
1019 0, /* nb_inplace_multiply*/
1020 0, /* nb_inplace_remainder */
1021 0, /* nb_inplace_power */
1022 0, /* nb_inplace_lshift */
1023 0, /* nb_inplace_rshift */
1024 0, /* nb_inplace_and */
1025 0, /* nb_inplace_xor */
1026 0, /* nb_inplace_or */
1027 (binaryfunc)complex_int_div, /* nb_floor_divide */
1028 (binaryfunc)complex_div, /* nb_true_divide */
1029 0, /* nb_inplace_floor_divide */
1030 0, /* nb_inplace_true_divide */
1033 PyTypeObject PyComplex_Type = {
1034 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1035 "complex",
1036 sizeof(PyComplexObject),
1038 complex_dealloc, /* tp_dealloc */
1039 0, /* tp_print */
1040 0, /* tp_getattr */
1041 0, /* tp_setattr */
1042 0, /* tp_compare */
1043 (reprfunc)complex_repr, /* tp_repr */
1044 &complex_as_number, /* tp_as_number */
1045 0, /* tp_as_sequence */
1046 0, /* tp_as_mapping */
1047 (hashfunc)complex_hash, /* tp_hash */
1048 0, /* tp_call */
1049 (reprfunc)complex_str, /* tp_str */
1050 PyObject_GenericGetAttr, /* tp_getattro */
1051 0, /* tp_setattro */
1052 0, /* tp_as_buffer */
1053 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1054 complex_doc, /* tp_doc */
1055 0, /* tp_traverse */
1056 0, /* tp_clear */
1057 complex_richcompare, /* tp_richcompare */
1058 0, /* tp_weaklistoffset */
1059 0, /* tp_iter */
1060 0, /* tp_iternext */
1061 complex_methods, /* tp_methods */
1062 complex_members, /* tp_members */
1063 0, /* tp_getset */
1064 0, /* tp_base */
1065 0, /* tp_dict */
1066 0, /* tp_descr_get */
1067 0, /* tp_descr_set */
1068 0, /* tp_dictoffset */
1069 0, /* tp_init */
1070 PyType_GenericAlloc, /* tp_alloc */
1071 complex_new, /* tp_new */
1072 PyObject_Del, /* tp_free */
1075 #endif