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
));
187 complex_subtype_from_c_complex(PyTypeObject
*type
, Py_complex cval
)
191 op
= type
->tp_alloc(type
, 0);
193 ((PyComplexObject
*)op
)->cval
= cval
;
198 PyComplex_FromCComplex(Py_complex cval
)
200 register PyComplexObject
*op
;
202 /* Inline PyObject_New */
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
)
276 if (v
->cval
.real
== 0.) {
277 PyOS_snprintf(format
, 32, "%%.%ig", precision
);
278 PyOS_ascii_formatd(buf
, bufsz
, format
, v
->cval
.imag
);
279 strncat(buf
, "j", bufsz
);
282 /* Format imaginary part with sign, real part without */
283 PyOS_snprintf(format
, 32, "%%.%ig", precision
);
284 PyOS_ascii_formatd(re
, 64, format
, v
->cval
.real
);
285 PyOS_snprintf(format
, 32, "%%+.%ig", precision
);
286 PyOS_ascii_formatd(im
, 64, format
, v
->cval
.imag
);
287 PyOS_snprintf(buf
, bufsz
, "(%s%sj)", re
, im
);
292 complex_print(PyComplexObject
*v
, FILE *fp
, int flags
)
295 complex_to_buf(buf
, sizeof(buf
), v
,
296 (flags
& Py_PRINT_RAW
) ? PREC_STR
: PREC_REPR
);
302 complex_repr(PyComplexObject
*v
)
305 complex_to_buf(buf
, sizeof(buf
), v
, PREC_REPR
);
306 return PyString_FromString(buf
);
310 complex_str(PyComplexObject
*v
)
313 complex_to_buf(buf
, sizeof(buf
), v
, PREC_STR
);
314 return PyString_FromString(buf
);
318 complex_hash(PyComplexObject
*v
)
320 long hashreal
, hashimag
, combined
;
321 hashreal
= _Py_HashDouble(v
->cval
.real
);
324 hashimag
= _Py_HashDouble(v
->cval
.imag
);
327 /* Note: if the imaginary part is 0, hashimag is 0 now,
328 * so the following returns hashreal unchanged. This is
329 * important because numbers of different types that
330 * compare equal must have the same hash value, so that
331 * hash(x + 0*j) must equal hash(x).
333 combined
= hashreal
+ 1000003 * hashimag
;
340 complex_add(PyComplexObject
*v
, PyComplexObject
*w
)
343 PyFPE_START_PROTECT("complex_add", return 0)
344 result
= c_sum(v
->cval
,w
->cval
);
345 PyFPE_END_PROTECT(result
)
346 return PyComplex_FromCComplex(result
);
350 complex_sub(PyComplexObject
*v
, PyComplexObject
*w
)
353 PyFPE_START_PROTECT("complex_sub", return 0)
354 result
= c_diff(v
->cval
,w
->cval
);
355 PyFPE_END_PROTECT(result
)
356 return PyComplex_FromCComplex(result
);
360 complex_mul(PyComplexObject
*v
, PyComplexObject
*w
)
363 PyFPE_START_PROTECT("complex_mul", return 0)
364 result
= c_prod(v
->cval
,w
->cval
);
365 PyFPE_END_PROTECT(result
)
366 return PyComplex_FromCComplex(result
);
370 complex_div(PyComplexObject
*v
, PyComplexObject
*w
)
373 PyFPE_START_PROTECT("complex_div", return 0)
375 quot
= c_quot(v
->cval
,w
->cval
);
376 PyFPE_END_PROTECT(quot
)
378 PyErr_SetString(PyExc_ZeroDivisionError
, "complex division");
381 return PyComplex_FromCComplex(quot
);
385 complex_classic_div(PyComplexObject
*v
, PyComplexObject
*w
)
389 if (Py_DivisionWarningFlag
>= 2 &&
390 PyErr_Warn(PyExc_DeprecationWarning
,
391 "classic complex division") < 0)
394 PyFPE_START_PROTECT("complex_classic_div", return 0)
396 quot
= c_quot(v
->cval
,w
->cval
);
397 PyFPE_END_PROTECT(quot
)
399 PyErr_SetString(PyExc_ZeroDivisionError
, "complex division");
402 return PyComplex_FromCComplex(quot
);
406 complex_remainder(PyComplexObject
*v
, PyComplexObject
*w
)
410 if (PyErr_Warn(PyExc_DeprecationWarning
,
411 "complex divmod(), // and % are deprecated") < 0)
415 div
= c_quot(v
->cval
,w
->cval
); /* The raw divisor value. */
417 PyErr_SetString(PyExc_ZeroDivisionError
, "complex remainder");
420 div
.real
= floor(div
.real
); /* Use the floor of the real part. */
422 mod
= c_diff(v
->cval
, c_prod(w
->cval
, div
));
424 return PyComplex_FromCComplex(mod
);
429 complex_divmod(PyComplexObject
*v
, PyComplexObject
*w
)
434 if (PyErr_Warn(PyExc_DeprecationWarning
,
435 "complex divmod(), // and % are deprecated") < 0)
439 div
= c_quot(v
->cval
,w
->cval
); /* The raw divisor value. */
441 PyErr_SetString(PyExc_ZeroDivisionError
, "complex divmod()");
444 div
.real
= floor(div
.real
); /* Use the floor of the real part. */
446 mod
= c_diff(v
->cval
, c_prod(w
->cval
, div
));
447 d
= PyComplex_FromCComplex(div
);
448 m
= PyComplex_FromCComplex(mod
);
449 z
= PyTuple_Pack(2, d
, m
);
456 complex_pow(PyComplexObject
*v
, PyObject
*w
, PyComplexObject
*z
)
462 if ((PyObject
*)z
!=Py_None
) {
463 PyErr_SetString(PyExc_ValueError
, "complex modulo");
466 PyFPE_START_PROTECT("complex_pow", return 0)
468 exponent
= ((PyComplexObject
*)w
)->cval
;
469 int_exponent
= (long)exponent
.real
;
470 if (exponent
.imag
== 0. && exponent
.real
== int_exponent
)
471 p
= c_powi(v
->cval
,int_exponent
);
473 p
= c_pow(v
->cval
,exponent
);
476 Py_ADJUST_ERANGE2(p
.real
, p
.imag
);
478 PyErr_SetString(PyExc_ZeroDivisionError
,
479 "0.0 to a negative or complex power");
482 else if (errno
== ERANGE
) {
483 PyErr_SetString(PyExc_OverflowError
,
484 "complex exponentiaion");
487 return PyComplex_FromCComplex(p
);
491 complex_int_div(PyComplexObject
*v
, PyComplexObject
*w
)
495 t
= complex_divmod(v
, w
);
497 r
= PyTuple_GET_ITEM(t
, 0);
506 complex_neg(PyComplexObject
*v
)
509 neg
.real
= -v
->cval
.real
;
510 neg
.imag
= -v
->cval
.imag
;
511 return PyComplex_FromCComplex(neg
);
515 complex_pos(PyComplexObject
*v
)
517 if (PyComplex_CheckExact(v
)) {
519 return (PyObject
*)v
;
522 return PyComplex_FromCComplex(v
->cval
);
526 complex_abs(PyComplexObject
*v
)
529 PyFPE_START_PROTECT("complex_abs", return 0)
530 result
= hypot(v
->cval
.real
,v
->cval
.imag
);
531 PyFPE_END_PROTECT(result
)
532 return PyFloat_FromDouble(result
);
536 complex_nonzero(PyComplexObject
*v
)
538 return v
->cval
.real
!= 0.0 || v
->cval
.imag
!= 0.0;
542 complex_coerce(PyObject
**pv
, PyObject
**pw
)
546 if (PyInt_Check(*pw
)) {
547 cval
.real
= (double)PyInt_AsLong(*pw
);
548 *pw
= PyComplex_FromCComplex(cval
);
552 else if (PyLong_Check(*pw
)) {
553 cval
.real
= PyLong_AsDouble(*pw
);
554 if (cval
.real
== -1.0 && PyErr_Occurred())
556 *pw
= PyComplex_FromCComplex(cval
);
560 else if (PyFloat_Check(*pw
)) {
561 cval
.real
= PyFloat_AsDouble(*pw
);
562 *pw
= PyComplex_FromCComplex(cval
);
566 else if (PyComplex_Check(*pw
)) {
571 return 1; /* Can't do it */
575 complex_richcompare(PyObject
*v
, PyObject
*w
, int op
)
581 c
= PyNumber_CoerceEx(&v
, &w
);
585 Py_INCREF(Py_NotImplemented
);
586 return Py_NotImplemented
;
588 /* Make sure both arguments are complex. */
589 if (!(PyComplex_Check(v
) && PyComplex_Check(w
))) {
592 Py_INCREF(Py_NotImplemented
);
593 return Py_NotImplemented
;
596 i
= ((PyComplexObject
*)v
)->cval
;
597 j
= ((PyComplexObject
*)w
)->cval
;
601 if (op
!= Py_EQ
&& op
!= Py_NE
) {
602 PyErr_SetString(PyExc_TypeError
,
603 "no ordering relation is defined for complex numbers");
607 if ((i
.real
== j
.real
&& i
.imag
== j
.imag
) == (op
== Py_EQ
))
617 complex_int(PyObject
*v
)
619 PyErr_SetString(PyExc_TypeError
,
620 "can't convert complex to int; use int(abs(z))");
625 complex_long(PyObject
*v
)
627 PyErr_SetString(PyExc_TypeError
,
628 "can't convert complex to long; use long(abs(z))");
633 complex_float(PyObject
*v
)
635 PyErr_SetString(PyExc_TypeError
,
636 "can't convert complex to float; use abs(z)");
641 complex_conjugate(PyObject
*self
)
644 c
= ((PyComplexObject
*)self
)->cval
;
646 return PyComplex_FromCComplex(c
);
650 complex_getnewargs(PyComplexObject
*v
)
652 return Py_BuildValue("(D)", &v
->cval
);
655 static PyMethodDef complex_methods
[] = {
656 {"conjugate", (PyCFunction
)complex_conjugate
, METH_NOARGS
},
657 {"__getnewargs__", (PyCFunction
)complex_getnewargs
, METH_NOARGS
},
658 {NULL
, NULL
} /* sentinel */
661 static PyMemberDef complex_members
[] = {
662 {"real", T_DOUBLE
, offsetof(PyComplexObject
, cval
.real
), READONLY
,
663 "the real part of a complex number"},
664 {"imag", T_DOUBLE
, offsetof(PyComplexObject
, cval
.imag
), READONLY
,
665 "the imaginary part of a complex number"},
670 complex_subtype_from_string(PyTypeObject
*type
, PyObject
*v
)
672 const char *s
, *start
;
674 double x
=0.0, y
=0.0, z
;
675 int got_re
=0, got_im
=0, done
=0;
679 char buffer
[256]; /* For errors */
680 #ifdef Py_USING_UNICODE
685 if (PyString_Check(v
)) {
686 s
= PyString_AS_STRING(v
);
687 len
= PyString_GET_SIZE(v
);
689 #ifdef Py_USING_UNICODE
690 else if (PyUnicode_Check(v
)) {
691 if (PyUnicode_GET_SIZE(v
) >= (Py_ssize_t
)sizeof(s_buffer
)) {
692 PyErr_SetString(PyExc_ValueError
,
693 "complex() literal too large to convert");
696 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v
),
697 PyUnicode_GET_SIZE(v
),
705 else if (PyObject_AsCharBuffer(v
, &s
, &len
)) {
706 PyErr_SetString(PyExc_TypeError
,
707 "complex() arg is not a string");
711 /* position on first nonblank */
713 while (*s
&& isspace(Py_CHARMASK(*s
)))
716 PyErr_SetString(PyExc_ValueError
,
717 "complex() arg is an empty string");
728 if (s
-start
!= len
) {
731 "complex() arg contains a null byte");
734 if(!done
) sw_error
=1;
741 if (done
) sw_error
=1;
743 if ( *s
=='\0'||*s
=='+'||*s
=='-' ||
744 isspace(Py_CHARMASK(*s
)) ) sw_error
=1;
749 if (got_im
|| done
) {
761 if (*s
!='+' && *s
!='-' )
766 if (isspace(Py_CHARMASK(*s
))) {
767 while (*s
&& isspace(Py_CHARMASK(*s
)))
776 (*s
=='.' || isdigit(Py_CHARMASK(*s
)));
777 if (done
||!digit_or_dot
) {
782 PyFPE_START_PROTECT("strtod", return 0)
783 z
= PyOS_ascii_strtod(s
, &end
) ;
786 PyOS_snprintf(buffer
, sizeof(buffer
),
787 "float() out of range: %.150s", s
);
794 if (*s
=='J' || *s
=='j') {
803 /* accept a real part */
811 } /* end of switch */
813 } while (s
- start
< len
&& !sw_error
);
816 PyErr_SetString(PyExc_ValueError
,
817 "complex() arg is a malformed string");
821 return complex_subtype_from_doubles(type
, x
, y
);
825 complex_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
827 PyObject
*r
, *i
, *tmp
, *f
;
828 PyNumberMethods
*nbr
, *nbi
= NULL
;
831 static PyObject
*complexstr
;
832 static char *kwlist
[] = {"real", "imag", 0};
836 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|OO:complex", kwlist
,
840 /* Special-case for single argument that is already complex */
841 if (PyComplex_CheckExact(r
) && i
== NULL
&&
842 type
== &PyComplex_Type
) {
843 /* Note that we can't know whether it's safe to return
844 a complex *subclass* instance as-is, hence the restriction
845 to exact complexes here. */
849 if (PyString_Check(r
) || PyUnicode_Check(r
)) {
851 PyErr_SetString(PyExc_TypeError
,
852 "complex() can't take second arg"
853 " if first is a string");
856 return complex_subtype_from_string(type
, r
);
858 if (i
!= NULL
&& (PyString_Check(i
) || PyUnicode_Check(i
))) {
859 PyErr_SetString(PyExc_TypeError
,
860 "complex() second arg can't be a string");
864 /* XXX Hack to support classes with __complex__ method */
865 if (complexstr
== NULL
) {
866 complexstr
= PyString_InternFromString("__complex__");
867 if (complexstr
== NULL
)
870 f
= PyObject_GetAttr(r
, complexstr
);
874 PyObject
*args
= PyTuple_New(0);
877 r
= PyEval_CallObject(f
, args
);
884 nbr
= r
->ob_type
->tp_as_number
;
886 nbi
= i
->ob_type
->tp_as_number
;
887 if (nbr
== NULL
|| nbr
->nb_float
== NULL
||
888 ((i
!= NULL
) && (nbi
== NULL
|| nbi
->nb_float
== NULL
))) {
889 PyErr_SetString(PyExc_TypeError
,
890 "complex() argument must be a string or a number");
896 if (PyComplex_Check(r
)) {
897 /* Note that if r is of a complex subtype, we're only
898 retaining its real & imag parts here, and the return
899 value is (properly) of the builtin complex type. */
900 cr
= ((PyComplexObject
*)r
)->cval
;
906 tmp
= PyNumber_Float(r
);
912 if (!PyFloat_Check(tmp
)) {
913 PyErr_SetString(PyExc_TypeError
,
914 "float(r) didn't return a float");
918 cr
.real
= PyFloat_AsDouble(tmp
);
926 else if (PyComplex_Check(i
))
927 ci
= ((PyComplexObject
*)i
)->cval
;
929 tmp
= (*nbi
->nb_float
)(i
);
932 ci
.real
= PyFloat_AsDouble(tmp
);
938 return complex_subtype_from_c_complex(type
, cr
);
941 PyDoc_STRVAR(complex_doc
,
942 "complex(real[, imag]) -> complex number\n"
944 "Create a complex number from a real part and an optional imaginary part.\n"
945 "This is equivalent to (real + imag*1j) where imag defaults to 0.");
947 static PyNumberMethods complex_as_number
= {
948 (binaryfunc
)complex_add
, /* nb_add */
949 (binaryfunc
)complex_sub
, /* nb_subtract */
950 (binaryfunc
)complex_mul
, /* nb_multiply */
951 (binaryfunc
)complex_classic_div
, /* nb_divide */
952 (binaryfunc
)complex_remainder
, /* nb_remainder */
953 (binaryfunc
)complex_divmod
, /* nb_divmod */
954 (ternaryfunc
)complex_pow
, /* nb_power */
955 (unaryfunc
)complex_neg
, /* nb_negative */
956 (unaryfunc
)complex_pos
, /* nb_positive */
957 (unaryfunc
)complex_abs
, /* nb_absolute */
958 (inquiry
)complex_nonzero
, /* nb_nonzero */
965 complex_coerce
, /* nb_coerce */
966 complex_int
, /* nb_int */
967 complex_long
, /* nb_long */
968 complex_float
, /* nb_float */
971 0, /* nb_inplace_add */
972 0, /* nb_inplace_subtract */
973 0, /* nb_inplace_multiply*/
974 0, /* nb_inplace_divide */
975 0, /* nb_inplace_remainder */
976 0, /* nb_inplace_power */
977 0, /* nb_inplace_lshift */
978 0, /* nb_inplace_rshift */
979 0, /* nb_inplace_and */
980 0, /* nb_inplace_xor */
981 0, /* nb_inplace_or */
982 (binaryfunc
)complex_int_div
, /* nb_floor_divide */
983 (binaryfunc
)complex_div
, /* nb_true_divide */
984 0, /* nb_inplace_floor_divide */
985 0, /* nb_inplace_true_divide */
988 PyTypeObject PyComplex_Type
= {
989 PyObject_HEAD_INIT(&PyType_Type
)
992 sizeof(PyComplexObject
),
994 complex_dealloc
, /* tp_dealloc */
995 (printfunc
)complex_print
, /* tp_print */
999 (reprfunc
)complex_repr
, /* tp_repr */
1000 &complex_as_number
, /* tp_as_number */
1001 0, /* tp_as_sequence */
1002 0, /* tp_as_mapping */
1003 (hashfunc
)complex_hash
, /* tp_hash */
1005 (reprfunc
)complex_str
, /* tp_str */
1006 PyObject_GenericGetAttr
, /* tp_getattro */
1007 0, /* tp_setattro */
1008 0, /* tp_as_buffer */
1009 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
1010 complex_doc
, /* tp_doc */
1011 0, /* tp_traverse */
1013 complex_richcompare
, /* tp_richcompare */
1014 0, /* tp_weaklistoffset */
1016 0, /* tp_iternext */
1017 complex_methods
, /* tp_methods */
1018 complex_members
, /* tp_members */
1022 0, /* tp_descr_get */
1023 0, /* tp_descr_set */
1024 0, /* tp_dictoffset */
1026 PyType_GenericAlloc
, /* tp_alloc */
1027 complex_new
, /* tp_new */
1028 PyObject_Del
, /* tp_free */