Issue #7553: test_long_future wasn't testing properly. Thanks Florent Xicluna
[python.git] / Objects / complexobject.c
blob298e262f86e1955a475b33ca9da91e7e28b160b3
2 /* Complex object implementation */
4 /* Borrows heavily from floatobject.c */
6 /* Submitted by Jim Hugunin */
8 #include "Python.h"
9 #include "structmember.h"
11 #ifndef WITHOUT_COMPLEX
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 double
187 c_abs(Py_complex z)
189 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
190 double result;
192 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
193 /* C99 rules: if either the real or the imaginary part is an
194 infinity, return infinity, even if the other part is a
195 NaN. */
196 if (Py_IS_INFINITY(z.real)) {
197 result = fabs(z.real);
198 errno = 0;
199 return result;
201 if (Py_IS_INFINITY(z.imag)) {
202 result = fabs(z.imag);
203 errno = 0;
204 return result;
206 /* either the real or imaginary part is a NaN,
207 and neither is infinite. Result should be NaN. */
208 return Py_NAN;
210 result = hypot(z.real, z.imag);
211 if (!Py_IS_FINITE(result))
212 errno = ERANGE;
213 else
214 errno = 0;
215 return result;
218 static PyObject *
219 complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
221 PyObject *op;
223 op = type->tp_alloc(type, 0);
224 if (op != NULL)
225 ((PyComplexObject *)op)->cval = cval;
226 return op;
229 PyObject *
230 PyComplex_FromCComplex(Py_complex cval)
232 register PyComplexObject *op;
234 /* Inline PyObject_New */
235 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
236 if (op == NULL)
237 return PyErr_NoMemory();
238 PyObject_INIT(op, &PyComplex_Type);
239 op->cval = cval;
240 return (PyObject *) op;
243 static PyObject *
244 complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
246 Py_complex c;
247 c.real = real;
248 c.imag = imag;
249 return complex_subtype_from_c_complex(type, c);
252 PyObject *
253 PyComplex_FromDoubles(double real, double imag)
255 Py_complex c;
256 c.real = real;
257 c.imag = imag;
258 return PyComplex_FromCComplex(c);
261 double
262 PyComplex_RealAsDouble(PyObject *op)
264 if (PyComplex_Check(op)) {
265 return ((PyComplexObject *)op)->cval.real;
267 else {
268 return PyFloat_AsDouble(op);
272 double
273 PyComplex_ImagAsDouble(PyObject *op)
275 if (PyComplex_Check(op)) {
276 return ((PyComplexObject *)op)->cval.imag;
278 else {
279 return 0.0;
283 Py_complex
284 PyComplex_AsCComplex(PyObject *op)
286 Py_complex cv;
287 PyObject *newop = NULL;
288 static PyObject *complex_str = NULL;
290 assert(op);
291 /* If op is already of type PyComplex_Type, return its value */
292 if (PyComplex_Check(op)) {
293 return ((PyComplexObject *)op)->cval;
295 /* If not, use op's __complex__ method, if it exists */
297 /* return -1 on failure */
298 cv.real = -1.;
299 cv.imag = 0.;
301 if (complex_str == NULL) {
302 if (!(complex_str = PyString_InternFromString("__complex__")))
303 return cv;
306 if (PyInstance_Check(op)) {
307 /* this can go away in python 3000 */
308 if (PyObject_HasAttr(op, complex_str)) {
309 newop = PyObject_CallMethod(op, "__complex__", NULL);
310 if (!newop)
311 return cv;
313 /* else try __float__ */
314 } else {
315 PyObject *complexfunc;
316 complexfunc = _PyType_Lookup(op->ob_type, complex_str);
317 /* complexfunc is a borrowed reference */
318 if (complexfunc) {
319 newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL);
320 if (!newop)
321 return cv;
325 if (newop) {
326 if (!PyComplex_Check(newop)) {
327 PyErr_SetString(PyExc_TypeError,
328 "__complex__ should return a complex object");
329 Py_DECREF(newop);
330 return cv;
332 cv = ((PyComplexObject *)newop)->cval;
333 Py_DECREF(newop);
334 return cv;
336 /* If neither of the above works, interpret op as a float giving the
337 real part of the result, and fill in the imaginary part as 0. */
338 else {
339 /* PyFloat_AsDouble will return -1 on failure */
340 cv.real = PyFloat_AsDouble(op);
341 return cv;
345 static void
346 complex_dealloc(PyObject *op)
348 op->ob_type->tp_free(op);
352 static PyObject *
353 complex_format(PyComplexObject *v, int precision, char format_code)
355 PyObject *result = NULL;
356 Py_ssize_t len;
358 /* If these are non-NULL, they'll need to be freed. */
359 char *pre = NULL;
360 char *im = NULL;
361 char *buf = NULL;
363 /* These do not need to be freed. re is either an alias
364 for pre or a pointer to a constant. lead and tail
365 are pointers to constants. */
366 char *re = NULL;
367 char *lead = "";
368 char *tail = "";
370 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
371 re = "";
372 im = PyOS_double_to_string(v->cval.imag, format_code,
373 precision, 0, NULL);
374 if (!im) {
375 PyErr_NoMemory();
376 goto done;
378 } else {
379 /* Format imaginary part with sign, real part without */
380 pre = PyOS_double_to_string(v->cval.real, format_code,
381 precision, 0, NULL);
382 if (!pre) {
383 PyErr_NoMemory();
384 goto done;
386 re = pre;
388 im = PyOS_double_to_string(v->cval.imag, format_code,
389 precision, Py_DTSF_SIGN, NULL);
390 if (!im) {
391 PyErr_NoMemory();
392 goto done;
394 lead = "(";
395 tail = ")";
397 /* Alloc the final buffer. Add one for the "j" in the format string,
398 and one for the trailing zero. */
399 len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
400 buf = PyMem_Malloc(len);
401 if (!buf) {
402 PyErr_NoMemory();
403 goto done;
405 PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
406 result = PyString_FromString(buf);
407 done:
408 PyMem_Free(im);
409 PyMem_Free(pre);
410 PyMem_Free(buf);
412 return result;
415 static int
416 complex_print(PyComplexObject *v, FILE *fp, int flags)
418 PyObject *formatv;
419 char *buf;
420 if (flags & Py_PRINT_RAW)
421 formatv = complex_format(v, PyFloat_STR_PRECISION, 'g');
422 else
423 formatv = complex_format(v, 0, 'r');
424 if (formatv == NULL)
425 return -1;
426 buf = PyString_AS_STRING(formatv);
427 Py_BEGIN_ALLOW_THREADS
428 fputs(buf, fp);
429 Py_END_ALLOW_THREADS
430 Py_DECREF(formatv);
431 return 0;
434 static PyObject *
435 complex_repr(PyComplexObject *v)
437 return complex_format(v, 0, 'r');
440 static PyObject *
441 complex_str(PyComplexObject *v)
443 return complex_format(v, PyFloat_STR_PRECISION, 'g');
446 static long
447 complex_hash(PyComplexObject *v)
449 long hashreal, hashimag, combined;
450 hashreal = _Py_HashDouble(v->cval.real);
451 if (hashreal == -1)
452 return -1;
453 hashimag = _Py_HashDouble(v->cval.imag);
454 if (hashimag == -1)
455 return -1;
456 /* Note: if the imaginary part is 0, hashimag is 0 now,
457 * so the following returns hashreal unchanged. This is
458 * important because numbers of different types that
459 * compare equal must have the same hash value, so that
460 * hash(x + 0*j) must equal hash(x).
462 combined = hashreal + 1000003 * hashimag;
463 if (combined == -1)
464 combined = -2;
465 return combined;
468 /* This macro may return! */
469 #define TO_COMPLEX(obj, c) \
470 if (PyComplex_Check(obj)) \
471 c = ((PyComplexObject *)(obj))->cval; \
472 else if (to_complex(&(obj), &(c)) < 0) \
473 return (obj)
475 static int
476 to_complex(PyObject **pobj, Py_complex *pc)
478 PyObject *obj = *pobj;
480 pc->real = pc->imag = 0.0;
481 if (PyInt_Check(obj)) {
482 pc->real = PyInt_AS_LONG(obj);
483 return 0;
485 if (PyLong_Check(obj)) {
486 pc->real = PyLong_AsDouble(obj);
487 if (pc->real == -1.0 && PyErr_Occurred()) {
488 *pobj = NULL;
489 return -1;
491 return 0;
493 if (PyFloat_Check(obj)) {
494 pc->real = PyFloat_AsDouble(obj);
495 return 0;
497 Py_INCREF(Py_NotImplemented);
498 *pobj = Py_NotImplemented;
499 return -1;
503 static PyObject *
504 complex_add(PyComplexObject *v, PyComplexObject *w)
506 Py_complex result;
507 PyFPE_START_PROTECT("complex_add", return 0)
508 result = c_sum(v->cval,w->cval);
509 PyFPE_END_PROTECT(result)
510 return PyComplex_FromCComplex(result);
513 static PyObject *
514 complex_sub(PyComplexObject *v, PyComplexObject *w)
516 Py_complex result;
517 PyFPE_START_PROTECT("complex_sub", return 0)
518 result = c_diff(v->cval,w->cval);
519 PyFPE_END_PROTECT(result)
520 return PyComplex_FromCComplex(result);
523 static PyObject *
524 complex_mul(PyComplexObject *v, PyComplexObject *w)
526 Py_complex result;
527 PyFPE_START_PROTECT("complex_mul", return 0)
528 result = c_prod(v->cval,w->cval);
529 PyFPE_END_PROTECT(result)
530 return PyComplex_FromCComplex(result);
533 static PyObject *
534 complex_div(PyComplexObject *v, PyComplexObject *w)
536 Py_complex quot;
538 PyFPE_START_PROTECT("complex_div", return 0)
539 errno = 0;
540 quot = c_quot(v->cval,w->cval);
541 PyFPE_END_PROTECT(quot)
542 if (errno == EDOM) {
543 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
544 return NULL;
546 return PyComplex_FromCComplex(quot);
549 static PyObject *
550 complex_classic_div(PyComplexObject *v, PyComplexObject *w)
552 Py_complex quot;
554 if (Py_DivisionWarningFlag >= 2 &&
555 PyErr_Warn(PyExc_DeprecationWarning,
556 "classic complex division") < 0)
557 return NULL;
559 PyFPE_START_PROTECT("complex_classic_div", return 0)
560 errno = 0;
561 quot = c_quot(v->cval,w->cval);
562 PyFPE_END_PROTECT(quot)
563 if (errno == EDOM) {
564 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
565 return NULL;
567 return PyComplex_FromCComplex(quot);
570 static PyObject *
571 complex_remainder(PyComplexObject *v, PyComplexObject *w)
573 Py_complex div, mod;
575 if (PyErr_Warn(PyExc_DeprecationWarning,
576 "complex divmod(), // and % are deprecated") < 0)
577 return NULL;
579 errno = 0;
580 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
581 if (errno == EDOM) {
582 PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
583 return NULL;
585 div.real = floor(div.real); /* Use the floor of the real part. */
586 div.imag = 0.0;
587 mod = c_diff(v->cval, c_prod(w->cval, div));
589 return PyComplex_FromCComplex(mod);
593 static PyObject *
594 complex_divmod(PyComplexObject *v, PyComplexObject *w)
596 Py_complex div, mod;
597 PyObject *d, *m, *z;
599 if (PyErr_Warn(PyExc_DeprecationWarning,
600 "complex divmod(), // and % are deprecated") < 0)
601 return NULL;
603 errno = 0;
604 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
605 if (errno == EDOM) {
606 PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
607 return NULL;
609 div.real = floor(div.real); /* Use the floor of the real part. */
610 div.imag = 0.0;
611 mod = c_diff(v->cval, c_prod(w->cval, div));
612 d = PyComplex_FromCComplex(div);
613 m = PyComplex_FromCComplex(mod);
614 z = PyTuple_Pack(2, d, m);
615 Py_XDECREF(d);
616 Py_XDECREF(m);
617 return z;
620 static PyObject *
621 complex_pow(PyObject *v, PyObject *w, PyObject *z)
623 Py_complex p;
624 Py_complex exponent;
625 long int_exponent;
626 Py_complex a, b;
627 TO_COMPLEX(v, a);
628 TO_COMPLEX(w, b);
630 if (z!=Py_None) {
631 PyErr_SetString(PyExc_ValueError, "complex modulo");
632 return NULL;
634 PyFPE_START_PROTECT("complex_pow", return 0)
635 errno = 0;
636 exponent = b;
637 int_exponent = (long)exponent.real;
638 if (exponent.imag == 0. && exponent.real == int_exponent)
639 p = c_powi(a,int_exponent);
640 else
641 p = c_pow(a,exponent);
643 PyFPE_END_PROTECT(p)
644 Py_ADJUST_ERANGE2(p.real, p.imag);
645 if (errno == EDOM) {
646 PyErr_SetString(PyExc_ZeroDivisionError,
647 "0.0 to a negative or complex power");
648 return NULL;
650 else if (errno == ERANGE) {
651 PyErr_SetString(PyExc_OverflowError,
652 "complex exponentiation");
653 return NULL;
655 return PyComplex_FromCComplex(p);
658 static PyObject *
659 complex_int_div(PyComplexObject *v, PyComplexObject *w)
661 PyObject *t, *r;
663 if (PyErr_Warn(PyExc_DeprecationWarning,
664 "complex divmod(), // and % are deprecated") < 0)
665 return NULL;
667 t = complex_divmod(v, w);
668 if (t != NULL) {
669 r = PyTuple_GET_ITEM(t, 0);
670 Py_INCREF(r);
671 Py_DECREF(t);
672 return r;
674 return NULL;
677 static PyObject *
678 complex_neg(PyComplexObject *v)
680 Py_complex neg;
681 neg.real = -v->cval.real;
682 neg.imag = -v->cval.imag;
683 return PyComplex_FromCComplex(neg);
686 static PyObject *
687 complex_pos(PyComplexObject *v)
689 if (PyComplex_CheckExact(v)) {
690 Py_INCREF(v);
691 return (PyObject *)v;
693 else
694 return PyComplex_FromCComplex(v->cval);
697 static PyObject *
698 complex_abs(PyComplexObject *v)
700 double result;
702 PyFPE_START_PROTECT("complex_abs", return 0)
703 result = c_abs(v->cval);
704 PyFPE_END_PROTECT(result)
706 if (errno == ERANGE) {
707 PyErr_SetString(PyExc_OverflowError,
708 "absolute value too large");
709 return NULL;
711 return PyFloat_FromDouble(result);
714 static int
715 complex_nonzero(PyComplexObject *v)
717 return v->cval.real != 0.0 || v->cval.imag != 0.0;
720 static int
721 complex_coerce(PyObject **pv, PyObject **pw)
723 Py_complex cval;
724 cval.imag = 0.;
725 if (PyInt_Check(*pw)) {
726 cval.real = (double)PyInt_AsLong(*pw);
727 *pw = PyComplex_FromCComplex(cval);
728 Py_INCREF(*pv);
729 return 0;
731 else if (PyLong_Check(*pw)) {
732 cval.real = PyLong_AsDouble(*pw);
733 if (cval.real == -1.0 && PyErr_Occurred())
734 return -1;
735 *pw = PyComplex_FromCComplex(cval);
736 Py_INCREF(*pv);
737 return 0;
739 else if (PyFloat_Check(*pw)) {
740 cval.real = PyFloat_AsDouble(*pw);
741 *pw = PyComplex_FromCComplex(cval);
742 Py_INCREF(*pv);
743 return 0;
745 else if (PyComplex_Check(*pw)) {
746 Py_INCREF(*pv);
747 Py_INCREF(*pw);
748 return 0;
750 return 1; /* Can't do it */
753 static PyObject *
754 complex_richcompare(PyObject *v, PyObject *w, int op)
756 int c;
757 Py_complex i, j;
758 PyObject *res;
760 c = PyNumber_CoerceEx(&v, &w);
761 if (c < 0)
762 return NULL;
763 if (c > 0) {
764 Py_INCREF(Py_NotImplemented);
765 return Py_NotImplemented;
767 /* Make sure both arguments are complex. */
768 if (!(PyComplex_Check(v) && PyComplex_Check(w))) {
769 Py_DECREF(v);
770 Py_DECREF(w);
771 Py_INCREF(Py_NotImplemented);
772 return Py_NotImplemented;
775 i = ((PyComplexObject *)v)->cval;
776 j = ((PyComplexObject *)w)->cval;
777 Py_DECREF(v);
778 Py_DECREF(w);
780 if (op != Py_EQ && op != Py_NE) {
781 PyErr_SetString(PyExc_TypeError,
782 "no ordering relation is defined for complex numbers");
783 return NULL;
786 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
787 res = Py_True;
788 else
789 res = Py_False;
791 Py_INCREF(res);
792 return res;
795 static PyObject *
796 complex_int(PyObject *v)
798 PyErr_SetString(PyExc_TypeError,
799 "can't convert complex to int");
800 return NULL;
803 static PyObject *
804 complex_long(PyObject *v)
806 PyErr_SetString(PyExc_TypeError,
807 "can't convert complex to long");
808 return NULL;
811 static PyObject *
812 complex_float(PyObject *v)
814 PyErr_SetString(PyExc_TypeError,
815 "can't convert complex to float");
816 return NULL;
819 static PyObject *
820 complex_conjugate(PyObject *self)
822 Py_complex c;
823 c = ((PyComplexObject *)self)->cval;
824 c.imag = -c.imag;
825 return PyComplex_FromCComplex(c);
828 PyDoc_STRVAR(complex_conjugate_doc,
829 "complex.conjugate() -> complex\n"
830 "\n"
831 "Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
833 static PyObject *
834 complex_getnewargs(PyComplexObject *v)
836 Py_complex c = v->cval;
837 return Py_BuildValue("(dd)", c.real, c.imag);
840 PyDoc_STRVAR(complex__format__doc,
841 "complex.__format__() -> str\n"
842 "\n"
843 "Converts to a string according to format_spec.");
845 static PyObject *
846 complex__format__(PyObject* self, PyObject* args)
848 PyObject *format_spec;
850 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
851 return NULL;
852 if (PyBytes_Check(format_spec))
853 return _PyComplex_FormatAdvanced(self,
854 PyBytes_AS_STRING(format_spec),
855 PyBytes_GET_SIZE(format_spec));
856 if (PyUnicode_Check(format_spec)) {
857 /* Convert format_spec to a str */
858 PyObject *result;
859 PyObject *str_spec = PyObject_Str(format_spec);
861 if (str_spec == NULL)
862 return NULL;
864 result = _PyComplex_FormatAdvanced(self,
865 PyBytes_AS_STRING(str_spec),
866 PyBytes_GET_SIZE(str_spec));
868 Py_DECREF(str_spec);
869 return result;
871 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
872 return NULL;
875 #if 0
876 static PyObject *
877 complex_is_finite(PyObject *self)
879 Py_complex c;
880 c = ((PyComplexObject *)self)->cval;
881 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
882 Py_IS_FINITE(c.imag)));
885 PyDoc_STRVAR(complex_is_finite_doc,
886 "complex.is_finite() -> bool\n"
887 "\n"
888 "Returns True if the real and the imaginary part is finite.");
889 #endif
891 static PyMethodDef complex_methods[] = {
892 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
893 complex_conjugate_doc},
894 #if 0
895 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
896 complex_is_finite_doc},
897 #endif
898 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
899 {"__format__", (PyCFunction)complex__format__,
900 METH_VARARGS, complex__format__doc},
901 {NULL, NULL} /* sentinel */
904 static PyMemberDef complex_members[] = {
905 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
906 "the real part of a complex number"},
907 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
908 "the imaginary part of a complex number"},
909 {0},
912 static PyObject *
913 complex_subtype_from_string(PyTypeObject *type, PyObject *v)
915 const char *s, *start;
916 char *end;
917 double x=0.0, y=0.0, z;
918 int got_bracket=0;
919 #ifdef Py_USING_UNICODE
920 char *s_buffer = NULL;
921 #endif
922 Py_ssize_t len;
924 if (PyString_Check(v)) {
925 s = PyString_AS_STRING(v);
926 len = PyString_GET_SIZE(v);
928 #ifdef Py_USING_UNICODE
929 else if (PyUnicode_Check(v)) {
930 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
931 if (s_buffer == NULL)
932 return PyErr_NoMemory();
933 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
934 PyUnicode_GET_SIZE(v),
935 s_buffer,
936 NULL))
937 goto error;
938 s = s_buffer;
939 len = strlen(s);
941 #endif
942 else if (PyObject_AsCharBuffer(v, &s, &len)) {
943 PyErr_SetString(PyExc_TypeError,
944 "complex() arg is not a string");
945 return NULL;
948 /* position on first nonblank */
949 start = s;
950 while (Py_ISSPACE(*s))
951 s++;
952 if (*s == '(') {
953 /* Skip over possible bracket from repr(). */
954 got_bracket = 1;
955 s++;
956 while (Py_ISSPACE(*s))
957 s++;
960 /* a valid complex string usually takes one of the three forms:
962 <float> - real part only
963 <float>j - imaginary part only
964 <float><signed-float>j - real and imaginary parts
966 where <float> represents any numeric string that's accepted by the
967 float constructor (including 'nan', 'inf', 'infinity', etc.), and
968 <signed-float> is any string of the form <float> whose first
969 character is '+' or '-'.
971 For backwards compatibility, the extra forms
973 <float><sign>j
974 <sign>j
977 are also accepted, though support for these forms may be removed from
978 a future version of Python.
981 /* first look for forms starting with <float> */
982 z = PyOS_string_to_double(s, &end, NULL);
983 if (z == -1.0 && PyErr_Occurred()) {
984 if (PyErr_ExceptionMatches(PyExc_ValueError))
985 PyErr_Clear();
986 else
987 goto error;
989 if (end != s) {
990 /* all 4 forms starting with <float> land here */
991 s = end;
992 if (*s == '+' || *s == '-') {
993 /* <float><signed-float>j | <float><sign>j */
994 x = z;
995 y = PyOS_string_to_double(s, &end, NULL);
996 if (y == -1.0 && PyErr_Occurred()) {
997 if (PyErr_ExceptionMatches(PyExc_ValueError))
998 PyErr_Clear();
999 else
1000 goto error;
1002 if (end != s)
1003 /* <float><signed-float>j */
1004 s = end;
1005 else {
1006 /* <float><sign>j */
1007 y = *s == '+' ? 1.0 : -1.0;
1008 s++;
1010 if (!(*s == 'j' || *s == 'J'))
1011 goto parse_error;
1012 s++;
1014 else if (*s == 'j' || *s == 'J') {
1015 /* <float>j */
1016 s++;
1017 y = z;
1019 else
1020 /* <float> */
1021 x = z;
1023 else {
1024 /* not starting with <float>; must be <sign>j or j */
1025 if (*s == '+' || *s == '-') {
1026 /* <sign>j */
1027 y = *s == '+' ? 1.0 : -1.0;
1028 s++;
1030 else
1031 /* j */
1032 y = 1.0;
1033 if (!(*s == 'j' || *s == 'J'))
1034 goto parse_error;
1035 s++;
1038 /* trailing whitespace and closing bracket */
1039 while (Py_ISSPACE(*s))
1040 s++;
1041 if (got_bracket) {
1042 /* if there was an opening parenthesis, then the corresponding
1043 closing parenthesis should be right here */
1044 if (*s != ')')
1045 goto parse_error;
1046 s++;
1047 while (Py_ISSPACE(*s))
1048 s++;
1051 /* we should now be at the end of the string */
1052 if (s-start != len)
1053 goto parse_error;
1056 #ifdef Py_USING_UNICODE
1057 if (s_buffer)
1058 PyMem_FREE(s_buffer);
1059 #endif
1060 return complex_subtype_from_doubles(type, x, y);
1062 parse_error:
1063 PyErr_SetString(PyExc_ValueError,
1064 "complex() arg is a malformed string");
1065 error:
1066 #ifdef Py_USING_UNICODE
1067 if (s_buffer)
1068 PyMem_FREE(s_buffer);
1069 #endif
1070 return NULL;
1073 static PyObject *
1074 complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1076 PyObject *r, *i, *tmp, *f;
1077 PyNumberMethods *nbr, *nbi = NULL;
1078 Py_complex cr, ci;
1079 int own_r = 0;
1080 int cr_is_complex = 0;
1081 int ci_is_complex = 0;
1082 static PyObject *complexstr;
1083 static char *kwlist[] = {"real", "imag", 0};
1085 r = Py_False;
1086 i = NULL;
1087 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
1088 &r, &i))
1089 return NULL;
1091 /* Special-case for a single argument when type(arg) is complex. */
1092 if (PyComplex_CheckExact(r) && i == NULL &&
1093 type == &PyComplex_Type) {
1094 /* Note that we can't know whether it's safe to return
1095 a complex *subclass* instance as-is, hence the restriction
1096 to exact complexes here. If either the input or the
1097 output is a complex subclass, it will be handled below
1098 as a non-orthogonal vector. */
1099 Py_INCREF(r);
1100 return r;
1102 if (PyString_Check(r) || PyUnicode_Check(r)) {
1103 if (i != NULL) {
1104 PyErr_SetString(PyExc_TypeError,
1105 "complex() can't take second arg"
1106 " if first is a string");
1107 return NULL;
1109 return complex_subtype_from_string(type, r);
1111 if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
1112 PyErr_SetString(PyExc_TypeError,
1113 "complex() second arg can't be a string");
1114 return NULL;
1117 /* XXX Hack to support classes with __complex__ method */
1118 if (complexstr == NULL) {
1119 complexstr = PyString_InternFromString("__complex__");
1120 if (complexstr == NULL)
1121 return NULL;
1123 f = PyObject_GetAttr(r, complexstr);
1124 if (f == NULL)
1125 PyErr_Clear();
1126 else {
1127 PyObject *args = PyTuple_New(0);
1128 if (args == NULL)
1129 return NULL;
1130 r = PyEval_CallObject(f, args);
1131 Py_DECREF(args);
1132 Py_DECREF(f);
1133 if (r == NULL)
1134 return NULL;
1135 own_r = 1;
1137 nbr = r->ob_type->tp_as_number;
1138 if (i != NULL)
1139 nbi = i->ob_type->tp_as_number;
1140 if (nbr == NULL || nbr->nb_float == NULL ||
1141 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
1142 PyErr_SetString(PyExc_TypeError,
1143 "complex() argument must be a string or a number");
1144 if (own_r) {
1145 Py_DECREF(r);
1147 return NULL;
1150 /* If we get this far, then the "real" and "imag" parts should
1151 both be treated as numbers, and the constructor should return a
1152 complex number equal to (real + imag*1j).
1154 Note that we do NOT assume the input to already be in canonical
1155 form; the "real" and "imag" parts might themselves be complex
1156 numbers, which slightly complicates the code below. */
1157 if (PyComplex_Check(r)) {
1158 /* Note that if r is of a complex subtype, we're only
1159 retaining its real & imag parts here, and the return
1160 value is (properly) of the builtin complex type. */
1161 cr = ((PyComplexObject*)r)->cval;
1162 cr_is_complex = 1;
1163 if (own_r) {
1164 Py_DECREF(r);
1167 else {
1168 /* The "real" part really is entirely real, and contributes
1169 nothing in the imaginary direction.
1170 Just treat it as a double. */
1171 tmp = PyNumber_Float(r);
1172 if (own_r) {
1173 /* r was a newly created complex number, rather
1174 than the original "real" argument. */
1175 Py_DECREF(r);
1177 if (tmp == NULL)
1178 return NULL;
1179 if (!PyFloat_Check(tmp)) {
1180 PyErr_SetString(PyExc_TypeError,
1181 "float(r) didn't return a float");
1182 Py_DECREF(tmp);
1183 return NULL;
1185 cr.real = PyFloat_AsDouble(tmp);
1186 cr.imag = 0.0; /* Shut up compiler warning */
1187 Py_DECREF(tmp);
1189 if (i == NULL) {
1190 ci.real = 0.0;
1192 else if (PyComplex_Check(i)) {
1193 ci = ((PyComplexObject*)i)->cval;
1194 ci_is_complex = 1;
1195 } else {
1196 /* The "imag" part really is entirely imaginary, and
1197 contributes nothing in the real direction.
1198 Just treat it as a double. */
1199 tmp = (*nbi->nb_float)(i);
1200 if (tmp == NULL)
1201 return NULL;
1202 ci.real = PyFloat_AsDouble(tmp);
1203 Py_DECREF(tmp);
1205 /* If the input was in canonical form, then the "real" and "imag"
1206 parts are real numbers, so that ci.imag and cr.imag are zero.
1207 We need this correction in case they were not real numbers. */
1209 if (ci_is_complex) {
1210 cr.real -= ci.imag;
1212 if (cr_is_complex) {
1213 ci.real += cr.imag;
1215 return complex_subtype_from_doubles(type, cr.real, ci.real);
1218 PyDoc_STRVAR(complex_doc,
1219 "complex(real[, imag]) -> complex number\n"
1220 "\n"
1221 "Create a complex number from a real part and an optional imaginary part.\n"
1222 "This is equivalent to (real + imag*1j) where imag defaults to 0.");
1224 static PyNumberMethods complex_as_number = {
1225 (binaryfunc)complex_add, /* nb_add */
1226 (binaryfunc)complex_sub, /* nb_subtract */
1227 (binaryfunc)complex_mul, /* nb_multiply */
1228 (binaryfunc)complex_classic_div, /* nb_divide */
1229 (binaryfunc)complex_remainder, /* nb_remainder */
1230 (binaryfunc)complex_divmod, /* nb_divmod */
1231 (ternaryfunc)complex_pow, /* nb_power */
1232 (unaryfunc)complex_neg, /* nb_negative */
1233 (unaryfunc)complex_pos, /* nb_positive */
1234 (unaryfunc)complex_abs, /* nb_absolute */
1235 (inquiry)complex_nonzero, /* nb_nonzero */
1236 0, /* nb_invert */
1237 0, /* nb_lshift */
1238 0, /* nb_rshift */
1239 0, /* nb_and */
1240 0, /* nb_xor */
1241 0, /* nb_or */
1242 complex_coerce, /* nb_coerce */
1243 complex_int, /* nb_int */
1244 complex_long, /* nb_long */
1245 complex_float, /* nb_float */
1246 0, /* nb_oct */
1247 0, /* nb_hex */
1248 0, /* nb_inplace_add */
1249 0, /* nb_inplace_subtract */
1250 0, /* nb_inplace_multiply*/
1251 0, /* nb_inplace_divide */
1252 0, /* nb_inplace_remainder */
1253 0, /* nb_inplace_power */
1254 0, /* nb_inplace_lshift */
1255 0, /* nb_inplace_rshift */
1256 0, /* nb_inplace_and */
1257 0, /* nb_inplace_xor */
1258 0, /* nb_inplace_or */
1259 (binaryfunc)complex_int_div, /* nb_floor_divide */
1260 (binaryfunc)complex_div, /* nb_true_divide */
1261 0, /* nb_inplace_floor_divide */
1262 0, /* nb_inplace_true_divide */
1265 PyTypeObject PyComplex_Type = {
1266 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1267 "complex",
1268 sizeof(PyComplexObject),
1270 complex_dealloc, /* tp_dealloc */
1271 (printfunc)complex_print, /* tp_print */
1272 0, /* tp_getattr */
1273 0, /* tp_setattr */
1274 0, /* tp_compare */
1275 (reprfunc)complex_repr, /* tp_repr */
1276 &complex_as_number, /* tp_as_number */
1277 0, /* tp_as_sequence */
1278 0, /* tp_as_mapping */
1279 (hashfunc)complex_hash, /* tp_hash */
1280 0, /* tp_call */
1281 (reprfunc)complex_str, /* tp_str */
1282 PyObject_GenericGetAttr, /* tp_getattro */
1283 0, /* tp_setattro */
1284 0, /* tp_as_buffer */
1285 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1286 complex_doc, /* tp_doc */
1287 0, /* tp_traverse */
1288 0, /* tp_clear */
1289 complex_richcompare, /* tp_richcompare */
1290 0, /* tp_weaklistoffset */
1291 0, /* tp_iter */
1292 0, /* tp_iternext */
1293 complex_methods, /* tp_methods */
1294 complex_members, /* tp_members */
1295 0, /* tp_getset */
1296 0, /* tp_base */
1297 0, /* tp_dict */
1298 0, /* tp_descr_get */
1299 0, /* tp_descr_set */
1300 0, /* tp_dictoffset */
1301 0, /* tp_init */
1302 PyType_GenericAlloc, /* tp_alloc */
1303 complex_new, /* tp_new */
1304 PyObject_Del, /* tp_free */
1307 #endif