docstring update.
[python.git] / Objects / complexobject.c
blob2ae8056ac611f1aab530bfd28b65fdf6cabaea2d
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 double
191 c_abs(Py_complex z)
193 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
194 double result;
196 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
197 /* C99 rules: if either the real or the imaginary part is an
198 infinity, return infinity, even if the other part is a
199 NaN. */
200 if (Py_IS_INFINITY(z.real)) {
201 result = fabs(z.real);
202 errno = 0;
203 return result;
205 if (Py_IS_INFINITY(z.imag)) {
206 result = fabs(z.imag);
207 errno = 0;
208 return result;
210 /* either the real or imaginary part is a NaN,
211 and neither is infinite. Result should be NaN. */
212 return Py_NAN;
214 result = hypot(z.real, z.imag);
215 if (!Py_IS_FINITE(result))
216 errno = ERANGE;
217 else
218 errno = 0;
219 return result;
222 static PyObject *
223 complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
225 PyObject *op;
227 op = type->tp_alloc(type, 0);
228 if (op != NULL)
229 ((PyComplexObject *)op)->cval = cval;
230 return op;
233 PyObject *
234 PyComplex_FromCComplex(Py_complex cval)
236 register PyComplexObject *op;
238 /* Inline PyObject_New */
239 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
240 if (op == NULL)
241 return PyErr_NoMemory();
242 PyObject_INIT(op, &PyComplex_Type);
243 op->cval = cval;
244 return (PyObject *) op;
247 static PyObject *
248 complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
250 Py_complex c;
251 c.real = real;
252 c.imag = imag;
253 return complex_subtype_from_c_complex(type, c);
256 PyObject *
257 PyComplex_FromDoubles(double real, double imag)
259 Py_complex c;
260 c.real = real;
261 c.imag = imag;
262 return PyComplex_FromCComplex(c);
265 double
266 PyComplex_RealAsDouble(PyObject *op)
268 if (PyComplex_Check(op)) {
269 return ((PyComplexObject *)op)->cval.real;
271 else {
272 return PyFloat_AsDouble(op);
276 double
277 PyComplex_ImagAsDouble(PyObject *op)
279 if (PyComplex_Check(op)) {
280 return ((PyComplexObject *)op)->cval.imag;
282 else {
283 return 0.0;
287 Py_complex
288 PyComplex_AsCComplex(PyObject *op)
290 Py_complex cv;
291 PyObject *newop = NULL;
292 static PyObject *complex_str = NULL;
294 assert(op);
295 /* If op is already of type PyComplex_Type, return its value */
296 if (PyComplex_Check(op)) {
297 return ((PyComplexObject *)op)->cval;
299 /* If not, use op's __complex__ method, if it exists */
301 /* return -1 on failure */
302 cv.real = -1.;
303 cv.imag = 0.;
305 if (complex_str == NULL) {
306 if (!(complex_str = PyString_InternFromString("__complex__")))
307 return cv;
310 if (PyInstance_Check(op)) {
311 /* this can go away in python 3000 */
312 if (PyObject_HasAttr(op, complex_str)) {
313 newop = PyObject_CallMethod(op, "__complex__", NULL);
314 if (!newop)
315 return cv;
317 /* else try __float__ */
318 } else {
319 PyObject *complexfunc;
320 complexfunc = _PyType_Lookup(op->ob_type, complex_str);
321 /* complexfunc is a borrowed reference */
322 if (complexfunc) {
323 newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL);
324 if (!newop)
325 return cv;
329 if (newop) {
330 if (!PyComplex_Check(newop)) {
331 PyErr_SetString(PyExc_TypeError,
332 "__complex__ should return a complex object");
333 Py_DECREF(newop);
334 return cv;
336 cv = ((PyComplexObject *)newop)->cval;
337 Py_DECREF(newop);
338 return cv;
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 cv.real = PyFloat_AsDouble(op);
345 return cv;
349 static void
350 complex_dealloc(PyObject *op)
352 op->ob_type->tp_free(op);
356 static PyObject *
357 complex_format(PyComplexObject *v, char format_code)
359 PyObject *result = NULL;
360 Py_ssize_t len;
362 /* If these are non-NULL, they'll need to be freed. */
363 char *pre = NULL;
364 char *im = NULL;
365 char *buf = NULL;
367 /* These do not need to be freed. re is either an alias
368 for pre or a pointer to a constant. lead and tail
369 are pointers to constants. */
370 char *re = NULL;
371 char *lead = "";
372 char *tail = "";
374 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
375 re = "";
376 im = PyOS_double_to_string(v->cval.imag, format_code,
377 0, 0, NULL);
378 if (!im) {
379 PyErr_NoMemory();
380 goto done;
382 } else {
383 /* Format imaginary part with sign, real part without */
384 pre = PyOS_double_to_string(v->cval.real, format_code,
385 0, 0, NULL);
386 if (!pre) {
387 PyErr_NoMemory();
388 goto done;
390 re = pre;
392 im = PyOS_double_to_string(v->cval.imag, format_code,
393 0, Py_DTSF_SIGN, NULL);
394 if (!im) {
395 PyErr_NoMemory();
396 goto done;
398 lead = "(";
399 tail = ")";
401 /* Alloc the final buffer. Add one for the "j" in the format string,
402 and one for the trailing zero. */
403 len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
404 buf = PyMem_Malloc(len);
405 if (!buf) {
406 PyErr_NoMemory();
407 goto done;
409 PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
410 result = PyString_FromString(buf);
411 done:
412 PyMem_Free(im);
413 PyMem_Free(pre);
414 PyMem_Free(buf);
416 return result;
419 static int
420 complex_print(PyComplexObject *v, FILE *fp, int flags)
422 PyObject *formatv;
423 char *buf;
424 formatv = complex_format(v, (flags & Py_PRINT_RAW) ? 's' : 'r');
425 if (formatv == NULL)
426 return -1;
427 buf = PyString_AS_STRING(formatv);
428 Py_BEGIN_ALLOW_THREADS
429 fputs(buf, fp);
430 Py_END_ALLOW_THREADS
431 Py_DECREF(formatv);
432 return 0;
435 static PyObject *
436 complex_repr(PyComplexObject *v)
438 return complex_format(v, 'r');
441 static PyObject *
442 complex_str(PyComplexObject *v)
444 return complex_format(v, 's');
447 static long
448 complex_hash(PyComplexObject *v)
450 long hashreal, hashimag, combined;
451 hashreal = _Py_HashDouble(v->cval.real);
452 if (hashreal == -1)
453 return -1;
454 hashimag = _Py_HashDouble(v->cval.imag);
455 if (hashimag == -1)
456 return -1;
457 /* Note: if the imaginary part is 0, hashimag is 0 now,
458 * so the following returns hashreal unchanged. This is
459 * important because numbers of different types that
460 * compare equal must have the same hash value, so that
461 * hash(x + 0*j) must equal hash(x).
463 combined = hashreal + 1000003 * hashimag;
464 if (combined == -1)
465 combined = -2;
466 return combined;
469 /* This macro may return! */
470 #define TO_COMPLEX(obj, c) \
471 if (PyComplex_Check(obj)) \
472 c = ((PyComplexObject *)(obj))->cval; \
473 else if (to_complex(&(obj), &(c)) < 0) \
474 return (obj)
476 static int
477 to_complex(PyObject **pobj, Py_complex *pc)
479 PyObject *obj = *pobj;
481 pc->real = pc->imag = 0.0;
482 if (PyInt_Check(obj)) {
483 pc->real = PyInt_AS_LONG(obj);
484 return 0;
486 if (PyLong_Check(obj)) {
487 pc->real = PyLong_AsDouble(obj);
488 if (pc->real == -1.0 && PyErr_Occurred()) {
489 *pobj = NULL;
490 return -1;
492 return 0;
494 if (PyFloat_Check(obj)) {
495 pc->real = PyFloat_AsDouble(obj);
496 return 0;
498 Py_INCREF(Py_NotImplemented);
499 *pobj = Py_NotImplemented;
500 return -1;
504 static PyObject *
505 complex_add(PyComplexObject *v, PyComplexObject *w)
507 Py_complex result;
508 PyFPE_START_PROTECT("complex_add", return 0)
509 result = c_sum(v->cval,w->cval);
510 PyFPE_END_PROTECT(result)
511 return PyComplex_FromCComplex(result);
514 static PyObject *
515 complex_sub(PyComplexObject *v, PyComplexObject *w)
517 Py_complex result;
518 PyFPE_START_PROTECT("complex_sub", return 0)
519 result = c_diff(v->cval,w->cval);
520 PyFPE_END_PROTECT(result)
521 return PyComplex_FromCComplex(result);
524 static PyObject *
525 complex_mul(PyComplexObject *v, PyComplexObject *w)
527 Py_complex result;
528 PyFPE_START_PROTECT("complex_mul", return 0)
529 result = c_prod(v->cval,w->cval);
530 PyFPE_END_PROTECT(result)
531 return PyComplex_FromCComplex(result);
534 static PyObject *
535 complex_div(PyComplexObject *v, PyComplexObject *w)
537 Py_complex quot;
539 PyFPE_START_PROTECT("complex_div", return 0)
540 errno = 0;
541 quot = c_quot(v->cval,w->cval);
542 PyFPE_END_PROTECT(quot)
543 if (errno == EDOM) {
544 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
545 return NULL;
547 return PyComplex_FromCComplex(quot);
550 static PyObject *
551 complex_classic_div(PyComplexObject *v, PyComplexObject *w)
553 Py_complex quot;
555 if (Py_DivisionWarningFlag >= 2 &&
556 PyErr_Warn(PyExc_DeprecationWarning,
557 "classic complex division") < 0)
558 return NULL;
560 PyFPE_START_PROTECT("complex_classic_div", return 0)
561 errno = 0;
562 quot = c_quot(v->cval,w->cval);
563 PyFPE_END_PROTECT(quot)
564 if (errno == EDOM) {
565 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
566 return NULL;
568 return PyComplex_FromCComplex(quot);
571 static PyObject *
572 complex_remainder(PyComplexObject *v, PyComplexObject *w)
574 Py_complex div, mod;
576 if (PyErr_Warn(PyExc_DeprecationWarning,
577 "complex divmod(), // and % are deprecated") < 0)
578 return NULL;
580 errno = 0;
581 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
582 if (errno == EDOM) {
583 PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
584 return NULL;
586 div.real = floor(div.real); /* Use the floor of the real part. */
587 div.imag = 0.0;
588 mod = c_diff(v->cval, c_prod(w->cval, div));
590 return PyComplex_FromCComplex(mod);
594 static PyObject *
595 complex_divmod(PyComplexObject *v, PyComplexObject *w)
597 Py_complex div, mod;
598 PyObject *d, *m, *z;
600 if (PyErr_Warn(PyExc_DeprecationWarning,
601 "complex divmod(), // and % are deprecated") < 0)
602 return NULL;
604 errno = 0;
605 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
606 if (errno == EDOM) {
607 PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
608 return NULL;
610 div.real = floor(div.real); /* Use the floor of the real part. */
611 div.imag = 0.0;
612 mod = c_diff(v->cval, c_prod(w->cval, div));
613 d = PyComplex_FromCComplex(div);
614 m = PyComplex_FromCComplex(mod);
615 z = PyTuple_Pack(2, d, m);
616 Py_XDECREF(d);
617 Py_XDECREF(m);
618 return z;
621 static PyObject *
622 complex_pow(PyObject *v, PyObject *w, PyObject *z)
624 Py_complex p;
625 Py_complex exponent;
626 long int_exponent;
627 Py_complex a, b;
628 TO_COMPLEX(v, a);
629 TO_COMPLEX(w, b);
631 if (z!=Py_None) {
632 PyErr_SetString(PyExc_ValueError, "complex modulo");
633 return NULL;
635 PyFPE_START_PROTECT("complex_pow", return 0)
636 errno = 0;
637 exponent = b;
638 int_exponent = (long)exponent.real;
639 if (exponent.imag == 0. && exponent.real == int_exponent)
640 p = c_powi(a,int_exponent);
641 else
642 p = c_pow(a,exponent);
644 PyFPE_END_PROTECT(p)
645 Py_ADJUST_ERANGE2(p.real, p.imag);
646 if (errno == EDOM) {
647 PyErr_SetString(PyExc_ZeroDivisionError,
648 "0.0 to a negative or complex power");
649 return NULL;
651 else if (errno == ERANGE) {
652 PyErr_SetString(PyExc_OverflowError,
653 "complex exponentiation");
654 return NULL;
656 return PyComplex_FromCComplex(p);
659 static PyObject *
660 complex_int_div(PyComplexObject *v, PyComplexObject *w)
662 PyObject *t, *r;
664 if (PyErr_Warn(PyExc_DeprecationWarning,
665 "complex divmod(), // and % are deprecated") < 0)
666 return NULL;
668 t = complex_divmod(v, w);
669 if (t != NULL) {
670 r = PyTuple_GET_ITEM(t, 0);
671 Py_INCREF(r);
672 Py_DECREF(t);
673 return r;
675 return NULL;
678 static PyObject *
679 complex_neg(PyComplexObject *v)
681 Py_complex neg;
682 neg.real = -v->cval.real;
683 neg.imag = -v->cval.imag;
684 return PyComplex_FromCComplex(neg);
687 static PyObject *
688 complex_pos(PyComplexObject *v)
690 if (PyComplex_CheckExact(v)) {
691 Py_INCREF(v);
692 return (PyObject *)v;
694 else
695 return PyComplex_FromCComplex(v->cval);
698 static PyObject *
699 complex_abs(PyComplexObject *v)
701 double result;
703 PyFPE_START_PROTECT("complex_abs", return 0)
704 result = c_abs(v->cval);
705 PyFPE_END_PROTECT(result)
707 if (errno == ERANGE) {
708 PyErr_SetString(PyExc_OverflowError,
709 "absolute value too large");
710 return NULL;
712 return PyFloat_FromDouble(result);
715 static int
716 complex_nonzero(PyComplexObject *v)
718 return v->cval.real != 0.0 || v->cval.imag != 0.0;
721 static int
722 complex_coerce(PyObject **pv, PyObject **pw)
724 Py_complex cval;
725 cval.imag = 0.;
726 if (PyInt_Check(*pw)) {
727 cval.real = (double)PyInt_AsLong(*pw);
728 *pw = PyComplex_FromCComplex(cval);
729 Py_INCREF(*pv);
730 return 0;
732 else if (PyLong_Check(*pw)) {
733 cval.real = PyLong_AsDouble(*pw);
734 if (cval.real == -1.0 && PyErr_Occurred())
735 return -1;
736 *pw = PyComplex_FromCComplex(cval);
737 Py_INCREF(*pv);
738 return 0;
740 else if (PyFloat_Check(*pw)) {
741 cval.real = PyFloat_AsDouble(*pw);
742 *pw = PyComplex_FromCComplex(cval);
743 Py_INCREF(*pv);
744 return 0;
746 else if (PyComplex_Check(*pw)) {
747 Py_INCREF(*pv);
748 Py_INCREF(*pw);
749 return 0;
751 return 1; /* Can't do it */
754 static PyObject *
755 complex_richcompare(PyObject *v, PyObject *w, int op)
757 int c;
758 Py_complex i, j;
759 PyObject *res;
761 c = PyNumber_CoerceEx(&v, &w);
762 if (c < 0)
763 return NULL;
764 if (c > 0) {
765 Py_INCREF(Py_NotImplemented);
766 return Py_NotImplemented;
768 /* Make sure both arguments are complex. */
769 if (!(PyComplex_Check(v) && PyComplex_Check(w))) {
770 Py_DECREF(v);
771 Py_DECREF(w);
772 Py_INCREF(Py_NotImplemented);
773 return Py_NotImplemented;
776 i = ((PyComplexObject *)v)->cval;
777 j = ((PyComplexObject *)w)->cval;
778 Py_DECREF(v);
779 Py_DECREF(w);
781 if (op != Py_EQ && op != Py_NE) {
782 PyErr_SetString(PyExc_TypeError,
783 "no ordering relation is defined for complex numbers");
784 return NULL;
787 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
788 res = Py_True;
789 else
790 res = Py_False;
792 Py_INCREF(res);
793 return res;
796 static PyObject *
797 complex_int(PyObject *v)
799 PyErr_SetString(PyExc_TypeError,
800 "can't convert complex to int; use int(abs(z))");
801 return NULL;
804 static PyObject *
805 complex_long(PyObject *v)
807 PyErr_SetString(PyExc_TypeError,
808 "can't convert complex to long; use long(abs(z))");
809 return NULL;
812 static PyObject *
813 complex_float(PyObject *v)
815 PyErr_SetString(PyExc_TypeError,
816 "can't convert complex to float; use abs(z)");
817 return NULL;
820 static PyObject *
821 complex_conjugate(PyObject *self)
823 Py_complex c;
824 c = ((PyComplexObject *)self)->cval;
825 c.imag = -c.imag;
826 return PyComplex_FromCComplex(c);
829 PyDoc_STRVAR(complex_conjugate_doc,
830 "complex.conjugate() -> complex\n"
831 "\n"
832 "Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
834 static PyObject *
835 complex_getnewargs(PyComplexObject *v)
837 Py_complex c = v->cval;
838 return Py_BuildValue("(dd)", c.real, c.imag);
841 PyDoc_STRVAR(complex__format__doc,
842 "complex.__format__() -> str\n"
843 "\n"
844 "Converts to a string according to format_spec.");
846 static PyObject *
847 complex__format__(PyObject* self, PyObject* args)
849 PyObject *format_spec;
851 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
852 return NULL;
853 if (PyBytes_Check(format_spec))
854 return _PyComplex_FormatAdvanced(self,
855 PyBytes_AS_STRING(format_spec),
856 PyBytes_GET_SIZE(format_spec));
857 if (PyUnicode_Check(format_spec)) {
858 /* Convert format_spec to a str */
859 PyObject *result;
860 PyObject *str_spec = PyObject_Str(format_spec);
862 if (str_spec == NULL)
863 return NULL;
865 result = _PyComplex_FormatAdvanced(self,
866 PyBytes_AS_STRING(str_spec),
867 PyBytes_GET_SIZE(str_spec));
869 Py_DECREF(str_spec);
870 return result;
872 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
873 return NULL;
876 #if 0
877 static PyObject *
878 complex_is_finite(PyObject *self)
880 Py_complex c;
881 c = ((PyComplexObject *)self)->cval;
882 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
883 Py_IS_FINITE(c.imag)));
886 PyDoc_STRVAR(complex_is_finite_doc,
887 "complex.is_finite() -> bool\n"
888 "\n"
889 "Returns True if the real and the imaginary part is finite.");
890 #endif
892 static PyMethodDef complex_methods[] = {
893 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
894 complex_conjugate_doc},
895 #if 0
896 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
897 complex_is_finite_doc},
898 #endif
899 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
900 {"__format__", (PyCFunction)complex__format__,
901 METH_VARARGS, complex__format__doc},
902 {NULL, NULL} /* sentinel */
905 static PyMemberDef complex_members[] = {
906 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
907 "the real part of a complex number"},
908 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
909 "the imaginary part of a complex number"},
910 {0},
913 static PyObject *
914 complex_subtype_from_string(PyTypeObject *type, PyObject *v)
916 const char *s, *start;
917 char *end;
918 double x=0.0, y=0.0, z;
919 int got_bracket=0;
920 #ifdef Py_USING_UNICODE
921 char s_buffer[256];
922 #endif
923 Py_ssize_t len;
925 if (PyString_Check(v)) {
926 s = PyString_AS_STRING(v);
927 len = PyString_GET_SIZE(v);
929 #ifdef Py_USING_UNICODE
930 else if (PyUnicode_Check(v)) {
931 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
932 PyErr_SetString(PyExc_ValueError,
933 "complex() literal too large to convert");
934 return NULL;
936 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
937 PyUnicode_GET_SIZE(v),
938 s_buffer,
939 NULL))
940 return NULL;
941 s = s_buffer;
942 len = strlen(s);
944 #endif
945 else if (PyObject_AsCharBuffer(v, &s, &len)) {
946 PyErr_SetString(PyExc_TypeError,
947 "complex() arg is not a string");
948 return NULL;
951 /* position on first nonblank */
952 start = s;
953 while (*s && isspace(Py_CHARMASK(*s)))
954 s++;
955 if (*s == '(') {
956 /* Skip over possible bracket from repr(). */
957 got_bracket = 1;
958 s++;
959 while (*s && isspace(Py_CHARMASK(*s)))
960 s++;
963 /* a valid complex string usually takes one of the three forms:
965 <float> - real part only
966 <float>j - imaginary part only
967 <float><signed-float>j - real and imaginary parts
969 where <float> represents any numeric string that's accepted by the
970 float constructor (including 'nan', 'inf', 'infinity', etc.), and
971 <signed-float> is any string of the form <float> whose first
972 character is '+' or '-'.
974 For backwards compatibility, the extra forms
976 <float><sign>j
977 <sign>j
980 are also accepted, though support for these forms may be removed from
981 a future version of Python.
984 /* first look for forms starting with <float> */
985 errno = 0;
986 z = PyOS_ascii_strtod(s, &end);
987 if (end == s && errno == ENOMEM)
988 return PyErr_NoMemory();
989 if (errno == ERANGE && fabs(z) >= 1.0)
990 goto overflow;
992 if (end != s) {
993 /* all 4 forms starting with <float> land here */
994 s = end;
995 if (*s == '+' || *s == '-') {
996 /* <float><signed-float>j | <float><sign>j */
997 x = z;
998 errno = 0;
999 y = PyOS_ascii_strtod(s, &end);
1000 if (end == s && errno == ENOMEM)
1001 return PyErr_NoMemory();
1002 if (errno == ERANGE && fabs(y) >= 1.0)
1003 goto overflow;
1004 if (end != s)
1005 /* <float><signed-float>j */
1006 s = end;
1007 else {
1008 /* <float><sign>j */
1009 y = *s == '+' ? 1.0 : -1.0;
1010 s++;
1012 if (!(*s == 'j' || *s == 'J'))
1013 goto parse_error;
1014 s++;
1016 else if (*s == 'j' || *s == 'J') {
1017 /* <float>j */
1018 s++;
1019 y = z;
1021 else
1022 /* <float> */
1023 x = z;
1025 else {
1026 /* not starting with <float>; must be <sign>j or j */
1027 if (*s == '+' || *s == '-') {
1028 /* <sign>j */
1029 y = *s == '+' ? 1.0 : -1.0;
1030 s++;
1032 else
1033 /* j */
1034 y = 1.0;
1035 if (!(*s == 'j' || *s == 'J'))
1036 goto parse_error;
1037 s++;
1040 /* trailing whitespace and closing bracket */
1041 while (*s && isspace(Py_CHARMASK(*s)))
1042 s++;
1043 if (got_bracket) {
1044 /* if there was an opening parenthesis, then the corresponding
1045 closing parenthesis should be right here */
1046 if (*s != ')')
1047 goto parse_error;
1048 s++;
1049 while (*s && isspace(Py_CHARMASK(*s)))
1050 s++;
1053 /* we should now be at the end of the string */
1054 if (s-start != len)
1055 goto parse_error;
1057 return complex_subtype_from_doubles(type, x, y);
1059 parse_error:
1060 PyErr_SetString(PyExc_ValueError,
1061 "complex() arg is a malformed string");
1062 return NULL;
1064 overflow:
1065 PyErr_SetString(PyExc_OverflowError,
1066 "complex() arg overflow");
1067 return NULL;
1070 static PyObject *
1071 complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1073 PyObject *r, *i, *tmp, *f;
1074 PyNumberMethods *nbr, *nbi = NULL;
1075 Py_complex cr, ci;
1076 int own_r = 0;
1077 int cr_is_complex = 0;
1078 int ci_is_complex = 0;
1079 static PyObject *complexstr;
1080 static char *kwlist[] = {"real", "imag", 0};
1082 r = Py_False;
1083 i = NULL;
1084 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
1085 &r, &i))
1086 return NULL;
1088 /* Special-case for a single argument when type(arg) is complex. */
1089 if (PyComplex_CheckExact(r) && i == NULL &&
1090 type == &PyComplex_Type) {
1091 /* Note that we can't know whether it's safe to return
1092 a complex *subclass* instance as-is, hence the restriction
1093 to exact complexes here. If either the input or the
1094 output is a complex subclass, it will be handled below
1095 as a non-orthogonal vector. */
1096 Py_INCREF(r);
1097 return r;
1099 if (PyString_Check(r) || PyUnicode_Check(r)) {
1100 if (i != NULL) {
1101 PyErr_SetString(PyExc_TypeError,
1102 "complex() can't take second arg"
1103 " if first is a string");
1104 return NULL;
1106 return complex_subtype_from_string(type, r);
1108 if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
1109 PyErr_SetString(PyExc_TypeError,
1110 "complex() second arg can't be a string");
1111 return NULL;
1114 /* XXX Hack to support classes with __complex__ method */
1115 if (complexstr == NULL) {
1116 complexstr = PyString_InternFromString("__complex__");
1117 if (complexstr == NULL)
1118 return NULL;
1120 f = PyObject_GetAttr(r, complexstr);
1121 if (f == NULL)
1122 PyErr_Clear();
1123 else {
1124 PyObject *args = PyTuple_New(0);
1125 if (args == NULL)
1126 return NULL;
1127 r = PyEval_CallObject(f, args);
1128 Py_DECREF(args);
1129 Py_DECREF(f);
1130 if (r == NULL)
1131 return NULL;
1132 own_r = 1;
1134 nbr = r->ob_type->tp_as_number;
1135 if (i != NULL)
1136 nbi = i->ob_type->tp_as_number;
1137 if (nbr == NULL || nbr->nb_float == NULL ||
1138 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
1139 PyErr_SetString(PyExc_TypeError,
1140 "complex() argument must be a string or a number");
1141 if (own_r) {
1142 Py_DECREF(r);
1144 return NULL;
1147 /* If we get this far, then the "real" and "imag" parts should
1148 both be treated as numbers, and the constructor should return a
1149 complex number equal to (real + imag*1j).
1151 Note that we do NOT assume the input to already be in canonical
1152 form; the "real" and "imag" parts might themselves be complex
1153 numbers, which slightly complicates the code below. */
1154 if (PyComplex_Check(r)) {
1155 /* Note that if r is of a complex subtype, we're only
1156 retaining its real & imag parts here, and the return
1157 value is (properly) of the builtin complex type. */
1158 cr = ((PyComplexObject*)r)->cval;
1159 cr_is_complex = 1;
1160 if (own_r) {
1161 Py_DECREF(r);
1164 else {
1165 /* The "real" part really is entirely real, and contributes
1166 nothing in the imaginary direction.
1167 Just treat it as a double. */
1168 tmp = PyNumber_Float(r);
1169 if (own_r) {
1170 /* r was a newly created complex number, rather
1171 than the original "real" argument. */
1172 Py_DECREF(r);
1174 if (tmp == NULL)
1175 return NULL;
1176 if (!PyFloat_Check(tmp)) {
1177 PyErr_SetString(PyExc_TypeError,
1178 "float(r) didn't return a float");
1179 Py_DECREF(tmp);
1180 return NULL;
1182 cr.real = PyFloat_AsDouble(tmp);
1183 cr.imag = 0.0; /* Shut up compiler warning */
1184 Py_DECREF(tmp);
1186 if (i == NULL) {
1187 ci.real = 0.0;
1189 else if (PyComplex_Check(i)) {
1190 ci = ((PyComplexObject*)i)->cval;
1191 ci_is_complex = 1;
1192 } else {
1193 /* The "imag" part really is entirely imaginary, and
1194 contributes nothing in the real direction.
1195 Just treat it as a double. */
1196 tmp = (*nbi->nb_float)(i);
1197 if (tmp == NULL)
1198 return NULL;
1199 ci.real = PyFloat_AsDouble(tmp);
1200 Py_DECREF(tmp);
1202 /* If the input was in canonical form, then the "real" and "imag"
1203 parts are real numbers, so that ci.imag and cr.imag are zero.
1204 We need this correction in case they were not real numbers. */
1206 if (ci_is_complex) {
1207 cr.real -= ci.imag;
1209 if (cr_is_complex) {
1210 ci.real += cr.imag;
1212 return complex_subtype_from_doubles(type, cr.real, ci.real);
1215 PyDoc_STRVAR(complex_doc,
1216 "complex(real[, imag]) -> complex number\n"
1217 "\n"
1218 "Create a complex number from a real part and an optional imaginary part.\n"
1219 "This is equivalent to (real + imag*1j) where imag defaults to 0.");
1221 static PyNumberMethods complex_as_number = {
1222 (binaryfunc)complex_add, /* nb_add */
1223 (binaryfunc)complex_sub, /* nb_subtract */
1224 (binaryfunc)complex_mul, /* nb_multiply */
1225 (binaryfunc)complex_classic_div, /* nb_divide */
1226 (binaryfunc)complex_remainder, /* nb_remainder */
1227 (binaryfunc)complex_divmod, /* nb_divmod */
1228 (ternaryfunc)complex_pow, /* nb_power */
1229 (unaryfunc)complex_neg, /* nb_negative */
1230 (unaryfunc)complex_pos, /* nb_positive */
1231 (unaryfunc)complex_abs, /* nb_absolute */
1232 (inquiry)complex_nonzero, /* nb_nonzero */
1233 0, /* nb_invert */
1234 0, /* nb_lshift */
1235 0, /* nb_rshift */
1236 0, /* nb_and */
1237 0, /* nb_xor */
1238 0, /* nb_or */
1239 complex_coerce, /* nb_coerce */
1240 complex_int, /* nb_int */
1241 complex_long, /* nb_long */
1242 complex_float, /* nb_float */
1243 0, /* nb_oct */
1244 0, /* nb_hex */
1245 0, /* nb_inplace_add */
1246 0, /* nb_inplace_subtract */
1247 0, /* nb_inplace_multiply*/
1248 0, /* nb_inplace_divide */
1249 0, /* nb_inplace_remainder */
1250 0, /* nb_inplace_power */
1251 0, /* nb_inplace_lshift */
1252 0, /* nb_inplace_rshift */
1253 0, /* nb_inplace_and */
1254 0, /* nb_inplace_xor */
1255 0, /* nb_inplace_or */
1256 (binaryfunc)complex_int_div, /* nb_floor_divide */
1257 (binaryfunc)complex_div, /* nb_true_divide */
1258 0, /* nb_inplace_floor_divide */
1259 0, /* nb_inplace_true_divide */
1262 PyTypeObject PyComplex_Type = {
1263 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1264 "complex",
1265 sizeof(PyComplexObject),
1267 complex_dealloc, /* tp_dealloc */
1268 (printfunc)complex_print, /* tp_print */
1269 0, /* tp_getattr */
1270 0, /* tp_setattr */
1271 0, /* tp_compare */
1272 (reprfunc)complex_repr, /* tp_repr */
1273 &complex_as_number, /* tp_as_number */
1274 0, /* tp_as_sequence */
1275 0, /* tp_as_mapping */
1276 (hashfunc)complex_hash, /* tp_hash */
1277 0, /* tp_call */
1278 (reprfunc)complex_str, /* tp_str */
1279 PyObject_GenericGetAttr, /* tp_getattro */
1280 0, /* tp_setattro */
1281 0, /* tp_as_buffer */
1282 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1283 complex_doc, /* tp_doc */
1284 0, /* tp_traverse */
1285 0, /* tp_clear */
1286 complex_richcompare, /* tp_richcompare */
1287 0, /* tp_weaklistoffset */
1288 0, /* tp_iter */
1289 0, /* tp_iternext */
1290 complex_methods, /* tp_methods */
1291 complex_members, /* tp_members */
1292 0, /* tp_getset */
1293 0, /* tp_base */
1294 0, /* tp_dict */
1295 0, /* tp_descr_get */
1296 0, /* tp_descr_set */
1297 0, /* tp_dictoffset */
1298 0, /* tp_init */
1299 PyType_GenericAlloc, /* tp_alloc */
1300 complex_new, /* tp_new */
1301 PyObject_Del, /* tp_free */
1304 #endif