2 /* Complex object implementation */
4 /* Borrows heavily from floatobject.c */
6 /* Submitted by Jim Hugunin */
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
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.
29 /* elementary operations on complex numbers */
31 static Py_complex c_1
= {1., 0.};
34 c_sum(Py_complex a
, Py_complex b
)
37 r
.real
= a
.real
+ b
.real
;
38 r
.imag
= a
.imag
+ b
.imag
;
43 c_diff(Py_complex a
, Py_complex b
)
46 r
.real
= a
.real
- b
.real
;
47 r
.imag
= a
.imag
- b
.imag
;
61 c_prod(Py_complex a
, Py_complex b
)
64 r
.real
= a
.real
*b
.real
- a
.imag
*b
.imag
;
65 r
.imag
= a
.real
*b
.imag
+ a
.imag
*b
.real
;
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
80 double d = b.real*b.real + b.imag*b.imag;
83 r.real = (a.real*b.real + a.imag*b.imag)/d;
84 r.imag = (a.imag*b.real - a.real*b.imag)/d;
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
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) {
103 r
.real
= r
.imag
= 0.0;
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
;
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
;
124 c_pow(Py_complex a
, Py_complex b
)
127 double vabs
,len
,at
,phase
;
128 if (b
.real
== 0. && b
.imag
== 0.) {
132 else if (a
.real
== 0. && a
.imag
== 0.) {
133 if (b
.imag
!= 0. || b
.real
< 0.)
139 vabs
= hypot(a
.real
,a
.imag
);
140 len
= pow(vabs
,b
.real
);
141 at
= atan2(a
.imag
, a
.real
);
144 len
/= exp(at
*b
.imag
);
145 phase
+= b
.imag
*log(vabs
);
147 r
.real
= len
*cos(phase
);
148 r
.imag
= len
*sin(phase
);
154 c_powu(Py_complex x
, long n
)
160 while (mask
> 0 && n
>= mask
) {
170 c_powi(Py_complex x
, long n
)
174 if (n
> 100 || n
< -100) {
175 cn
.real
= (double) n
;
182 return c_quot(c_1
,c_powu(x
,-n
));
189 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
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
196 if (Py_IS_INFINITY(z
.real
)) {
197 result
= fabs(z
.real
);
201 if (Py_IS_INFINITY(z
.imag
)) {
202 result
= fabs(z
.imag
);
206 /* either the real or imaginary part is a NaN,
207 and neither is infinite. Result should be NaN. */
210 result
= hypot(z
.real
, z
.imag
);
211 if (!Py_IS_FINITE(result
))
219 complex_subtype_from_c_complex(PyTypeObject
*type
, Py_complex cval
)
223 op
= type
->tp_alloc(type
, 0);
225 ((PyComplexObject
*)op
)->cval
= cval
;
230 PyComplex_FromCComplex(Py_complex cval
)
232 register PyComplexObject
*op
;
234 /* Inline PyObject_New */
235 op
= (PyComplexObject
*) PyObject_MALLOC(sizeof(PyComplexObject
));
237 return PyErr_NoMemory();
238 PyObject_INIT(op
, &PyComplex_Type
);
240 return (PyObject
*) op
;
244 complex_subtype_from_doubles(PyTypeObject
*type
, double real
, double imag
)
249 return complex_subtype_from_c_complex(type
, c
);
253 PyComplex_FromDoubles(double real
, double imag
)
258 return PyComplex_FromCComplex(c
);
262 PyComplex_RealAsDouble(PyObject
*op
)
264 if (PyComplex_Check(op
)) {
265 return ((PyComplexObject
*)op
)->cval
.real
;
268 return PyFloat_AsDouble(op
);
273 PyComplex_ImagAsDouble(PyObject
*op
)
275 if (PyComplex_Check(op
)) {
276 return ((PyComplexObject
*)op
)->cval
.imag
;
284 try_complex_special_method(PyObject
*op
) {
286 static PyObject
*complexstr
;
288 if (complexstr
== NULL
) {
289 complexstr
= PyString_InternFromString("__complex__");
290 if (complexstr
== NULL
)
293 if (PyInstance_Check(op
)) {
294 f
= PyObject_GetAttr(op
, complexstr
);
296 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
303 f
= _PyObject_LookupSpecial(op
, "__complex__", &complexstr
);
304 if (f
== NULL
&& PyErr_Occurred())
308 PyObject
*res
= PyObject_CallFunctionObjArgs(f
, NULL
);
316 PyComplex_AsCComplex(PyObject
*op
)
319 PyObject
*newop
= NULL
;
322 /* If op is already of type PyComplex_Type, return its value */
323 if (PyComplex_Check(op
)) {
324 return ((PyComplexObject
*)op
)->cval
;
326 /* If not, use op's __complex__ method, if it exists */
328 /* return -1 on failure */
332 newop
= try_complex_special_method(op
);
335 if (!PyComplex_Check(newop
)) {
336 PyErr_SetString(PyExc_TypeError
,
337 "__complex__ should return a complex object");
341 cv
= ((PyComplexObject
*)newop
)->cval
;
345 else if (PyErr_Occurred()) {
348 /* If neither of the above works, interpret op as a float giving the
349 real part of the result, and fill in the imaginary part as 0. */
351 /* PyFloat_AsDouble will return -1 on failure */
352 cv
.real
= PyFloat_AsDouble(op
);
358 complex_dealloc(PyObject
*op
)
360 op
->ob_type
->tp_free(op
);
365 complex_format(PyComplexObject
*v
, int precision
, char format_code
)
367 PyObject
*result
= NULL
;
370 /* If these are non-NULL, they'll need to be freed. */
375 /* These do not need to be freed. re is either an alias
376 for pre or a pointer to a constant. lead and tail
377 are pointers to constants. */
382 if (v
->cval
.real
== 0. && copysign(1.0, v
->cval
.real
)==1.0) {
384 im
= PyOS_double_to_string(v
->cval
.imag
, format_code
,
391 /* Format imaginary part with sign, real part without */
392 pre
= PyOS_double_to_string(v
->cval
.real
, format_code
,
400 im
= PyOS_double_to_string(v
->cval
.imag
, format_code
,
401 precision
, Py_DTSF_SIGN
, NULL
);
409 /* Alloc the final buffer. Add one for the "j" in the format string,
410 and one for the trailing zero. */
411 len
= strlen(lead
) + strlen(re
) + strlen(im
) + strlen(tail
) + 2;
412 buf
= PyMem_Malloc(len
);
417 PyOS_snprintf(buf
, len
, "%s%s%sj%s", lead
, re
, im
, tail
);
418 result
= PyString_FromString(buf
);
428 complex_print(PyComplexObject
*v
, FILE *fp
, int flags
)
432 if (flags
& Py_PRINT_RAW
)
433 formatv
= complex_format(v
, PyFloat_STR_PRECISION
, 'g');
435 formatv
= complex_format(v
, 0, 'r');
438 buf
= PyString_AS_STRING(formatv
);
439 Py_BEGIN_ALLOW_THREADS
447 complex_repr(PyComplexObject
*v
)
449 return complex_format(v
, 0, 'r');
453 complex_str(PyComplexObject
*v
)
455 return complex_format(v
, PyFloat_STR_PRECISION
, 'g');
459 complex_hash(PyComplexObject
*v
)
461 long hashreal
, hashimag
, combined
;
462 hashreal
= _Py_HashDouble(v
->cval
.real
);
465 hashimag
= _Py_HashDouble(v
->cval
.imag
);
468 /* Note: if the imaginary part is 0, hashimag is 0 now,
469 * so the following returns hashreal unchanged. This is
470 * important because numbers of different types that
471 * compare equal must have the same hash value, so that
472 * hash(x + 0*j) must equal hash(x).
474 combined
= hashreal
+ 1000003 * hashimag
;
480 /* This macro may return! */
481 #define TO_COMPLEX(obj, c) \
482 if (PyComplex_Check(obj)) \
483 c = ((PyComplexObject *)(obj))->cval; \
484 else if (to_complex(&(obj), &(c)) < 0) \
488 to_complex(PyObject
**pobj
, Py_complex
*pc
)
490 PyObject
*obj
= *pobj
;
492 pc
->real
= pc
->imag
= 0.0;
493 if (PyInt_Check(obj
)) {
494 pc
->real
= PyInt_AS_LONG(obj
);
497 if (PyLong_Check(obj
)) {
498 pc
->real
= PyLong_AsDouble(obj
);
499 if (pc
->real
== -1.0 && PyErr_Occurred()) {
505 if (PyFloat_Check(obj
)) {
506 pc
->real
= PyFloat_AsDouble(obj
);
509 Py_INCREF(Py_NotImplemented
);
510 *pobj
= Py_NotImplemented
;
516 complex_add(PyComplexObject
*v
, PyComplexObject
*w
)
519 PyFPE_START_PROTECT("complex_add", return 0)
520 result
= c_sum(v
->cval
,w
->cval
);
521 PyFPE_END_PROTECT(result
)
522 return PyComplex_FromCComplex(result
);
526 complex_sub(PyComplexObject
*v
, PyComplexObject
*w
)
529 PyFPE_START_PROTECT("complex_sub", return 0)
530 result
= c_diff(v
->cval
,w
->cval
);
531 PyFPE_END_PROTECT(result
)
532 return PyComplex_FromCComplex(result
);
536 complex_mul(PyComplexObject
*v
, PyComplexObject
*w
)
539 PyFPE_START_PROTECT("complex_mul", return 0)
540 result
= c_prod(v
->cval
,w
->cval
);
541 PyFPE_END_PROTECT(result
)
542 return PyComplex_FromCComplex(result
);
546 complex_div(PyComplexObject
*v
, PyComplexObject
*w
)
550 PyFPE_START_PROTECT("complex_div", return 0)
552 quot
= c_quot(v
->cval
,w
->cval
);
553 PyFPE_END_PROTECT(quot
)
555 PyErr_SetString(PyExc_ZeroDivisionError
, "complex division");
558 return PyComplex_FromCComplex(quot
);
562 complex_classic_div(PyComplexObject
*v
, PyComplexObject
*w
)
566 if (Py_DivisionWarningFlag
>= 2 &&
567 PyErr_Warn(PyExc_DeprecationWarning
,
568 "classic complex division") < 0)
571 PyFPE_START_PROTECT("complex_classic_div", return 0)
573 quot
= c_quot(v
->cval
,w
->cval
);
574 PyFPE_END_PROTECT(quot
)
576 PyErr_SetString(PyExc_ZeroDivisionError
, "complex division");
579 return PyComplex_FromCComplex(quot
);
583 complex_remainder(PyComplexObject
*v
, PyComplexObject
*w
)
587 if (PyErr_Warn(PyExc_DeprecationWarning
,
588 "complex divmod(), // and % are deprecated") < 0)
592 div
= c_quot(v
->cval
,w
->cval
); /* The raw divisor value. */
594 PyErr_SetString(PyExc_ZeroDivisionError
, "complex remainder");
597 div
.real
= floor(div
.real
); /* Use the floor of the real part. */
599 mod
= c_diff(v
->cval
, c_prod(w
->cval
, div
));
601 return PyComplex_FromCComplex(mod
);
606 complex_divmod(PyComplexObject
*v
, PyComplexObject
*w
)
611 if (PyErr_Warn(PyExc_DeprecationWarning
,
612 "complex divmod(), // and % are deprecated") < 0)
616 div
= c_quot(v
->cval
,w
->cval
); /* The raw divisor value. */
618 PyErr_SetString(PyExc_ZeroDivisionError
, "complex divmod()");
621 div
.real
= floor(div
.real
); /* Use the floor of the real part. */
623 mod
= c_diff(v
->cval
, c_prod(w
->cval
, div
));
624 d
= PyComplex_FromCComplex(div
);
625 m
= PyComplex_FromCComplex(mod
);
626 z
= PyTuple_Pack(2, d
, m
);
633 complex_pow(PyObject
*v
, PyObject
*w
, PyObject
*z
)
643 PyErr_SetString(PyExc_ValueError
, "complex modulo");
646 PyFPE_START_PROTECT("complex_pow", return 0)
649 int_exponent
= (long)exponent
.real
;
650 if (exponent
.imag
== 0. && exponent
.real
== int_exponent
)
651 p
= c_powi(a
,int_exponent
);
653 p
= c_pow(a
,exponent
);
656 Py_ADJUST_ERANGE2(p
.real
, p
.imag
);
658 PyErr_SetString(PyExc_ZeroDivisionError
,
659 "0.0 to a negative or complex power");
662 else if (errno
== ERANGE
) {
663 PyErr_SetString(PyExc_OverflowError
,
664 "complex exponentiation");
667 return PyComplex_FromCComplex(p
);
671 complex_int_div(PyComplexObject
*v
, PyComplexObject
*w
)
675 if (PyErr_Warn(PyExc_DeprecationWarning
,
676 "complex divmod(), // and % are deprecated") < 0)
679 t
= complex_divmod(v
, w
);
681 r
= PyTuple_GET_ITEM(t
, 0);
690 complex_neg(PyComplexObject
*v
)
693 neg
.real
= -v
->cval
.real
;
694 neg
.imag
= -v
->cval
.imag
;
695 return PyComplex_FromCComplex(neg
);
699 complex_pos(PyComplexObject
*v
)
701 if (PyComplex_CheckExact(v
)) {
703 return (PyObject
*)v
;
706 return PyComplex_FromCComplex(v
->cval
);
710 complex_abs(PyComplexObject
*v
)
714 PyFPE_START_PROTECT("complex_abs", return 0)
715 result
= c_abs(v
->cval
);
716 PyFPE_END_PROTECT(result
)
718 if (errno
== ERANGE
) {
719 PyErr_SetString(PyExc_OverflowError
,
720 "absolute value too large");
723 return PyFloat_FromDouble(result
);
727 complex_nonzero(PyComplexObject
*v
)
729 return v
->cval
.real
!= 0.0 || v
->cval
.imag
!= 0.0;
733 complex_coerce(PyObject
**pv
, PyObject
**pw
)
737 if (PyInt_Check(*pw
)) {
738 cval
.real
= (double)PyInt_AsLong(*pw
);
739 *pw
= PyComplex_FromCComplex(cval
);
743 else if (PyLong_Check(*pw
)) {
744 cval
.real
= PyLong_AsDouble(*pw
);
745 if (cval
.real
== -1.0 && PyErr_Occurred())
747 *pw
= PyComplex_FromCComplex(cval
);
751 else if (PyFloat_Check(*pw
)) {
752 cval
.real
= PyFloat_AsDouble(*pw
);
753 *pw
= PyComplex_FromCComplex(cval
);
757 else if (PyComplex_Check(*pw
)) {
762 return 1; /* Can't do it */
766 complex_richcompare(PyObject
*v
, PyObject
*w
, int op
)
772 c
= PyNumber_CoerceEx(&v
, &w
);
776 Py_INCREF(Py_NotImplemented
);
777 return Py_NotImplemented
;
779 /* Make sure both arguments are complex. */
780 if (!(PyComplex_Check(v
) && PyComplex_Check(w
))) {
783 Py_INCREF(Py_NotImplemented
);
784 return Py_NotImplemented
;
787 i
= ((PyComplexObject
*)v
)->cval
;
788 j
= ((PyComplexObject
*)w
)->cval
;
792 if (op
!= Py_EQ
&& op
!= Py_NE
) {
793 PyErr_SetString(PyExc_TypeError
,
794 "no ordering relation is defined for complex numbers");
798 if ((i
.real
== j
.real
&& i
.imag
== j
.imag
) == (op
== Py_EQ
))
808 complex_int(PyObject
*v
)
810 PyErr_SetString(PyExc_TypeError
,
811 "can't convert complex to int");
816 complex_long(PyObject
*v
)
818 PyErr_SetString(PyExc_TypeError
,
819 "can't convert complex to long");
824 complex_float(PyObject
*v
)
826 PyErr_SetString(PyExc_TypeError
,
827 "can't convert complex to float");
832 complex_conjugate(PyObject
*self
)
835 c
= ((PyComplexObject
*)self
)->cval
;
837 return PyComplex_FromCComplex(c
);
840 PyDoc_STRVAR(complex_conjugate_doc
,
841 "complex.conjugate() -> complex\n"
843 "Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
846 complex_getnewargs(PyComplexObject
*v
)
848 Py_complex c
= v
->cval
;
849 return Py_BuildValue("(dd)", c
.real
, c
.imag
);
852 PyDoc_STRVAR(complex__format__doc
,
853 "complex.__format__() -> str\n"
855 "Converts to a string according to format_spec.");
858 complex__format__(PyObject
* self
, PyObject
* args
)
860 PyObject
*format_spec
;
862 if (!PyArg_ParseTuple(args
, "O:__format__", &format_spec
))
864 if (PyBytes_Check(format_spec
))
865 return _PyComplex_FormatAdvanced(self
,
866 PyBytes_AS_STRING(format_spec
),
867 PyBytes_GET_SIZE(format_spec
));
868 if (PyUnicode_Check(format_spec
)) {
869 /* Convert format_spec to a str */
871 PyObject
*str_spec
= PyObject_Str(format_spec
);
873 if (str_spec
== NULL
)
876 result
= _PyComplex_FormatAdvanced(self
,
877 PyBytes_AS_STRING(str_spec
),
878 PyBytes_GET_SIZE(str_spec
));
883 PyErr_SetString(PyExc_TypeError
, "__format__ requires str or unicode");
889 complex_is_finite(PyObject
*self
)
892 c
= ((PyComplexObject
*)self
)->cval
;
893 return PyBool_FromLong((long)(Py_IS_FINITE(c
.real
) &&
894 Py_IS_FINITE(c
.imag
)));
897 PyDoc_STRVAR(complex_is_finite_doc
,
898 "complex.is_finite() -> bool\n"
900 "Returns True if the real and the imaginary part is finite.");
903 static PyMethodDef complex_methods
[] = {
904 {"conjugate", (PyCFunction
)complex_conjugate
, METH_NOARGS
,
905 complex_conjugate_doc
},
907 {"is_finite", (PyCFunction
)complex_is_finite
, METH_NOARGS
,
908 complex_is_finite_doc
},
910 {"__getnewargs__", (PyCFunction
)complex_getnewargs
, METH_NOARGS
},
911 {"__format__", (PyCFunction
)complex__format__
,
912 METH_VARARGS
, complex__format__doc
},
913 {NULL
, NULL
} /* sentinel */
916 static PyMemberDef complex_members
[] = {
917 {"real", T_DOUBLE
, offsetof(PyComplexObject
, cval
.real
), READONLY
,
918 "the real part of a complex number"},
919 {"imag", T_DOUBLE
, offsetof(PyComplexObject
, cval
.imag
), READONLY
,
920 "the imaginary part of a complex number"},
925 complex_subtype_from_string(PyTypeObject
*type
, PyObject
*v
)
927 const char *s
, *start
;
929 double x
=0.0, y
=0.0, z
;
931 #ifdef Py_USING_UNICODE
932 char *s_buffer
= NULL
;
936 if (PyString_Check(v
)) {
937 s
= PyString_AS_STRING(v
);
938 len
= PyString_GET_SIZE(v
);
940 #ifdef Py_USING_UNICODE
941 else if (PyUnicode_Check(v
)) {
942 s_buffer
= (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v
)+1);
943 if (s_buffer
== NULL
)
944 return PyErr_NoMemory();
945 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
946 PyUnicode_GET_SIZE(v
),
954 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
955 PyErr_SetString(PyExc_TypeError
,
956 "complex() arg is not a string");
960 /* position on first nonblank */
962 while (Py_ISSPACE(*s
))
965 /* Skip over possible bracket from repr(). */
968 while (Py_ISSPACE(*s
))
972 /* a valid complex string usually takes one of the three forms:
974 <float> - real part only
975 <float>j - imaginary part only
976 <float><signed-float>j - real and imaginary parts
978 where <float> represents any numeric string that's accepted by the
979 float constructor (including 'nan', 'inf', 'infinity', etc.), and
980 <signed-float> is any string of the form <float> whose first
981 character is '+' or '-'.
983 For backwards compatibility, the extra forms
989 are also accepted, though support for these forms may be removed from
990 a future version of Python.
993 /* first look for forms starting with <float> */
994 z
= PyOS_string_to_double(s
, &end
, NULL
);
995 if (z
== -1.0 && PyErr_Occurred()) {
996 if (PyErr_ExceptionMatches(PyExc_ValueError
))
1002 /* all 4 forms starting with <float> land here */
1004 if (*s
== '+' || *s
== '-') {
1005 /* <float><signed-float>j | <float><sign>j */
1007 y
= PyOS_string_to_double(s
, &end
, NULL
);
1008 if (y
== -1.0 && PyErr_Occurred()) {
1009 if (PyErr_ExceptionMatches(PyExc_ValueError
))
1015 /* <float><signed-float>j */
1018 /* <float><sign>j */
1019 y
= *s
== '+' ? 1.0 : -1.0;
1022 if (!(*s
== 'j' || *s
== 'J'))
1026 else if (*s
== 'j' || *s
== 'J') {
1036 /* not starting with <float>; must be <sign>j or j */
1037 if (*s
== '+' || *s
== '-') {
1039 y
= *s
== '+' ? 1.0 : -1.0;
1045 if (!(*s
== 'j' || *s
== 'J'))
1050 /* trailing whitespace and closing bracket */
1051 while (Py_ISSPACE(*s
))
1054 /* if there was an opening parenthesis, then the corresponding
1055 closing parenthesis should be right here */
1059 while (Py_ISSPACE(*s
))
1063 /* we should now be at the end of the string */
1068 #ifdef Py_USING_UNICODE
1070 PyMem_FREE(s_buffer
);
1072 return complex_subtype_from_doubles(type
, x
, y
);
1075 PyErr_SetString(PyExc_ValueError
,
1076 "complex() arg is a malformed string");
1078 #ifdef Py_USING_UNICODE
1080 PyMem_FREE(s_buffer
);
1086 complex_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1088 PyObject
*r
, *i
, *tmp
;
1089 PyNumberMethods
*nbr
, *nbi
= NULL
;
1092 int cr_is_complex
= 0;
1093 int ci_is_complex
= 0;
1094 static char *kwlist
[] = {"real", "imag", 0};
1098 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|OO:complex", kwlist
,
1102 /* Special-case for a single argument when type(arg) is complex. */
1103 if (PyComplex_CheckExact(r
) && i
== NULL
&&
1104 type
== &PyComplex_Type
) {
1105 /* Note that we can't know whether it's safe to return
1106 a complex *subclass* instance as-is, hence the restriction
1107 to exact complexes here. If either the input or the
1108 output is a complex subclass, it will be handled below
1109 as a non-orthogonal vector. */
1113 if (PyString_Check(r
) || PyUnicode_Check(r
)) {
1115 PyErr_SetString(PyExc_TypeError
,
1116 "complex() can't take second arg"
1117 " if first is a string");
1120 return complex_subtype_from_string(type
, r
);
1122 if (i
!= NULL
&& (PyString_Check(i
) || PyUnicode_Check(i
))) {
1123 PyErr_SetString(PyExc_TypeError
,
1124 "complex() second arg can't be a string");
1128 tmp
= try_complex_special_method(r
);
1133 else if (PyErr_Occurred()) {
1137 nbr
= r
->ob_type
->tp_as_number
;
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");
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
;
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
);
1173 /* r was a newly created complex number, rather
1174 than the original "real" argument. */
1179 if (!PyFloat_Check(tmp
)) {
1180 PyErr_SetString(PyExc_TypeError
,
1181 "float(r) didn't return a float");
1185 cr
.real
= PyFloat_AsDouble(tmp
);
1186 cr
.imag
= 0.0; /* Shut up compiler warning */
1192 else if (PyComplex_Check(i
)) {
1193 ci
= ((PyComplexObject
*)i
)->cval
;
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
);
1202 ci
.real
= PyFloat_AsDouble(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
) {
1212 if (cr_is_complex
) {
1215 return complex_subtype_from_doubles(type
, cr
.real
, ci
.real
);
1218 PyDoc_STRVAR(complex_doc
,
1219 "complex(real[, imag]) -> complex number\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 */
1242 complex_coerce
, /* nb_coerce */
1243 complex_int
, /* nb_int */
1244 complex_long
, /* nb_long */
1245 complex_float
, /* nb_float */
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)
1268 sizeof(PyComplexObject
),
1270 complex_dealloc
, /* tp_dealloc */
1271 (printfunc
)complex_print
, /* tp_print */
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 */
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 */
1289 complex_richcompare
, /* tp_richcompare */
1290 0, /* tp_weaklistoffset */
1292 0, /* tp_iternext */
1293 complex_methods
, /* tp_methods */
1294 complex_members
, /* tp_members */
1298 0, /* tp_descr_get */
1299 0, /* tp_descr_set */
1300 0, /* tp_dictoffset */
1302 PyType_GenericAlloc
, /* tp_alloc */
1303 complex_new
, /* tp_new */
1304 PyObject_Del
, /* tp_free */