This commit was manufactured by cvs2svn to create tag 'r223c1'.
[python/dscho.git] / Objects / complexobject.c
blobf9bfd003ff9c2232391c551fded3c010f00cf8fa
2 /* Complex object implementation */
4 /* Borrows heavily from floatobject.c */
6 /* Submitted by Jim Hugunin */
8 #ifndef WITHOUT_COMPLEX
10 #include "Python.h"
11 #include "structmember.h"
13 /* Precisions used by repr() and str(), respectively.
15 The repr() precision (17 significant decimal digits) is the minimal number
16 that is guaranteed to have enough precision so that if the number is read
17 back in the exact same binary value is recreated. This is true for IEEE
18 floating point by design, and also happens to work for all other modern
19 hardware.
21 The str() precision is chosen so that in most cases, the rounding noise
22 created by various operations is suppressed, while giving plenty of
23 precision for practical use.
26 #define PREC_REPR 17
27 #define PREC_STR 12
29 /* elementary operations on complex numbers */
31 static Py_complex c_1 = {1., 0.};
33 Py_complex
34 c_sum(Py_complex a, Py_complex b)
36 Py_complex r;
37 r.real = a.real + b.real;
38 r.imag = a.imag + b.imag;
39 return r;
42 Py_complex
43 c_diff(Py_complex a, Py_complex b)
45 Py_complex r;
46 r.real = a.real - b.real;
47 r.imag = a.imag - b.imag;
48 return r;
51 Py_complex
52 c_neg(Py_complex a)
54 Py_complex r;
55 r.real = -a.real;
56 r.imag = -a.imag;
57 return r;
60 Py_complex
61 c_prod(Py_complex a, Py_complex b)
63 Py_complex r;
64 r.real = a.real*b.real - a.imag*b.imag;
65 r.imag = a.real*b.imag + a.imag*b.real;
66 return r;
69 Py_complex
70 c_quot(Py_complex a, Py_complex b)
72 /******************************************************************
73 This was the original algorithm. It's grossly prone to spurious
74 overflow and underflow errors. It also merrily divides by 0 despite
75 checking for that(!). The code still serves a doc purpose here, as
76 the algorithm following is a simple by-cases transformation of this
77 one:
79 Py_complex r;
80 double d = b.real*b.real + b.imag*b.imag;
81 if (d == 0.)
82 errno = EDOM;
83 r.real = (a.real*b.real + a.imag*b.imag)/d;
84 r.imag = (a.imag*b.real - a.real*b.imag)/d;
85 return r;
86 ******************************************************************/
88 /* This algorithm is better, and is pretty obvious: first divide the
89 * numerators and denominator by whichever of {b.real, b.imag} has
90 * larger magnitude. The earliest reference I found was to CACM
91 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
92 * University). As usual, though, we're still ignoring all IEEE
93 * endcases.
95 Py_complex r; /* the result */
96 const double abs_breal = b.real < 0 ? -b.real : b.real;
97 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
99 if (abs_breal >= abs_bimag) {
100 /* divide tops and bottom by b.real */
101 if (abs_breal == 0.0) {
102 errno = EDOM;
103 r.real = r.imag = 0.0;
105 else {
106 const double ratio = b.imag / b.real;
107 const double denom = b.real + b.imag * ratio;
108 r.real = (a.real + a.imag * ratio) / denom;
109 r.imag = (a.imag - a.real * ratio) / denom;
112 else {
113 /* divide tops and bottom by b.imag */
114 const double ratio = b.real / b.imag;
115 const double denom = b.real * ratio + b.imag;
116 assert(b.imag != 0.0);
117 r.real = (a.real * ratio + a.imag) / denom;
118 r.imag = (a.imag * ratio - a.real) / denom;
120 return r;
123 Py_complex
124 c_pow(Py_complex a, Py_complex b)
126 Py_complex r;
127 double vabs,len,at,phase;
128 if (b.real == 0. && b.imag == 0.) {
129 r.real = 1.;
130 r.imag = 0.;
132 else if (a.real == 0. && a.imag == 0.) {
133 if (b.imag != 0. || b.real < 0.)
134 errno = EDOM;
135 r.real = 0.;
136 r.imag = 0.;
138 else {
139 vabs = hypot(a.real,a.imag);
140 len = pow(vabs,b.real);
141 at = atan2(a.imag, a.real);
142 phase = at*b.real;
143 if (b.imag != 0.0) {
144 len /= exp(at*b.imag);
145 phase += b.imag*log(vabs);
147 r.real = len*cos(phase);
148 r.imag = len*sin(phase);
150 return r;
153 static Py_complex
154 c_powu(Py_complex x, long n)
156 Py_complex r, p;
157 long mask = 1;
158 r = c_1;
159 p = x;
160 while (mask > 0 && n >= mask) {
161 if (n & mask)
162 r = c_prod(r,p);
163 mask <<= 1;
164 p = c_prod(p,p);
166 return r;
169 static Py_complex
170 c_powi(Py_complex x, long n)
172 Py_complex cn;
174 if (n > 100 || n < -100) {
175 cn.real = (double) n;
176 cn.imag = 0.;
177 return c_pow(x,cn);
179 else if (n > 0)
180 return c_powu(x,n);
181 else
182 return c_quot(c_1,c_powu(x,-n));
186 static PyObject *
187 complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
189 PyObject *op;
191 op = PyType_GenericAlloc(type, 0);
192 if (op != NULL)
193 ((PyComplexObject *)op)->cval = cval;
194 return op;
197 PyObject *
198 PyComplex_FromCComplex(Py_complex cval)
200 register PyComplexObject *op;
202 /* Inline PyObject_New */
203 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
204 if (op == NULL)
205 return PyErr_NoMemory();
206 PyObject_INIT(op, &PyComplex_Type);
207 op->cval = cval;
208 return (PyObject *) op;
211 static PyObject *
212 complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
214 Py_complex c;
215 c.real = real;
216 c.imag = imag;
217 return complex_subtype_from_c_complex(type, c);
220 PyObject *
221 PyComplex_FromDoubles(double real, double imag)
223 Py_complex c;
224 c.real = real;
225 c.imag = imag;
226 return PyComplex_FromCComplex(c);
229 double
230 PyComplex_RealAsDouble(PyObject *op)
232 if (PyComplex_Check(op)) {
233 return ((PyComplexObject *)op)->cval.real;
235 else {
236 return PyFloat_AsDouble(op);
240 double
241 PyComplex_ImagAsDouble(PyObject *op)
243 if (PyComplex_Check(op)) {
244 return ((PyComplexObject *)op)->cval.imag;
246 else {
247 return 0.0;
251 Py_complex
252 PyComplex_AsCComplex(PyObject *op)
254 Py_complex cv;
255 if (PyComplex_Check(op)) {
256 return ((PyComplexObject *)op)->cval;
258 else {
259 cv.real = PyFloat_AsDouble(op);
260 cv.imag = 0.;
261 return cv;
265 static void
266 complex_dealloc(PyObject *op)
268 op->ob_type->tp_free(op);
272 static void
273 complex_to_buf(char *buf, int bufsz, PyComplexObject *v, int precision)
275 if (v->cval.real == 0.)
276 PyOS_snprintf(buf, bufsz, "%.*gj",
277 precision, v->cval.imag);
278 else
279 PyOS_snprintf(buf, bufsz, "(%.*g%+.*gj)",
280 precision, v->cval.real,
281 precision, v->cval.imag);
284 static int
285 complex_print(PyComplexObject *v, FILE *fp, int flags)
287 char buf[100];
288 complex_to_buf(buf, sizeof(buf), v,
289 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
290 fputs(buf, fp);
291 return 0;
294 static PyObject *
295 complex_repr(PyComplexObject *v)
297 char buf[100];
298 complex_to_buf(buf, sizeof(buf), v, PREC_REPR);
299 return PyString_FromString(buf);
302 static PyObject *
303 complex_str(PyComplexObject *v)
305 char buf[100];
306 complex_to_buf(buf, sizeof(buf), v, PREC_STR);
307 return PyString_FromString(buf);
310 static long
311 complex_hash(PyComplexObject *v)
313 long hashreal, hashimag, combined;
314 hashreal = _Py_HashDouble(v->cval.real);
315 if (hashreal == -1)
316 return -1;
317 hashimag = _Py_HashDouble(v->cval.imag);
318 if (hashimag == -1)
319 return -1;
320 /* Note: if the imaginary part is 0, hashimag is 0 now,
321 * so the following returns hashreal unchanged. This is
322 * important because numbers of different types that
323 * compare equal must have the same hash value, so that
324 * hash(x + 0*j) must equal hash(x).
326 combined = hashreal + 1000003 * hashimag;
327 if (combined == -1)
328 combined = -2;
329 return combined;
332 static PyObject *
333 complex_add(PyComplexObject *v, PyComplexObject *w)
335 Py_complex result;
336 PyFPE_START_PROTECT("complex_add", return 0)
337 result = c_sum(v->cval,w->cval);
338 PyFPE_END_PROTECT(result)
339 return PyComplex_FromCComplex(result);
342 static PyObject *
343 complex_sub(PyComplexObject *v, PyComplexObject *w)
345 Py_complex result;
346 PyFPE_START_PROTECT("complex_sub", return 0)
347 result = c_diff(v->cval,w->cval);
348 PyFPE_END_PROTECT(result)
349 return PyComplex_FromCComplex(result);
352 static PyObject *
353 complex_mul(PyComplexObject *v, PyComplexObject *w)
355 Py_complex result;
356 PyFPE_START_PROTECT("complex_mul", return 0)
357 result = c_prod(v->cval,w->cval);
358 PyFPE_END_PROTECT(result)
359 return PyComplex_FromCComplex(result);
362 static PyObject *
363 complex_div(PyComplexObject *v, PyComplexObject *w)
365 Py_complex quot;
366 PyFPE_START_PROTECT("complex_div", return 0)
367 errno = 0;
368 quot = c_quot(v->cval,w->cval);
369 PyFPE_END_PROTECT(quot)
370 if (errno == EDOM) {
371 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
372 return NULL;
374 return PyComplex_FromCComplex(quot);
377 static PyObject *
378 complex_classic_div(PyComplexObject *v, PyComplexObject *w)
380 Py_complex quot;
382 if (Py_DivisionWarningFlag >= 2 &&
383 PyErr_Warn(PyExc_DeprecationWarning,
384 "classic complex division") < 0)
385 return NULL;
387 PyFPE_START_PROTECT("complex_classic_div", return 0)
388 errno = 0;
389 quot = c_quot(v->cval,w->cval);
390 PyFPE_END_PROTECT(quot)
391 if (errno == EDOM) {
392 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
393 return NULL;
395 return PyComplex_FromCComplex(quot);
398 static PyObject *
399 complex_remainder(PyComplexObject *v, PyComplexObject *w)
401 Py_complex div, mod;
403 if (PyErr_Warn(PyExc_DeprecationWarning,
404 "complex divmod(), // and % are deprecated") < 0)
405 return NULL;
407 errno = 0;
408 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
409 if (errno == EDOM) {
410 PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
411 return NULL;
413 div.real = floor(div.real); /* Use the floor of the real part. */
414 div.imag = 0.0;
415 mod = c_diff(v->cval, c_prod(w->cval, div));
417 return PyComplex_FromCComplex(mod);
421 static PyObject *
422 complex_divmod(PyComplexObject *v, PyComplexObject *w)
424 Py_complex div, mod;
425 PyObject *d, *m, *z;
427 if (PyErr_Warn(PyExc_DeprecationWarning,
428 "complex divmod(), // and % are deprecated") < 0)
429 return NULL;
431 errno = 0;
432 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
433 if (errno == EDOM) {
434 PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
435 return NULL;
437 div.real = floor(div.real); /* Use the floor of the real part. */
438 div.imag = 0.0;
439 mod = c_diff(v->cval, c_prod(w->cval, div));
440 d = PyComplex_FromCComplex(div);
441 m = PyComplex_FromCComplex(mod);
442 z = Py_BuildValue("(OO)", d, m);
443 Py_XDECREF(d);
444 Py_XDECREF(m);
445 return z;
448 static PyObject *
449 complex_pow(PyComplexObject *v, PyObject *w, PyComplexObject *z)
451 Py_complex p;
452 Py_complex exponent;
453 long int_exponent;
455 if ((PyObject *)z!=Py_None) {
456 PyErr_SetString(PyExc_ValueError, "complex modulo");
457 return NULL;
459 PyFPE_START_PROTECT("complex_pow", return 0)
460 errno = 0;
461 exponent = ((PyComplexObject*)w)->cval;
462 int_exponent = (long)exponent.real;
463 if (exponent.imag == 0. && exponent.real == int_exponent)
464 p = c_powi(v->cval,int_exponent);
465 else
466 p = c_pow(v->cval,exponent);
468 PyFPE_END_PROTECT(p)
469 Py_ADJUST_ERANGE2(p.real, p.imag);
470 if (errno == EDOM) {
471 PyErr_SetString(PyExc_ZeroDivisionError,
472 "0.0 to a negative or complex power");
473 return NULL;
475 else if (errno == ERANGE) {
476 PyErr_SetString(PyExc_OverflowError,
477 "complex exponentiaion");
478 return NULL;
480 return PyComplex_FromCComplex(p);
483 static PyObject *
484 complex_int_div(PyComplexObject *v, PyComplexObject *w)
486 PyObject *t, *r;
488 t = complex_divmod(v, w);
489 if (t != NULL) {
490 r = PyTuple_GET_ITEM(t, 0);
491 Py_INCREF(r);
492 Py_DECREF(t);
493 return r;
495 return NULL;
498 static PyObject *
499 complex_neg(PyComplexObject *v)
501 Py_complex neg;
502 neg.real = -v->cval.real;
503 neg.imag = -v->cval.imag;
504 return PyComplex_FromCComplex(neg);
507 static PyObject *
508 complex_pos(PyComplexObject *v)
510 if (PyComplex_CheckExact(v)) {
511 Py_INCREF(v);
512 return (PyObject *)v;
514 else
515 return PyComplex_FromCComplex(v->cval);
518 static PyObject *
519 complex_abs(PyComplexObject *v)
521 double result;
522 PyFPE_START_PROTECT("complex_abs", return 0)
523 result = hypot(v->cval.real,v->cval.imag);
524 PyFPE_END_PROTECT(result)
525 return PyFloat_FromDouble(result);
528 static int
529 complex_nonzero(PyComplexObject *v)
531 return v->cval.real != 0.0 || v->cval.imag != 0.0;
534 static int
535 complex_coerce(PyObject **pv, PyObject **pw)
537 Py_complex cval;
538 cval.imag = 0.;
539 if (PyInt_Check(*pw)) {
540 cval.real = (double)PyInt_AsLong(*pw);
541 *pw = PyComplex_FromCComplex(cval);
542 Py_INCREF(*pv);
543 return 0;
545 else if (PyLong_Check(*pw)) {
546 cval.real = PyLong_AsDouble(*pw);
547 if (cval.real == -1.0 && PyErr_Occurred())
548 return -1;
549 *pw = PyComplex_FromCComplex(cval);
550 Py_INCREF(*pv);
551 return 0;
553 else if (PyFloat_Check(*pw)) {
554 cval.real = PyFloat_AsDouble(*pw);
555 *pw = PyComplex_FromCComplex(cval);
556 Py_INCREF(*pv);
557 return 0;
559 else if (PyComplex_Check(*pw)) {
560 Py_INCREF(*pv);
561 Py_INCREF(*pw);
562 return 0;
564 return 1; /* Can't do it */
567 static PyObject *
568 complex_richcompare(PyObject *v, PyObject *w, int op)
570 int c;
571 Py_complex i, j;
572 PyObject *res;
574 c = PyNumber_CoerceEx(&v, &w);
575 if (c < 0)
576 return NULL;
577 if (c > 0) {
578 Py_INCREF(Py_NotImplemented);
579 return Py_NotImplemented;
581 /* Make sure both arguments are complex. */
582 if (!(PyComplex_Check(v) && PyComplex_Check(w))) {
583 Py_DECREF(v);
584 Py_DECREF(w);
585 Py_INCREF(Py_NotImplemented);
586 return Py_NotImplemented;
589 i = ((PyComplexObject *)v)->cval;
590 j = ((PyComplexObject *)w)->cval;
591 Py_DECREF(v);
592 Py_DECREF(w);
594 if (op != Py_EQ && op != Py_NE) {
595 PyErr_SetString(PyExc_TypeError,
596 "cannot compare complex numbers using <, <=, >, >=");
597 return NULL;
600 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
601 res = Py_True;
602 else
603 res = Py_False;
605 Py_INCREF(res);
606 return res;
609 static PyObject *
610 complex_int(PyObject *v)
612 PyErr_SetString(PyExc_TypeError,
613 "can't convert complex to int; use e.g. int(abs(z))");
614 return NULL;
617 static PyObject *
618 complex_long(PyObject *v)
620 PyErr_SetString(PyExc_TypeError,
621 "can't convert complex to long; use e.g. long(abs(z))");
622 return NULL;
625 static PyObject *
626 complex_float(PyObject *v)
628 PyErr_SetString(PyExc_TypeError,
629 "can't convert complex to float; use e.g. abs(z)");
630 return NULL;
633 static PyObject *
634 complex_conjugate(PyObject *self)
636 Py_complex c;
637 c = ((PyComplexObject *)self)->cval;
638 c.imag = -c.imag;
639 return PyComplex_FromCComplex(c);
642 static PyMethodDef complex_methods[] = {
643 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS},
644 {NULL, NULL} /* sentinel */
647 static PyMemberDef complex_members[] = {
648 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
649 "the real part of a complex number"},
650 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
651 "the imaginary part of a complex number"},
652 {0},
655 static PyObject *
656 complex_subtype_from_string(PyTypeObject *type, PyObject *v)
658 extern double strtod(const char *, char **);
659 const char *s, *start;
660 char *end;
661 double x=0.0, y=0.0, z;
662 int got_re=0, got_im=0, done=0;
663 int digit_or_dot;
664 int sw_error=0;
665 int sign;
666 char buffer[256]; /* For errors */
667 #ifdef Py_USING_UNICODE
668 char s_buffer[256];
669 #endif
670 int len;
672 if (PyString_Check(v)) {
673 s = PyString_AS_STRING(v);
674 len = PyString_GET_SIZE(v);
676 #ifdef Py_USING_UNICODE
677 else if (PyUnicode_Check(v)) {
678 if (PyUnicode_GET_SIZE(v) >= sizeof(s_buffer)) {
679 PyErr_SetString(PyExc_ValueError,
680 "complex() literal too large to convert");
681 return NULL;
683 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
684 PyUnicode_GET_SIZE(v),
685 s_buffer,
686 NULL))
687 return NULL;
688 s = s_buffer;
689 len = (int)strlen(s);
691 #endif
692 else if (PyObject_AsCharBuffer(v, &s, &len)) {
693 PyErr_SetString(PyExc_TypeError,
694 "complex() arg is not a string");
695 return NULL;
698 /* position on first nonblank */
699 start = s;
700 while (*s && isspace(Py_CHARMASK(*s)))
701 s++;
702 if (s[0] == '\0') {
703 PyErr_SetString(PyExc_ValueError,
704 "complex() arg is an empty string");
705 return NULL;
708 z = -1.0;
709 sign = 1;
710 do {
712 switch (*s) {
714 case '\0':
715 if (s-start != len) {
716 PyErr_SetString(
717 PyExc_ValueError,
718 "complex() arg contains a null byte");
719 return NULL;
721 if(!done) sw_error=1;
722 break;
724 case '-':
725 sign = -1;
726 /* Fallthrough */
727 case '+':
728 if (done) sw_error=1;
729 s++;
730 if ( *s=='\0'||*s=='+'||*s=='-' ||
731 isspace(Py_CHARMASK(*s)) ) sw_error=1;
732 break;
734 case 'J':
735 case 'j':
736 if (got_im || done) {
737 sw_error = 1;
738 break;
740 if (z<0.0) {
741 y=sign;
743 else{
744 y=sign*z;
746 got_im=1;
747 s++;
748 if (*s!='+' && *s!='-' )
749 done=1;
750 break;
752 default:
753 if (isspace(Py_CHARMASK(*s))) {
754 while (*s && isspace(Py_CHARMASK(*s)))
755 s++;
756 if (s[0] != '\0')
757 sw_error=1;
758 else
759 done = 1;
760 break;
762 digit_or_dot =
763 (*s=='.' || isdigit(Py_CHARMASK(*s)));
764 if (done||!digit_or_dot) {
765 sw_error=1;
766 break;
768 errno = 0;
769 PyFPE_START_PROTECT("strtod", return 0)
770 z = strtod(s, &end) ;
771 PyFPE_END_PROTECT(z)
772 if (errno != 0) {
773 PyOS_snprintf(buffer, sizeof(buffer),
774 "float() out of range: %.150s", s);
775 PyErr_SetString(
776 PyExc_ValueError,
777 buffer);
778 return NULL;
780 s=end;
781 if (*s=='J' || *s=='j') {
783 break;
785 if (got_re) {
786 sw_error=1;
787 break;
790 /* accept a real part */
791 x=sign*z;
792 got_re=1;
793 if (got_im) done=1;
794 z = -1.0;
795 sign = 1;
796 break;
798 } /* end of switch */
800 } while (s - start < len && !sw_error);
802 if (sw_error) {
803 PyErr_SetString(PyExc_ValueError,
804 "complex() arg is a malformed string");
805 return NULL;
808 return complex_subtype_from_doubles(type, x, y);
811 static PyObject *
812 complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
814 PyObject *r, *i, *tmp, *f;
815 PyNumberMethods *nbr, *nbi = NULL;
816 Py_complex cr, ci;
817 int own_r = 0;
818 static PyObject *complexstr;
819 static char *kwlist[] = {"real", "imag", 0};
821 r = Py_False;
822 i = NULL;
823 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
824 &r, &i))
825 return NULL;
826 if (PyString_Check(r) || PyUnicode_Check(r)) {
827 if (i != NULL) {
828 PyErr_SetString(PyExc_TypeError,
829 "complex() can't take second arg"
830 " if first is a string");
831 return NULL;
833 return complex_subtype_from_string(type, r);
835 if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
836 PyErr_SetString(PyExc_TypeError,
837 "complex() second arg can't be a string");
838 return NULL;
841 /* XXX Hack to support classes with __complex__ method */
842 if (complexstr == NULL) {
843 complexstr = PyString_InternFromString("__complex__");
844 if (complexstr == NULL)
845 return NULL;
847 f = PyObject_GetAttr(r, complexstr);
848 if (f == NULL)
849 PyErr_Clear();
850 else {
851 PyObject *args = Py_BuildValue("()");
852 if (args == NULL)
853 return NULL;
854 r = PyEval_CallObject(f, args);
855 Py_DECREF(args);
856 Py_DECREF(f);
857 if (r == NULL)
858 return NULL;
859 own_r = 1;
861 nbr = r->ob_type->tp_as_number;
862 if (i != NULL)
863 nbi = i->ob_type->tp_as_number;
864 if (nbr == NULL || nbr->nb_float == NULL ||
865 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
866 PyErr_SetString(PyExc_TypeError,
867 "complex() argument must be a string or a number");
868 return NULL;
870 if (PyComplex_Check(r)) {
871 /* Note that if r is of a complex subtype, we're only
872 retaining its real & imag parts here, and the return
873 value is (properly) of the builtin complex type. */
874 cr = ((PyComplexObject*)r)->cval;
875 if (own_r) {
876 Py_DECREF(r);
879 else {
880 tmp = PyNumber_Float(r);
881 if (own_r) {
882 Py_DECREF(r);
884 if (tmp == NULL)
885 return NULL;
886 if (!PyFloat_Check(tmp)) {
887 PyErr_SetString(PyExc_TypeError,
888 "float(r) didn't return a float");
889 Py_DECREF(tmp);
890 return NULL;
892 cr.real = PyFloat_AsDouble(tmp);
893 Py_DECREF(tmp);
894 cr.imag = 0.0;
896 if (i == NULL) {
897 ci.real = 0.0;
898 ci.imag = 0.0;
900 else if (PyComplex_Check(i))
901 ci = ((PyComplexObject*)i)->cval;
902 else {
903 tmp = (*nbi->nb_float)(i);
904 if (tmp == NULL)
905 return NULL;
906 ci.real = PyFloat_AsDouble(tmp);
907 Py_DECREF(tmp);
908 ci.imag = 0.;
910 cr.real -= ci.imag;
911 cr.imag += ci.real;
912 return complex_subtype_from_c_complex(type, cr);
915 static char complex_doc[] =
916 "complex(real[, imag]) -> complex number\n"
917 "\n"
918 "Create a complex number from a real part and an optional imaginary part.\n"
919 "This is equivalent to (real + imag*1j) where imag defaults to 0.";
921 static PyNumberMethods complex_as_number = {
922 (binaryfunc)complex_add, /* nb_add */
923 (binaryfunc)complex_sub, /* nb_subtract */
924 (binaryfunc)complex_mul, /* nb_multiply */
925 (binaryfunc)complex_classic_div, /* nb_divide */
926 (binaryfunc)complex_remainder, /* nb_remainder */
927 (binaryfunc)complex_divmod, /* nb_divmod */
928 (ternaryfunc)complex_pow, /* nb_power */
929 (unaryfunc)complex_neg, /* nb_negative */
930 (unaryfunc)complex_pos, /* nb_positive */
931 (unaryfunc)complex_abs, /* nb_absolute */
932 (inquiry)complex_nonzero, /* nb_nonzero */
933 0, /* nb_invert */
934 0, /* nb_lshift */
935 0, /* nb_rshift */
936 0, /* nb_and */
937 0, /* nb_xor */
938 0, /* nb_or */
939 (coercion)complex_coerce, /* nb_coerce */
940 (unaryfunc)complex_int, /* nb_int */
941 (unaryfunc)complex_long, /* nb_long */
942 (unaryfunc)complex_float, /* nb_float */
943 0, /* nb_oct */
944 0, /* nb_hex */
945 0, /* nb_inplace_add */
946 0, /* nb_inplace_subtract */
947 0, /* nb_inplace_multiply*/
948 0, /* nb_inplace_divide */
949 0, /* nb_inplace_remainder */
950 0, /* nb_inplace_power */
951 0, /* nb_inplace_lshift */
952 0, /* nb_inplace_rshift */
953 0, /* nb_inplace_and */
954 0, /* nb_inplace_xor */
955 0, /* nb_inplace_or */
956 (binaryfunc)complex_int_div, /* nb_floor_divide */
957 (binaryfunc)complex_div, /* nb_true_divide */
958 0, /* nb_inplace_floor_divide */
959 0, /* nb_inplace_true_divide */
962 PyTypeObject PyComplex_Type = {
963 PyObject_HEAD_INIT(&PyType_Type)
965 "complex",
966 sizeof(PyComplexObject),
968 (destructor)complex_dealloc, /* tp_dealloc */
969 (printfunc)complex_print, /* tp_print */
970 0, /* tp_getattr */
971 0, /* tp_setattr */
972 0, /* tp_compare */
973 (reprfunc)complex_repr, /* tp_repr */
974 &complex_as_number, /* tp_as_number */
975 0, /* tp_as_sequence */
976 0, /* tp_as_mapping */
977 (hashfunc)complex_hash, /* tp_hash */
978 0, /* tp_call */
979 (reprfunc)complex_str, /* tp_str */
980 PyObject_GenericGetAttr, /* tp_getattro */
981 0, /* tp_setattro */
982 0, /* tp_as_buffer */
983 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
984 complex_doc, /* tp_doc */
985 0, /* tp_traverse */
986 0, /* tp_clear */
987 complex_richcompare, /* tp_richcompare */
988 0, /* tp_weaklistoffset */
989 0, /* tp_iter */
990 0, /* tp_iternext */
991 complex_methods, /* tp_methods */
992 complex_members, /* tp_members */
993 0, /* tp_getset */
994 0, /* tp_base */
995 0, /* tp_dict */
996 0, /* tp_descr_get */
997 0, /* tp_descr_set */
998 0, /* tp_dictoffset */
999 0, /* tp_init */
1000 0, /* tp_alloc */
1001 complex_new, /* tp_new */
1002 _PyObject_Del, /* tp_free */
1005 #endif