Issue #7233: Fix Decimal.shift and Decimal.rotate methods for
[python.git] / Objects / complexobject.c
blobf277b6625c13a0a0a1d375f4c26743a84992fe74
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, int precision, 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 precision, 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 precision, 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 precision, 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 if (flags & Py_PRINT_RAW)
425 formatv = complex_format(v, PyFloat_STR_PRECISION, 'g');
426 else
427 formatv = complex_format(v, 0, 'r');
428 if (formatv == NULL)
429 return -1;
430 buf = PyString_AS_STRING(formatv);
431 Py_BEGIN_ALLOW_THREADS
432 fputs(buf, fp);
433 Py_END_ALLOW_THREADS
434 Py_DECREF(formatv);
435 return 0;
438 static PyObject *
439 complex_repr(PyComplexObject *v)
441 return complex_format(v, 0, 'r');
444 static PyObject *
445 complex_str(PyComplexObject *v)
447 return complex_format(v, PyFloat_STR_PRECISION, 'g');
450 static long
451 complex_hash(PyComplexObject *v)
453 long hashreal, hashimag, combined;
454 hashreal = _Py_HashDouble(v->cval.real);
455 if (hashreal == -1)
456 return -1;
457 hashimag = _Py_HashDouble(v->cval.imag);
458 if (hashimag == -1)
459 return -1;
460 /* Note: if the imaginary part is 0, hashimag is 0 now,
461 * so the following returns hashreal unchanged. This is
462 * important because numbers of different types that
463 * compare equal must have the same hash value, so that
464 * hash(x + 0*j) must equal hash(x).
466 combined = hashreal + 1000003 * hashimag;
467 if (combined == -1)
468 combined = -2;
469 return combined;
472 /* This macro may return! */
473 #define TO_COMPLEX(obj, c) \
474 if (PyComplex_Check(obj)) \
475 c = ((PyComplexObject *)(obj))->cval; \
476 else if (to_complex(&(obj), &(c)) < 0) \
477 return (obj)
479 static int
480 to_complex(PyObject **pobj, Py_complex *pc)
482 PyObject *obj = *pobj;
484 pc->real = pc->imag = 0.0;
485 if (PyInt_Check(obj)) {
486 pc->real = PyInt_AS_LONG(obj);
487 return 0;
489 if (PyLong_Check(obj)) {
490 pc->real = PyLong_AsDouble(obj);
491 if (pc->real == -1.0 && PyErr_Occurred()) {
492 *pobj = NULL;
493 return -1;
495 return 0;
497 if (PyFloat_Check(obj)) {
498 pc->real = PyFloat_AsDouble(obj);
499 return 0;
501 Py_INCREF(Py_NotImplemented);
502 *pobj = Py_NotImplemented;
503 return -1;
507 static PyObject *
508 complex_add(PyComplexObject *v, PyComplexObject *w)
510 Py_complex result;
511 PyFPE_START_PROTECT("complex_add", return 0)
512 result = c_sum(v->cval,w->cval);
513 PyFPE_END_PROTECT(result)
514 return PyComplex_FromCComplex(result);
517 static PyObject *
518 complex_sub(PyComplexObject *v, PyComplexObject *w)
520 Py_complex result;
521 PyFPE_START_PROTECT("complex_sub", return 0)
522 result = c_diff(v->cval,w->cval);
523 PyFPE_END_PROTECT(result)
524 return PyComplex_FromCComplex(result);
527 static PyObject *
528 complex_mul(PyComplexObject *v, PyComplexObject *w)
530 Py_complex result;
531 PyFPE_START_PROTECT("complex_mul", return 0)
532 result = c_prod(v->cval,w->cval);
533 PyFPE_END_PROTECT(result)
534 return PyComplex_FromCComplex(result);
537 static PyObject *
538 complex_div(PyComplexObject *v, PyComplexObject *w)
540 Py_complex quot;
542 PyFPE_START_PROTECT("complex_div", return 0)
543 errno = 0;
544 quot = c_quot(v->cval,w->cval);
545 PyFPE_END_PROTECT(quot)
546 if (errno == EDOM) {
547 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
548 return NULL;
550 return PyComplex_FromCComplex(quot);
553 static PyObject *
554 complex_classic_div(PyComplexObject *v, PyComplexObject *w)
556 Py_complex quot;
558 if (Py_DivisionWarningFlag >= 2 &&
559 PyErr_Warn(PyExc_DeprecationWarning,
560 "classic complex division") < 0)
561 return NULL;
563 PyFPE_START_PROTECT("complex_classic_div", return 0)
564 errno = 0;
565 quot = c_quot(v->cval,w->cval);
566 PyFPE_END_PROTECT(quot)
567 if (errno == EDOM) {
568 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
569 return NULL;
571 return PyComplex_FromCComplex(quot);
574 static PyObject *
575 complex_remainder(PyComplexObject *v, PyComplexObject *w)
577 Py_complex div, mod;
579 if (PyErr_Warn(PyExc_DeprecationWarning,
580 "complex divmod(), // and % are deprecated") < 0)
581 return NULL;
583 errno = 0;
584 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
585 if (errno == EDOM) {
586 PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
587 return NULL;
589 div.real = floor(div.real); /* Use the floor of the real part. */
590 div.imag = 0.0;
591 mod = c_diff(v->cval, c_prod(w->cval, div));
593 return PyComplex_FromCComplex(mod);
597 static PyObject *
598 complex_divmod(PyComplexObject *v, PyComplexObject *w)
600 Py_complex div, mod;
601 PyObject *d, *m, *z;
603 if (PyErr_Warn(PyExc_DeprecationWarning,
604 "complex divmod(), // and % are deprecated") < 0)
605 return NULL;
607 errno = 0;
608 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
609 if (errno == EDOM) {
610 PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
611 return NULL;
613 div.real = floor(div.real); /* Use the floor of the real part. */
614 div.imag = 0.0;
615 mod = c_diff(v->cval, c_prod(w->cval, div));
616 d = PyComplex_FromCComplex(div);
617 m = PyComplex_FromCComplex(mod);
618 z = PyTuple_Pack(2, d, m);
619 Py_XDECREF(d);
620 Py_XDECREF(m);
621 return z;
624 static PyObject *
625 complex_pow(PyObject *v, PyObject *w, PyObject *z)
627 Py_complex p;
628 Py_complex exponent;
629 long int_exponent;
630 Py_complex a, b;
631 TO_COMPLEX(v, a);
632 TO_COMPLEX(w, b);
634 if (z!=Py_None) {
635 PyErr_SetString(PyExc_ValueError, "complex modulo");
636 return NULL;
638 PyFPE_START_PROTECT("complex_pow", return 0)
639 errno = 0;
640 exponent = b;
641 int_exponent = (long)exponent.real;
642 if (exponent.imag == 0. && exponent.real == int_exponent)
643 p = c_powi(a,int_exponent);
644 else
645 p = c_pow(a,exponent);
647 PyFPE_END_PROTECT(p)
648 Py_ADJUST_ERANGE2(p.real, p.imag);
649 if (errno == EDOM) {
650 PyErr_SetString(PyExc_ZeroDivisionError,
651 "0.0 to a negative or complex power");
652 return NULL;
654 else if (errno == ERANGE) {
655 PyErr_SetString(PyExc_OverflowError,
656 "complex exponentiation");
657 return NULL;
659 return PyComplex_FromCComplex(p);
662 static PyObject *
663 complex_int_div(PyComplexObject *v, PyComplexObject *w)
665 PyObject *t, *r;
667 if (PyErr_Warn(PyExc_DeprecationWarning,
668 "complex divmod(), // and % are deprecated") < 0)
669 return NULL;
671 t = complex_divmod(v, w);
672 if (t != NULL) {
673 r = PyTuple_GET_ITEM(t, 0);
674 Py_INCREF(r);
675 Py_DECREF(t);
676 return r;
678 return NULL;
681 static PyObject *
682 complex_neg(PyComplexObject *v)
684 Py_complex neg;
685 neg.real = -v->cval.real;
686 neg.imag = -v->cval.imag;
687 return PyComplex_FromCComplex(neg);
690 static PyObject *
691 complex_pos(PyComplexObject *v)
693 if (PyComplex_CheckExact(v)) {
694 Py_INCREF(v);
695 return (PyObject *)v;
697 else
698 return PyComplex_FromCComplex(v->cval);
701 static PyObject *
702 complex_abs(PyComplexObject *v)
704 double result;
706 PyFPE_START_PROTECT("complex_abs", return 0)
707 result = c_abs(v->cval);
708 PyFPE_END_PROTECT(result)
710 if (errno == ERANGE) {
711 PyErr_SetString(PyExc_OverflowError,
712 "absolute value too large");
713 return NULL;
715 return PyFloat_FromDouble(result);
718 static int
719 complex_nonzero(PyComplexObject *v)
721 return v->cval.real != 0.0 || v->cval.imag != 0.0;
724 static int
725 complex_coerce(PyObject **pv, PyObject **pw)
727 Py_complex cval;
728 cval.imag = 0.;
729 if (PyInt_Check(*pw)) {
730 cval.real = (double)PyInt_AsLong(*pw);
731 *pw = PyComplex_FromCComplex(cval);
732 Py_INCREF(*pv);
733 return 0;
735 else if (PyLong_Check(*pw)) {
736 cval.real = PyLong_AsDouble(*pw);
737 if (cval.real == -1.0 && PyErr_Occurred())
738 return -1;
739 *pw = PyComplex_FromCComplex(cval);
740 Py_INCREF(*pv);
741 return 0;
743 else if (PyFloat_Check(*pw)) {
744 cval.real = PyFloat_AsDouble(*pw);
745 *pw = PyComplex_FromCComplex(cval);
746 Py_INCREF(*pv);
747 return 0;
749 else if (PyComplex_Check(*pw)) {
750 Py_INCREF(*pv);
751 Py_INCREF(*pw);
752 return 0;
754 return 1; /* Can't do it */
757 static PyObject *
758 complex_richcompare(PyObject *v, PyObject *w, int op)
760 int c;
761 Py_complex i, j;
762 PyObject *res;
764 c = PyNumber_CoerceEx(&v, &w);
765 if (c < 0)
766 return NULL;
767 if (c > 0) {
768 Py_INCREF(Py_NotImplemented);
769 return Py_NotImplemented;
771 /* Make sure both arguments are complex. */
772 if (!(PyComplex_Check(v) && PyComplex_Check(w))) {
773 Py_DECREF(v);
774 Py_DECREF(w);
775 Py_INCREF(Py_NotImplemented);
776 return Py_NotImplemented;
779 i = ((PyComplexObject *)v)->cval;
780 j = ((PyComplexObject *)w)->cval;
781 Py_DECREF(v);
782 Py_DECREF(w);
784 if (op != Py_EQ && op != Py_NE) {
785 PyErr_SetString(PyExc_TypeError,
786 "no ordering relation is defined for complex numbers");
787 return NULL;
790 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
791 res = Py_True;
792 else
793 res = Py_False;
795 Py_INCREF(res);
796 return res;
799 static PyObject *
800 complex_int(PyObject *v)
802 PyErr_SetString(PyExc_TypeError,
803 "can't convert complex to int");
804 return NULL;
807 static PyObject *
808 complex_long(PyObject *v)
810 PyErr_SetString(PyExc_TypeError,
811 "can't convert complex to long");
812 return NULL;
815 static PyObject *
816 complex_float(PyObject *v)
818 PyErr_SetString(PyExc_TypeError,
819 "can't convert complex to float");
820 return NULL;
823 static PyObject *
824 complex_conjugate(PyObject *self)
826 Py_complex c;
827 c = ((PyComplexObject *)self)->cval;
828 c.imag = -c.imag;
829 return PyComplex_FromCComplex(c);
832 PyDoc_STRVAR(complex_conjugate_doc,
833 "complex.conjugate() -> complex\n"
834 "\n"
835 "Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
837 static PyObject *
838 complex_getnewargs(PyComplexObject *v)
840 Py_complex c = v->cval;
841 return Py_BuildValue("(dd)", c.real, c.imag);
844 PyDoc_STRVAR(complex__format__doc,
845 "complex.__format__() -> str\n"
846 "\n"
847 "Converts to a string according to format_spec.");
849 static PyObject *
850 complex__format__(PyObject* self, PyObject* args)
852 PyObject *format_spec;
854 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
855 return NULL;
856 if (PyBytes_Check(format_spec))
857 return _PyComplex_FormatAdvanced(self,
858 PyBytes_AS_STRING(format_spec),
859 PyBytes_GET_SIZE(format_spec));
860 if (PyUnicode_Check(format_spec)) {
861 /* Convert format_spec to a str */
862 PyObject *result;
863 PyObject *str_spec = PyObject_Str(format_spec);
865 if (str_spec == NULL)
866 return NULL;
868 result = _PyComplex_FormatAdvanced(self,
869 PyBytes_AS_STRING(str_spec),
870 PyBytes_GET_SIZE(str_spec));
872 Py_DECREF(str_spec);
873 return result;
875 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
876 return NULL;
879 #if 0
880 static PyObject *
881 complex_is_finite(PyObject *self)
883 Py_complex c;
884 c = ((PyComplexObject *)self)->cval;
885 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
886 Py_IS_FINITE(c.imag)));
889 PyDoc_STRVAR(complex_is_finite_doc,
890 "complex.is_finite() -> bool\n"
891 "\n"
892 "Returns True if the real and the imaginary part is finite.");
893 #endif
895 static PyMethodDef complex_methods[] = {
896 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
897 complex_conjugate_doc},
898 #if 0
899 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
900 complex_is_finite_doc},
901 #endif
902 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
903 {"__format__", (PyCFunction)complex__format__,
904 METH_VARARGS, complex__format__doc},
905 {NULL, NULL} /* sentinel */
908 static PyMemberDef complex_members[] = {
909 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
910 "the real part of a complex number"},
911 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
912 "the imaginary part of a complex number"},
913 {0},
916 static PyObject *
917 complex_subtype_from_string(PyTypeObject *type, PyObject *v)
919 const char *s, *start;
920 char *end;
921 double x=0.0, y=0.0, z;
922 int got_bracket=0;
923 #ifdef Py_USING_UNICODE
924 char *s_buffer = NULL;
925 #endif
926 Py_ssize_t len;
928 if (PyString_Check(v)) {
929 s = PyString_AS_STRING(v);
930 len = PyString_GET_SIZE(v);
932 #ifdef Py_USING_UNICODE
933 else if (PyUnicode_Check(v)) {
934 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
935 if (s_buffer == NULL)
936 return PyErr_NoMemory();
937 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
938 PyUnicode_GET_SIZE(v),
939 s_buffer,
940 NULL))
941 goto error;
942 s = s_buffer;
943 len = strlen(s);
945 #endif
946 else if (PyObject_AsCharBuffer(v, &s, &len)) {
947 PyErr_SetString(PyExc_TypeError,
948 "complex() arg is not a string");
949 return NULL;
952 /* position on first nonblank */
953 start = s;
954 while (Py_ISSPACE(*s))
955 s++;
956 if (*s == '(') {
957 /* Skip over possible bracket from repr(). */
958 got_bracket = 1;
959 s++;
960 while (Py_ISSPACE(*s))
961 s++;
964 /* a valid complex string usually takes one of the three forms:
966 <float> - real part only
967 <float>j - imaginary part only
968 <float><signed-float>j - real and imaginary parts
970 where <float> represents any numeric string that's accepted by the
971 float constructor (including 'nan', 'inf', 'infinity', etc.), and
972 <signed-float> is any string of the form <float> whose first
973 character is '+' or '-'.
975 For backwards compatibility, the extra forms
977 <float><sign>j
978 <sign>j
981 are also accepted, though support for these forms may be removed from
982 a future version of Python.
985 /* first look for forms starting with <float> */
986 z = PyOS_string_to_double(s, &end, NULL);
987 if (z == -1.0 && PyErr_Occurred()) {
988 if (PyErr_ExceptionMatches(PyExc_ValueError))
989 PyErr_Clear();
990 else
991 goto error;
993 if (end != s) {
994 /* all 4 forms starting with <float> land here */
995 s = end;
996 if (*s == '+' || *s == '-') {
997 /* <float><signed-float>j | <float><sign>j */
998 x = z;
999 y = PyOS_string_to_double(s, &end, NULL);
1000 if (y == -1.0 && PyErr_Occurred()) {
1001 if (PyErr_ExceptionMatches(PyExc_ValueError))
1002 PyErr_Clear();
1003 else
1004 goto error;
1006 if (end != s)
1007 /* <float><signed-float>j */
1008 s = end;
1009 else {
1010 /* <float><sign>j */
1011 y = *s == '+' ? 1.0 : -1.0;
1012 s++;
1014 if (!(*s == 'j' || *s == 'J'))
1015 goto parse_error;
1016 s++;
1018 else if (*s == 'j' || *s == 'J') {
1019 /* <float>j */
1020 s++;
1021 y = z;
1023 else
1024 /* <float> */
1025 x = z;
1027 else {
1028 /* not starting with <float>; must be <sign>j or j */
1029 if (*s == '+' || *s == '-') {
1030 /* <sign>j */
1031 y = *s == '+' ? 1.0 : -1.0;
1032 s++;
1034 else
1035 /* j */
1036 y = 1.0;
1037 if (!(*s == 'j' || *s == 'J'))
1038 goto parse_error;
1039 s++;
1042 /* trailing whitespace and closing bracket */
1043 while (Py_ISSPACE(*s))
1044 s++;
1045 if (got_bracket) {
1046 /* if there was an opening parenthesis, then the corresponding
1047 closing parenthesis should be right here */
1048 if (*s != ')')
1049 goto parse_error;
1050 s++;
1051 while (Py_ISSPACE(*s))
1052 s++;
1055 /* we should now be at the end of the string */
1056 if (s-start != len)
1057 goto parse_error;
1060 #ifdef Py_USING_UNICODE
1061 if (s_buffer)
1062 PyMem_FREE(s_buffer);
1063 #endif
1064 return complex_subtype_from_doubles(type, x, y);
1066 parse_error:
1067 PyErr_SetString(PyExc_ValueError,
1068 "complex() arg is a malformed string");
1069 error:
1070 #ifdef Py_USING_UNICODE
1071 if (s_buffer)
1072 PyMem_FREE(s_buffer);
1073 #endif
1074 return NULL;
1077 static PyObject *
1078 complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1080 PyObject *r, *i, *tmp, *f;
1081 PyNumberMethods *nbr, *nbi = NULL;
1082 Py_complex cr, ci;
1083 int own_r = 0;
1084 int cr_is_complex = 0;
1085 int ci_is_complex = 0;
1086 static PyObject *complexstr;
1087 static char *kwlist[] = {"real", "imag", 0};
1089 r = Py_False;
1090 i = NULL;
1091 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
1092 &r, &i))
1093 return NULL;
1095 /* Special-case for a single argument when type(arg) is complex. */
1096 if (PyComplex_CheckExact(r) && i == NULL &&
1097 type == &PyComplex_Type) {
1098 /* Note that we can't know whether it's safe to return
1099 a complex *subclass* instance as-is, hence the restriction
1100 to exact complexes here. If either the input or the
1101 output is a complex subclass, it will be handled below
1102 as a non-orthogonal vector. */
1103 Py_INCREF(r);
1104 return r;
1106 if (PyString_Check(r) || PyUnicode_Check(r)) {
1107 if (i != NULL) {
1108 PyErr_SetString(PyExc_TypeError,
1109 "complex() can't take second arg"
1110 " if first is a string");
1111 return NULL;
1113 return complex_subtype_from_string(type, r);
1115 if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
1116 PyErr_SetString(PyExc_TypeError,
1117 "complex() second arg can't be a string");
1118 return NULL;
1121 /* XXX Hack to support classes with __complex__ method */
1122 if (complexstr == NULL) {
1123 complexstr = PyString_InternFromString("__complex__");
1124 if (complexstr == NULL)
1125 return NULL;
1127 f = PyObject_GetAttr(r, complexstr);
1128 if (f == NULL)
1129 PyErr_Clear();
1130 else {
1131 PyObject *args = PyTuple_New(0);
1132 if (args == NULL)
1133 return NULL;
1134 r = PyEval_CallObject(f, args);
1135 Py_DECREF(args);
1136 Py_DECREF(f);
1137 if (r == NULL)
1138 return NULL;
1139 own_r = 1;
1141 nbr = r->ob_type->tp_as_number;
1142 if (i != NULL)
1143 nbi = i->ob_type->tp_as_number;
1144 if (nbr == NULL || nbr->nb_float == NULL ||
1145 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
1146 PyErr_SetString(PyExc_TypeError,
1147 "complex() argument must be a string or a number");
1148 if (own_r) {
1149 Py_DECREF(r);
1151 return NULL;
1154 /* If we get this far, then the "real" and "imag" parts should
1155 both be treated as numbers, and the constructor should return a
1156 complex number equal to (real + imag*1j).
1158 Note that we do NOT assume the input to already be in canonical
1159 form; the "real" and "imag" parts might themselves be complex
1160 numbers, which slightly complicates the code below. */
1161 if (PyComplex_Check(r)) {
1162 /* Note that if r is of a complex subtype, we're only
1163 retaining its real & imag parts here, and the return
1164 value is (properly) of the builtin complex type. */
1165 cr = ((PyComplexObject*)r)->cval;
1166 cr_is_complex = 1;
1167 if (own_r) {
1168 Py_DECREF(r);
1171 else {
1172 /* The "real" part really is entirely real, and contributes
1173 nothing in the imaginary direction.
1174 Just treat it as a double. */
1175 tmp = PyNumber_Float(r);
1176 if (own_r) {
1177 /* r was a newly created complex number, rather
1178 than the original "real" argument. */
1179 Py_DECREF(r);
1181 if (tmp == NULL)
1182 return NULL;
1183 if (!PyFloat_Check(tmp)) {
1184 PyErr_SetString(PyExc_TypeError,
1185 "float(r) didn't return a float");
1186 Py_DECREF(tmp);
1187 return NULL;
1189 cr.real = PyFloat_AsDouble(tmp);
1190 cr.imag = 0.0; /* Shut up compiler warning */
1191 Py_DECREF(tmp);
1193 if (i == NULL) {
1194 ci.real = 0.0;
1196 else if (PyComplex_Check(i)) {
1197 ci = ((PyComplexObject*)i)->cval;
1198 ci_is_complex = 1;
1199 } else {
1200 /* The "imag" part really is entirely imaginary, and
1201 contributes nothing in the real direction.
1202 Just treat it as a double. */
1203 tmp = (*nbi->nb_float)(i);
1204 if (tmp == NULL)
1205 return NULL;
1206 ci.real = PyFloat_AsDouble(tmp);
1207 Py_DECREF(tmp);
1209 /* If the input was in canonical form, then the "real" and "imag"
1210 parts are real numbers, so that ci.imag and cr.imag are zero.
1211 We need this correction in case they were not real numbers. */
1213 if (ci_is_complex) {
1214 cr.real -= ci.imag;
1216 if (cr_is_complex) {
1217 ci.real += cr.imag;
1219 return complex_subtype_from_doubles(type, cr.real, ci.real);
1222 PyDoc_STRVAR(complex_doc,
1223 "complex(real[, imag]) -> complex number\n"
1224 "\n"
1225 "Create a complex number from a real part and an optional imaginary part.\n"
1226 "This is equivalent to (real + imag*1j) where imag defaults to 0.");
1228 static PyNumberMethods complex_as_number = {
1229 (binaryfunc)complex_add, /* nb_add */
1230 (binaryfunc)complex_sub, /* nb_subtract */
1231 (binaryfunc)complex_mul, /* nb_multiply */
1232 (binaryfunc)complex_classic_div, /* nb_divide */
1233 (binaryfunc)complex_remainder, /* nb_remainder */
1234 (binaryfunc)complex_divmod, /* nb_divmod */
1235 (ternaryfunc)complex_pow, /* nb_power */
1236 (unaryfunc)complex_neg, /* nb_negative */
1237 (unaryfunc)complex_pos, /* nb_positive */
1238 (unaryfunc)complex_abs, /* nb_absolute */
1239 (inquiry)complex_nonzero, /* nb_nonzero */
1240 0, /* nb_invert */
1241 0, /* nb_lshift */
1242 0, /* nb_rshift */
1243 0, /* nb_and */
1244 0, /* nb_xor */
1245 0, /* nb_or */
1246 complex_coerce, /* nb_coerce */
1247 complex_int, /* nb_int */
1248 complex_long, /* nb_long */
1249 complex_float, /* nb_float */
1250 0, /* nb_oct */
1251 0, /* nb_hex */
1252 0, /* nb_inplace_add */
1253 0, /* nb_inplace_subtract */
1254 0, /* nb_inplace_multiply*/
1255 0, /* nb_inplace_divide */
1256 0, /* nb_inplace_remainder */
1257 0, /* nb_inplace_power */
1258 0, /* nb_inplace_lshift */
1259 0, /* nb_inplace_rshift */
1260 0, /* nb_inplace_and */
1261 0, /* nb_inplace_xor */
1262 0, /* nb_inplace_or */
1263 (binaryfunc)complex_int_div, /* nb_floor_divide */
1264 (binaryfunc)complex_div, /* nb_true_divide */
1265 0, /* nb_inplace_floor_divide */
1266 0, /* nb_inplace_true_divide */
1269 PyTypeObject PyComplex_Type = {
1270 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1271 "complex",
1272 sizeof(PyComplexObject),
1274 complex_dealloc, /* tp_dealloc */
1275 (printfunc)complex_print, /* tp_print */
1276 0, /* tp_getattr */
1277 0, /* tp_setattr */
1278 0, /* tp_compare */
1279 (reprfunc)complex_repr, /* tp_repr */
1280 &complex_as_number, /* tp_as_number */
1281 0, /* tp_as_sequence */
1282 0, /* tp_as_mapping */
1283 (hashfunc)complex_hash, /* tp_hash */
1284 0, /* tp_call */
1285 (reprfunc)complex_str, /* tp_str */
1286 PyObject_GenericGetAttr, /* tp_getattro */
1287 0, /* tp_setattro */
1288 0, /* tp_as_buffer */
1289 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1290 complex_doc, /* tp_doc */
1291 0, /* tp_traverse */
1292 0, /* tp_clear */
1293 complex_richcompare, /* tp_richcompare */
1294 0, /* tp_weaklistoffset */
1295 0, /* tp_iter */
1296 0, /* tp_iternext */
1297 complex_methods, /* tp_methods */
1298 complex_members, /* tp_members */
1299 0, /* tp_getset */
1300 0, /* tp_base */
1301 0, /* tp_dict */
1302 0, /* tp_descr_get */
1303 0, /* tp_descr_set */
1304 0, /* tp_dictoffset */
1305 0, /* tp_init */
1306 PyType_GenericAlloc, /* tp_alloc */
1307 complex_new, /* tp_new */
1308 PyObject_Del, /* tp_free */
1311 #endif