2 /* Complex object implementation */
4 /* Borrows heavily from floatobject.c */
6 /* Submitted by Jim Hugunin */
8 #ifndef WITHOUT_COMPLEX
11 #include "structmember.h"
13 /* Precisions used by repr() and str(), respectively.
15 The repr() precision (17 significant decimal digits) is the minimal number
16 that is guaranteed to have enough precision so that if the number is read
17 back in the exact same binary value is recreated. This is true for IEEE
18 floating point by design, and also happens to work for all other modern
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
));
187 complex_subtype_from_c_complex(PyTypeObject
*type
, Py_complex cval
)
191 op
= PyType_GenericAlloc(type
, 0);
193 ((PyComplexObject
*)op
)->cval
= cval
;
198 PyComplex_FromCComplex(Py_complex cval
)
200 register PyComplexObject
*op
;
202 /* PyObject_New is inlined */
203 op
= (PyComplexObject
*) PyObject_MALLOC(sizeof(PyComplexObject
));
205 return PyErr_NoMemory();
206 PyObject_INIT(op
, &PyComplex_Type
);
208 return (PyObject
*) op
;
212 complex_subtype_from_doubles(PyTypeObject
*type
, double real
, double imag
)
217 return complex_subtype_from_c_complex(type
, c
);
221 PyComplex_FromDoubles(double real
, double imag
)
226 return PyComplex_FromCComplex(c
);
230 PyComplex_RealAsDouble(PyObject
*op
)
232 if (PyComplex_Check(op
)) {
233 return ((PyComplexObject
*)op
)->cval
.real
;
236 return PyFloat_AsDouble(op
);
241 PyComplex_ImagAsDouble(PyObject
*op
)
243 if (PyComplex_Check(op
)) {
244 return ((PyComplexObject
*)op
)->cval
.imag
;
252 PyComplex_AsCComplex(PyObject
*op
)
255 if (PyComplex_Check(op
)) {
256 return ((PyComplexObject
*)op
)->cval
;
259 cv
.real
= PyFloat_AsDouble(op
);
266 complex_dealloc(PyObject
*op
)
268 op
->ob_type
->tp_free(op
);
273 complex_to_buf(char *buf
, int bufsz
, PyComplexObject
*v
, int precision
)
275 if (v
->cval
.real
== 0.)
276 PyOS_snprintf(buf
, bufsz
, "%.*gj",
277 precision
, v
->cval
.imag
);
279 PyOS_snprintf(buf
, bufsz
, "(%.*g%+.*gj)",
280 precision
, v
->cval
.real
,
281 precision
, v
->cval
.imag
);
285 complex_print(PyComplexObject
*v
, FILE *fp
, int flags
)
288 complex_to_buf(buf
, sizeof(buf
), v
,
289 (flags
& Py_PRINT_RAW
) ? PREC_STR
: PREC_REPR
);
295 complex_repr(PyComplexObject
*v
)
298 complex_to_buf(buf
, sizeof(buf
), v
, PREC_REPR
);
299 return PyString_FromString(buf
);
303 complex_str(PyComplexObject
*v
)
306 complex_to_buf(buf
, sizeof(buf
), v
, PREC_STR
);
307 return PyString_FromString(buf
);
311 complex_hash(PyComplexObject
*v
)
313 long hashreal
, hashimag
, combined
;
314 hashreal
= _Py_HashDouble(v
->cval
.real
);
317 hashimag
= _Py_HashDouble(v
->cval
.imag
);
320 /* Note: if the imaginary part is 0, hashimag is 0 now,
321 * so the following returns hashreal unchanged. This is
322 * important because numbers of different types that
323 * compare equal must have the same hash value, so that
324 * hash(x + 0*j) must equal hash(x).
326 combined
= hashreal
+ 1000003 * hashimag
;
333 complex_add(PyComplexObject
*v
, PyComplexObject
*w
)
336 PyFPE_START_PROTECT("complex_add", return 0)
337 result
= c_sum(v
->cval
,w
->cval
);
338 PyFPE_END_PROTECT(result
)
339 return PyComplex_FromCComplex(result
);
343 complex_sub(PyComplexObject
*v
, PyComplexObject
*w
)
346 PyFPE_START_PROTECT("complex_sub", return 0)
347 result
= c_diff(v
->cval
,w
->cval
);
348 PyFPE_END_PROTECT(result
)
349 return PyComplex_FromCComplex(result
);
353 complex_mul(PyComplexObject
*v
, PyComplexObject
*w
)
356 PyFPE_START_PROTECT("complex_mul", return 0)
357 result
= c_prod(v
->cval
,w
->cval
);
358 PyFPE_END_PROTECT(result
)
359 return PyComplex_FromCComplex(result
);
363 complex_div(PyComplexObject
*v
, PyComplexObject
*w
)
366 PyFPE_START_PROTECT("complex_div", return 0)
368 quot
= c_quot(v
->cval
,w
->cval
);
369 PyFPE_END_PROTECT(quot
)
371 PyErr_SetString(PyExc_ZeroDivisionError
, "complex division");
374 return PyComplex_FromCComplex(quot
);
378 complex_classic_div(PyComplexObject
*v
, PyComplexObject
*w
)
382 if (Py_DivisionWarningFlag
>= 2 &&
383 PyErr_Warn(PyExc_DeprecationWarning
,
384 "classic complex division") < 0)
387 PyFPE_START_PROTECT("complex_classic_div", return 0)
389 quot
= c_quot(v
->cval
,w
->cval
);
390 PyFPE_END_PROTECT(quot
)
392 PyErr_SetString(PyExc_ZeroDivisionError
, "complex division");
395 return PyComplex_FromCComplex(quot
);
399 complex_remainder(PyComplexObject
*v
, PyComplexObject
*w
)
403 div
= c_quot(v
->cval
,w
->cval
); /* The raw divisor value. */
405 PyErr_SetString(PyExc_ZeroDivisionError
, "complex remainder");
408 div
.real
= floor(div
.real
); /* Use the floor of the real part. */
410 mod
= c_diff(v
->cval
, c_prod(w
->cval
, div
));
412 return PyComplex_FromCComplex(mod
);
417 complex_divmod(PyComplexObject
*v
, PyComplexObject
*w
)
422 div
= c_quot(v
->cval
,w
->cval
); /* The raw divisor value. */
424 PyErr_SetString(PyExc_ZeroDivisionError
, "complex divmod()");
427 div
.real
= floor(div
.real
); /* Use the floor of the real part. */
429 mod
= c_diff(v
->cval
, c_prod(w
->cval
, div
));
430 d
= PyComplex_FromCComplex(div
);
431 m
= PyComplex_FromCComplex(mod
);
432 z
= Py_BuildValue("(OO)", d
, m
);
439 complex_pow(PyComplexObject
*v
, PyObject
*w
, PyComplexObject
*z
)
445 if ((PyObject
*)z
!=Py_None
) {
446 PyErr_SetString(PyExc_ValueError
, "complex modulo");
449 PyFPE_START_PROTECT("complex_pow", return 0)
451 exponent
= ((PyComplexObject
*)w
)->cval
;
452 int_exponent
= (long)exponent
.real
;
453 if (exponent
.imag
== 0. && exponent
.real
== int_exponent
)
454 p
= c_powi(v
->cval
,int_exponent
);
456 p
= c_pow(v
->cval
,exponent
);
459 if (errno
== ERANGE
) {
460 PyErr_SetString(PyExc_ValueError
,
461 "0.0 to a negative or complex power");
464 return PyComplex_FromCComplex(p
);
468 complex_int_div(PyComplexObject
*v
, PyComplexObject
*w
)
472 t
= complex_divmod(v
, w
);
474 r
= PyTuple_GET_ITEM(t
, 0);
483 complex_neg(PyComplexObject
*v
)
486 neg
.real
= -v
->cval
.real
;
487 neg
.imag
= -v
->cval
.imag
;
488 return PyComplex_FromCComplex(neg
);
492 complex_pos(PyComplexObject
*v
)
494 if (PyComplex_CheckExact(v
)) {
496 return (PyObject
*)v
;
499 return PyComplex_FromCComplex(v
->cval
);
503 complex_abs(PyComplexObject
*v
)
506 PyFPE_START_PROTECT("complex_abs", return 0)
507 result
= hypot(v
->cval
.real
,v
->cval
.imag
);
508 PyFPE_END_PROTECT(result
)
509 return PyFloat_FromDouble(result
);
513 complex_nonzero(PyComplexObject
*v
)
515 return v
->cval
.real
!= 0.0 || v
->cval
.imag
!= 0.0;
519 complex_coerce(PyObject
**pv
, PyObject
**pw
)
523 if (PyInt_Check(*pw
)) {
524 cval
.real
= (double)PyInt_AsLong(*pw
);
525 *pw
= PyComplex_FromCComplex(cval
);
529 else if (PyLong_Check(*pw
)) {
530 cval
.real
= PyLong_AsDouble(*pw
);
531 if (cval
.real
== -1.0 && PyErr_Occurred())
533 *pw
= PyComplex_FromCComplex(cval
);
537 else if (PyFloat_Check(*pw
)) {
538 cval
.real
= PyFloat_AsDouble(*pw
);
539 *pw
= PyComplex_FromCComplex(cval
);
543 else if (PyComplex_Check(*pw
)) {
548 return 1; /* Can't do it */
552 complex_richcompare(PyObject
*v
, PyObject
*w
, int op
)
558 c
= PyNumber_CoerceEx(&v
, &w
);
562 Py_INCREF(Py_NotImplemented
);
563 return Py_NotImplemented
;
565 /* Make sure both arguments are complex. */
566 if (!(PyComplex_Check(v
) && PyComplex_Check(w
))) {
569 Py_INCREF(Py_NotImplemented
);
570 return Py_NotImplemented
;
573 i
= ((PyComplexObject
*)v
)->cval
;
574 j
= ((PyComplexObject
*)w
)->cval
;
578 if (op
!= Py_EQ
&& op
!= Py_NE
) {
579 PyErr_SetString(PyExc_TypeError
,
580 "cannot compare complex numbers using <, <=, >, >=");
584 if ((i
.real
== j
.real
&& i
.imag
== j
.imag
) == (op
== Py_EQ
))
594 complex_int(PyObject
*v
)
596 PyErr_SetString(PyExc_TypeError
,
597 "can't convert complex to int; use e.g. int(abs(z))");
602 complex_long(PyObject
*v
)
604 PyErr_SetString(PyExc_TypeError
,
605 "can't convert complex to long; use e.g. long(abs(z))");
610 complex_float(PyObject
*v
)
612 PyErr_SetString(PyExc_TypeError
,
613 "can't convert complex to float; use e.g. abs(z)");
618 complex_conjugate(PyObject
*self
)
621 c
= ((PyComplexObject
*)self
)->cval
;
623 return PyComplex_FromCComplex(c
);
626 static PyMethodDef complex_methods
[] = {
627 {"conjugate", (PyCFunction
)complex_conjugate
, METH_NOARGS
},
628 {NULL
, NULL
} /* sentinel */
631 static PyMemberDef complex_members
[] = {
632 {"real", T_DOUBLE
, offsetof(PyComplexObject
, cval
.real
), 0,
633 "the real part of a complex number"},
634 {"imag", T_DOUBLE
, offsetof(PyComplexObject
, cval
.imag
), 0,
635 "the imaginary part of a complex number"},
640 complex_subtype_from_string(PyTypeObject
*type
, PyObject
*v
)
642 extern double strtod(const char *, char **);
643 const char *s
, *start
;
645 double x
=0.0, y
=0.0, z
;
646 int got_re
=0, got_im
=0, done
=0;
650 char buffer
[256]; /* For errors */
651 #ifdef Py_USING_UNICODE
656 if (PyString_Check(v
)) {
657 s
= PyString_AS_STRING(v
);
658 len
= PyString_GET_SIZE(v
);
660 #ifdef Py_USING_UNICODE
661 else if (PyUnicode_Check(v
)) {
662 if (PyUnicode_GET_SIZE(v
) >= sizeof(s_buffer
)) {
663 PyErr_SetString(PyExc_ValueError
,
664 "complex() literal too large to convert");
667 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
668 PyUnicode_GET_SIZE(v
),
673 len
= (int)strlen(s
);
676 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
677 PyErr_SetString(PyExc_TypeError
,
678 "complex() arg is not a string");
682 /* position on first nonblank */
684 while (*s
&& isspace(Py_CHARMASK(*s
)))
687 PyErr_SetString(PyExc_ValueError
,
688 "complex() arg is an empty string");
699 if (s
-start
!= len
) {
702 "complex() arg contains a null byte");
705 if(!done
) sw_error
=1;
712 if (done
) sw_error
=1;
714 if ( *s
=='\0'||*s
=='+'||*s
=='-' ||
715 isspace(Py_CHARMASK(*s
)) ) sw_error
=1;
720 if (got_im
|| done
) {
732 if (*s
!='+' && *s
!='-' )
737 if (isspace(Py_CHARMASK(*s
))) {
738 while (*s
&& isspace(Py_CHARMASK(*s
)))
747 (*s
=='.' || isdigit(Py_CHARMASK(*s
)));
748 if (done
||!digit_or_dot
) {
753 PyFPE_START_PROTECT("strtod", return 0)
754 z
= strtod(s
, &end
) ;
757 PyOS_snprintf(buffer
, sizeof(buffer
),
758 "float() out of range: %.150s", s
);
765 if (*s
=='J' || *s
=='j') {
774 /* accept a real part */
782 } /* end of switch */
784 } while (*s
!='\0' && !sw_error
);
787 PyErr_SetString(PyExc_ValueError
,
788 "complex() arg is a malformed string");
792 return complex_subtype_from_doubles(type
, x
, y
);
796 complex_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
798 PyObject
*r
, *i
, *tmp
;
799 PyNumberMethods
*nbr
, *nbi
= NULL
;
802 static char *kwlist
[] = {"real", "imag", 0};
806 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|OO:complex", kwlist
,
809 if (PyString_Check(r
) || PyUnicode_Check(r
)) {
811 PyErr_SetString(PyExc_TypeError
,
812 "complex() can't take second arg"
813 " if first is a string");
816 return complex_subtype_from_string(type
, r
);
818 if (i
!= NULL
&& (PyString_Check(i
) || PyUnicode_Check(i
))) {
819 PyErr_SetString(PyExc_TypeError
,
820 "complex() second arg can't be a string");
824 nbr
= r
->ob_type
->tp_as_number
;
826 nbi
= i
->ob_type
->tp_as_number
;
827 if (nbr
== NULL
|| nbr
->nb_float
== NULL
||
828 ((i
!= NULL
) && (nbi
== NULL
|| nbi
->nb_float
== NULL
))) {
829 PyErr_SetString(PyExc_TypeError
,
830 "complex() arg can't be converted to complex");
833 /* XXX Hack to support classes with __complex__ method */
834 if (PyInstance_Check(r
)) {
835 static PyObject
*complexstr
;
837 if (complexstr
== NULL
) {
838 complexstr
= PyString_InternFromString("__complex__");
839 if (complexstr
== NULL
)
842 f
= PyObject_GetAttr(r
, complexstr
);
846 PyObject
*args
= Py_BuildValue("()");
849 r
= PyEval_CallObject(f
, args
);
857 if (PyComplex_Check(r
)) {
858 /* Note that if r is of a complex subtype, we're only
859 retaining its real & imag parts here, and the return
860 value is (properly) of the builtin complex type. */
861 cr
= ((PyComplexObject
*)r
)->cval
;
867 tmp
= PyNumber_Float(r
);
873 if (!PyFloat_Check(tmp
)) {
874 PyErr_SetString(PyExc_TypeError
,
875 "float(r) didn't return a float");
879 cr
.real
= PyFloat_AsDouble(tmp
);
887 else if (PyComplex_Check(i
))
888 ci
= ((PyComplexObject
*)i
)->cval
;
890 tmp
= (*nbi
->nb_float
)(i
);
893 ci
.real
= PyFloat_AsDouble(tmp
);
899 return complex_subtype_from_c_complex(type
, cr
);
902 static char complex_doc
[] =
903 "complex(real[, imag]) -> complex number\n"
905 "Create a complex number from a real part and an optional imaginary part.\n"
906 "This is equivalent to (real + imag*1j) where imag defaults to 0.";
908 static PyNumberMethods complex_as_number
= {
909 (binaryfunc
)complex_add
, /* nb_add */
910 (binaryfunc
)complex_sub
, /* nb_subtract */
911 (binaryfunc
)complex_mul
, /* nb_multiply */
912 (binaryfunc
)complex_classic_div
, /* nb_divide */
913 (binaryfunc
)complex_remainder
, /* nb_remainder */
914 (binaryfunc
)complex_divmod
, /* nb_divmod */
915 (ternaryfunc
)complex_pow
, /* nb_power */
916 (unaryfunc
)complex_neg
, /* nb_negative */
917 (unaryfunc
)complex_pos
, /* nb_positive */
918 (unaryfunc
)complex_abs
, /* nb_absolute */
919 (inquiry
)complex_nonzero
, /* nb_nonzero */
926 (coercion
)complex_coerce
, /* nb_coerce */
927 (unaryfunc
)complex_int
, /* nb_int */
928 (unaryfunc
)complex_long
, /* nb_long */
929 (unaryfunc
)complex_float
, /* nb_float */
932 0, /* nb_inplace_add */
933 0, /* nb_inplace_subtract */
934 0, /* nb_inplace_multiply*/
935 0, /* nb_inplace_divide */
936 0, /* nb_inplace_remainder */
937 0, /* nb_inplace_power */
938 0, /* nb_inplace_lshift */
939 0, /* nb_inplace_rshift */
940 0, /* nb_inplace_and */
941 0, /* nb_inplace_xor */
942 0, /* nb_inplace_or */
943 (binaryfunc
)complex_int_div
, /* nb_floor_divide */
944 (binaryfunc
)complex_div
, /* nb_true_divide */
945 0, /* nb_inplace_floor_divide */
946 0, /* nb_inplace_true_divide */
949 PyTypeObject PyComplex_Type
= {
950 PyObject_HEAD_INIT(&PyType_Type
)
953 sizeof(PyComplexObject
),
955 (destructor
)complex_dealloc
, /* tp_dealloc */
956 (printfunc
)complex_print
, /* tp_print */
960 (reprfunc
)complex_repr
, /* tp_repr */
961 &complex_as_number
, /* tp_as_number */
962 0, /* tp_as_sequence */
963 0, /* tp_as_mapping */
964 (hashfunc
)complex_hash
, /* tp_hash */
966 (reprfunc
)complex_str
, /* tp_str */
967 PyObject_GenericGetAttr
, /* tp_getattro */
969 0, /* tp_as_buffer */
970 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
971 complex_doc
, /* tp_doc */
974 complex_richcompare
, /* tp_richcompare */
975 0, /* tp_weaklistoffset */
978 complex_methods
, /* tp_methods */
979 complex_members
, /* tp_members */
983 0, /* tp_descr_get */
984 0, /* tp_descr_set */
985 0, /* tp_dictoffset */
988 complex_new
, /* tp_new */
989 _PyObject_Del
, /* tp_free */