blob: a5b76f0460055b4a006681f48fee71175b2becbc [file] [log] [blame]
Guido van Rossum96783941997-05-20 18:21:34 +00001
Guido van Rossumf9fca921996-01-12 00:47:05 +00002/* Complex object implementation */
3
4/* Borrows heavily from floatobject.c */
5
Guido van Rossum96783941997-05-20 18:21:34 +00006/* Submitted by Jim Hugunin */
7
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00009#include "structmember.h"
Guido van Rossumf9fca921996-01-12 00:47:05 +000010
Guido van Rossumf9fca921996-01-12 00:47:05 +000011/* elementary operations on complex numbers */
12
Guido van Rossum9e720e31996-07-21 02:31:35 +000013static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000014
Tim Peters0f336042001-03-18 08:21:57 +000015Py_complex
16c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018 Py_complex r;
19 r.real = a.real + b.real;
20 r.imag = a.imag + b.imag;
21 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000022}
23
Tim Peters0f336042001-03-18 08:21:57 +000024Py_complex
25c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 Py_complex r;
28 r.real = a.real - b.real;
29 r.imag = a.imag - b.imag;
30 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000031}
32
Tim Peters0f336042001-03-18 08:21:57 +000033Py_complex
34c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 Py_complex r;
37 r.real = -a.real;
38 r.imag = -a.imag;
39 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000040}
41
Tim Peters0f336042001-03-18 08:21:57 +000042Py_complex
43c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 Py_complex r;
46 r.real = a.real*b.real - a.imag*b.imag;
47 r.imag = a.real*b.imag + a.imag*b.real;
48 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000049}
50
Tim Peters0f336042001-03-18 08:21:57 +000051Py_complex
52c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 /******************************************************************
55 This was the original algorithm. It's grossly prone to spurious
56 overflow and underflow errors. It also merrily divides by 0 despite
57 checking for that(!). The code still serves a doc purpose here, as
58 the algorithm following is a simple by-cases transformation of this
59 one:
Tim Peters0f336042001-03-18 08:21:57 +000060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 Py_complex r;
62 double d = b.real*b.real + b.imag*b.imag;
63 if (d == 0.)
64 errno = EDOM;
65 r.real = (a.real*b.real + a.imag*b.imag)/d;
66 r.imag = (a.imag*b.real - a.real*b.imag)/d;
67 return r;
68 ******************************************************************/
Tim Peters0f336042001-03-18 08:21:57 +000069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 /* This algorithm is better, and is pretty obvious: first divide the
71 * numerators and denominator by whichever of {b.real, b.imag} has
72 * larger magnitude. The earliest reference I found was to CACM
73 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
74 * University). As usual, though, we're still ignoring all IEEE
75 * endcases.
76 */
77 Py_complex r; /* the result */
78 const double abs_breal = b.real < 0 ? -b.real : b.real;
79 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
Tim Peters0f336042001-03-18 08:21:57 +000080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 if (abs_breal >= abs_bimag) {
82 /* divide tops and bottom by b.real */
83 if (abs_breal == 0.0) {
84 errno = EDOM;
85 r.real = r.imag = 0.0;
86 }
87 else {
88 const double ratio = b.imag / b.real;
89 const double denom = b.real + b.imag * ratio;
90 r.real = (a.real + a.imag * ratio) / denom;
91 r.imag = (a.imag - a.real * ratio) / denom;
92 }
93 }
94 else {
95 /* divide tops and bottom by b.imag */
96 const double ratio = b.real / b.imag;
97 const double denom = b.real * ratio + b.imag;
98 assert(b.imag != 0.0);
99 r.real = (a.real * ratio + a.imag) / denom;
100 r.imag = (a.imag * ratio - a.real) / denom;
101 }
102 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000103}
104
Tim Peters0f336042001-03-18 08:21:57 +0000105Py_complex
106c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 Py_complex r;
109 double vabs,len,at,phase;
110 if (b.real == 0. && b.imag == 0.) {
111 r.real = 1.;
112 r.imag = 0.;
113 }
114 else if (a.real == 0. && a.imag == 0.) {
115 if (b.imag != 0. || b.real < 0.)
116 errno = EDOM;
117 r.real = 0.;
118 r.imag = 0.;
119 }
120 else {
121 vabs = hypot(a.real,a.imag);
122 len = pow(vabs,b.real);
123 at = atan2(a.imag, a.real);
124 phase = at*b.real;
125 if (b.imag != 0.0) {
126 len /= exp(at*b.imag);
127 phase += b.imag*log(vabs);
128 }
129 r.real = len*cos(phase);
130 r.imag = len*sin(phase);
131 }
132 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000133}
134
Tim Peters0f336042001-03-18 08:21:57 +0000135static Py_complex
136c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 Py_complex r, p;
139 long mask = 1;
140 r = c_1;
141 p = x;
142 while (mask > 0 && n >= mask) {
143 if (n & mask)
144 r = c_prod(r,p);
145 mask <<= 1;
146 p = c_prod(p,p);
147 }
148 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000149}
150
Tim Peters0f336042001-03-18 08:21:57 +0000151static Py_complex
152c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 if (n > 100 || n < -100) {
157 cn.real = (double) n;
158 cn.imag = 0.;
159 return c_pow(x,cn);
160 }
161 else if (n > 0)
162 return c_powu(x,n);
163 else
164 return c_quot(c_1,c_powu(x,-n));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000165
166}
167
Christian Heimes53876d92008-04-19 00:31:39 +0000168double
169c_abs(Py_complex z)
170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
172 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
175 /* C99 rules: if either the real or the imaginary part is an
176 infinity, return infinity, even if the other part is a
177 NaN. */
178 if (Py_IS_INFINITY(z.real)) {
179 result = fabs(z.real);
180 errno = 0;
181 return result;
182 }
183 if (Py_IS_INFINITY(z.imag)) {
184 result = fabs(z.imag);
185 errno = 0;
186 return result;
187 }
188 /* either the real or imaginary part is a NaN,
189 and neither is infinite. Result should be NaN. */
190 return Py_NAN;
191 }
192 result = hypot(z.real, z.imag);
193 if (!Py_IS_FINITE(result))
194 errno = ERANGE;
195 else
196 errno = 0;
197 return result;
Christian Heimes53876d92008-04-19 00:31:39 +0000198}
199
Tim Peters6d6c1a32001-08-02 04:15:00 +0000200static PyObject *
201complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 PyObject *op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 op = type->tp_alloc(type, 0);
206 if (op != NULL)
207 ((PyComplexObject *)op)->cval = cval;
208 return op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000209}
210
Guido van Rossumf9fca921996-01-12 00:47:05 +0000211PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000212PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000213{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200214 PyComplexObject *op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 /* Inline PyObject_New */
217 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
218 if (op == NULL)
219 return PyErr_NoMemory();
Christian Heimesd3afe782013-12-04 09:27:47 +0100220 (void)PyObject_INIT(op, &PyComplex_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 op->cval = cval;
222 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000223}
224
Tim Peters6d6c1a32001-08-02 04:15:00 +0000225static PyObject *
226complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_complex c;
229 c.real = real;
230 c.imag = imag;
231 return complex_subtype_from_c_complex(type, c);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000232}
233
Guido van Rossumf9fca921996-01-12 00:47:05 +0000234PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000235PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 Py_complex c;
238 c.real = real;
239 c.imag = imag;
240 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000241}
242
243double
Fred Drake4288c802000-07-09 04:36:04 +0000244PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (PyComplex_Check(op)) {
247 return ((PyComplexObject *)op)->cval.real;
248 }
249 else {
250 return PyFloat_AsDouble(op);
251 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000252}
253
254double
Fred Drake4288c802000-07-09 04:36:04 +0000255PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (PyComplex_Check(op)) {
258 return ((PyComplexObject *)op)->cval.imag;
259 }
260 else {
261 return 0.0;
262 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000263}
264
Benjamin Petersonaea44282010-01-04 01:10:28 +0000265static PyObject *
266try_complex_special_method(PyObject *op) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 PyObject *f;
Benjamin Petersonce798522012-01-22 11:24:29 -0500268 _Py_IDENTIFIER(__complex__);
Benjamin Petersonaea44282010-01-04 01:10:28 +0000269
Benjamin Petersonce798522012-01-22 11:24:29 -0500270 f = _PyObject_LookupSpecial(op, &PyId___complex__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (f) {
272 PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
273 Py_DECREF(f);
Mark Dickinsond20fb822012-11-14 17:08:31 +0000274 if (res != NULL && !PyComplex_Check(res)) {
275 PyErr_SetString(PyExc_TypeError,
276 "__complex__ should return a complex object");
277 Py_DECREF(res);
278 return NULL;
279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return res;
281 }
282 return NULL;
Benjamin Petersonaea44282010-01-04 01:10:28 +0000283}
284
Guido van Rossum9e720e31996-07-21 02:31:35 +0000285Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000286PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 Py_complex cv;
289 PyObject *newop = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 assert(op);
292 /* If op is already of type PyComplex_Type, return its value */
293 if (PyComplex_Check(op)) {
294 return ((PyComplexObject *)op)->cval;
295 }
296 /* If not, use op's __complex__ method, if it exists */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* return -1 on failure */
299 cv.real = -1.;
300 cv.imag = 0.;
301
302 newop = try_complex_special_method(op);
303
304 if (newop) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 cv = ((PyComplexObject *)newop)->cval;
306 Py_DECREF(newop);
307 return cv;
308 }
309 else if (PyErr_Occurred()) {
310 return cv;
311 }
312 /* If neither of the above works, interpret op as a float giving the
313 real part of the result, and fill in the imaginary part as 0. */
314 else {
315 /* PyFloat_AsDouble will return -1 on failure */
316 cv.real = PyFloat_AsDouble(op);
317 return cv;
318 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000319}
320
Guido van Rossumf9fca921996-01-12 00:47:05 +0000321static void
Fred Drake4288c802000-07-09 04:36:04 +0000322complex_dealloc(PyObject *op)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 op->ob_type->tp_free(op);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000325}
326
Eric Smith0923d1d2009-04-16 20:16:10 +0000327static PyObject *
Eric Smith70099a12010-12-04 13:27:34 +0000328complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000329{
Eric Smith70099a12010-12-04 13:27:34 +0000330 int precision = 0;
331 char format_code = 'r';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyObject *result = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 /* If these are non-NULL, they'll need to be freed. */
335 char *pre = NULL;
336 char *im = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 /* These do not need to be freed. re is either an alias
339 for pre or a pointer to a constant. lead and tail
340 are pointers to constants. */
341 char *re = NULL;
342 char *lead = "";
343 char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
Eric Smith70099a12010-12-04 13:27:34 +0000346 /* Real part is +0: just output the imaginary part and do not
347 include parens. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 re = "";
349 im = PyOS_double_to_string(v->cval.imag, format_code,
350 precision, 0, NULL);
351 if (!im) {
352 PyErr_NoMemory();
353 goto done;
354 }
355 } else {
Eric Smith70099a12010-12-04 13:27:34 +0000356 /* Format imaginary part with sign, real part without. Include
357 parens in the result. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 pre = PyOS_double_to_string(v->cval.real, format_code,
359 precision, 0, NULL);
360 if (!pre) {
361 PyErr_NoMemory();
362 goto done;
363 }
364 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 im = PyOS_double_to_string(v->cval.imag, format_code,
367 precision, Py_DTSF_SIGN, NULL);
368 if (!im) {
369 PyErr_NoMemory();
370 goto done;
371 }
372 lead = "(";
373 tail = ")";
374 }
Victor Stinner6ced7c42011-03-21 18:15:42 +0100375 result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000376 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 PyMem_Free(im);
378 PyMem_Free(pre);
Eric Smith0923d1d2009-04-16 20:16:10 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000381}
382
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000383static Py_hash_t
Fred Drake4288c802000-07-09 04:36:04 +0000384complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000385{
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000386 Py_uhash_t hashreal, hashimag, combined;
387 hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real);
388 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 return -1;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000390 hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag);
391 if (hashimag == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 return -1;
393 /* Note: if the imaginary part is 0, hashimag is 0 now,
394 * so the following returns hashreal unchanged. This is
395 * important because numbers of different types that
396 * compare equal must have the same hash value, so that
397 * hash(x + 0*j) must equal hash(x).
398 */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000399 combined = hashreal + _PyHASH_IMAG * hashimag;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000400 if (combined == (Py_uhash_t)-1)
401 combined = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000402 return (Py_hash_t)combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000403}
404
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000405/* This macro may return! */
406#define TO_COMPLEX(obj, c) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (PyComplex_Check(obj)) \
408 c = ((PyComplexObject *)(obj))->cval; \
409 else if (to_complex(&(obj), &(c)) < 0) \
410 return (obj)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000411
412static int
413to_complex(PyObject **pobj, Py_complex *pc)
414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 pc->real = pc->imag = 0.0;
418 if (PyLong_Check(obj)) {
419 pc->real = PyLong_AsDouble(obj);
420 if (pc->real == -1.0 && PyErr_Occurred()) {
421 *pobj = NULL;
422 return -1;
423 }
424 return 0;
425 }
426 if (PyFloat_Check(obj)) {
427 pc->real = PyFloat_AsDouble(obj);
428 return 0;
429 }
430 Py_INCREF(Py_NotImplemented);
431 *pobj = Py_NotImplemented;
432 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000433}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000435
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000437complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 Py_complex result;
440 Py_complex a, b;
441 TO_COMPLEX(v, a);
442 TO_COMPLEX(w, b);
443 PyFPE_START_PROTECT("complex_add", return 0)
444 result = c_sum(a, b);
445 PyFPE_END_PROTECT(result)
446 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000447}
448
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000450complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 Py_complex result;
453 Py_complex a, b;
454 TO_COMPLEX(v, a);
455 TO_COMPLEX(w, b);
456 PyFPE_START_PROTECT("complex_sub", return 0)
457 result = c_diff(a, b);
458 PyFPE_END_PROTECT(result)
459 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000460}
461
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000463complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_complex result;
466 Py_complex a, b;
467 TO_COMPLEX(v, a);
468 TO_COMPLEX(w, b);
469 PyFPE_START_PROTECT("complex_mul", return 0)
470 result = c_prod(a, b);
471 PyFPE_END_PROTECT(result)
472 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000473}
474
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000475static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000476complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Py_complex quot;
479 Py_complex a, b;
480 TO_COMPLEX(v, a);
481 TO_COMPLEX(w, b);
482 PyFPE_START_PROTECT("complex_div", return 0)
483 errno = 0;
484 quot = c_quot(a, b);
485 PyFPE_END_PROTECT(quot)
486 if (errno == EDOM) {
487 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
488 return NULL;
489 }
490 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000491}
492
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000494complex_remainder(PyObject *v, PyObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 PyErr_SetString(PyExc_TypeError,
497 "can't mod complex numbers.");
498 return NULL;
Guido van Rossumee09fc11996-09-11 13:55:55 +0000499}
500
Guido van Rossumee09fc11996-09-11 13:55:55 +0000501
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000503complex_divmod(PyObject *v, PyObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 PyErr_SetString(PyExc_TypeError,
506 "can't take floor or mod of complex number.");
507 return NULL;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000508}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000509
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000511complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 Py_complex p;
514 Py_complex exponent;
515 long int_exponent;
516 Py_complex a, b;
517 TO_COMPLEX(v, a);
518 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (z != Py_None) {
521 PyErr_SetString(PyExc_ValueError, "complex modulo");
522 return NULL;
523 }
524 PyFPE_START_PROTECT("complex_pow", return 0)
525 errno = 0;
526 exponent = b;
527 int_exponent = (long)exponent.real;
528 if (exponent.imag == 0. && exponent.real == int_exponent)
529 p = c_powi(a, int_exponent);
530 else
531 p = c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyFPE_END_PROTECT(p)
534 Py_ADJUST_ERANGE2(p.real, p.imag);
535 if (errno == EDOM) {
536 PyErr_SetString(PyExc_ZeroDivisionError,
537 "0.0 to a negative or complex power");
538 return NULL;
539 }
540 else if (errno == ERANGE) {
541 PyErr_SetString(PyExc_OverflowError,
542 "complex exponentiation");
543 return NULL;
544 }
545 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000546}
547
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000549complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyErr_SetString(PyExc_TypeError,
552 "can't take floor of complex number.");
553 return NULL;
Guido van Rossum4668b002001-08-08 05:00:18 +0000554}
555
556static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000557complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 Py_complex neg;
560 neg.real = -v->cval.real;
561 neg.imag = -v->cval.imag;
562 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000563}
564
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000566complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 if (PyComplex_CheckExact(v)) {
569 Py_INCREF(v);
570 return (PyObject *)v;
571 }
572 else
573 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000574}
575
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000576static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000577complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyFPE_START_PROTECT("complex_abs", return 0)
582 result = c_abs(v->cval);
583 PyFPE_END_PROTECT(result)
Christian Heimes53876d92008-04-19 00:31:39 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (errno == ERANGE) {
586 PyErr_SetString(PyExc_OverflowError,
587 "absolute value too large");
588 return NULL;
589 }
590 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000591}
592
593static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000594complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000597}
598
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000599static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000600complex_richcompare(PyObject *v, PyObject *w, int op)
601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000603 Py_complex i;
604 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000607 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 }
Guido van Rossum22056422001-09-24 17:52:04 +0000609
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000610 assert(PyComplex_Check(v));
611 TO_COMPLEX(v, i);
612
613 if (PyLong_Check(w)) {
614 /* Check for 0.0 imaginary part first to avoid the rich
615 * comparison when possible.
616 */
617 if (i.imag == 0.0) {
618 PyObject *j, *sub_res;
619 j = PyFloat_FromDouble(i.real);
620 if (j == NULL)
621 return NULL;
622
623 sub_res = PyObject_RichCompare(j, w, op);
624 Py_DECREF(j);
625 return sub_res;
626 }
627 else {
628 equal = 0;
629 }
630 }
631 else if (PyFloat_Check(w)) {
632 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
633 }
634 else if (PyComplex_Check(w)) {
635 Py_complex j;
636
637 TO_COMPLEX(w, j);
638 equal = (i.real == j.real && i.imag == j.imag);
639 }
640 else {
641 goto Unimplemented;
642 }
643
644 if (equal == (op == Py_EQ))
645 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000647 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 Py_INCREF(res);
650 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000651
652Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500653 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000654}
655
656static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000657complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 PyErr_SetString(PyExc_TypeError,
660 "can't convert complex to int");
661 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000662}
663
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000664static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000665complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyErr_SetString(PyExc_TypeError,
668 "can't convert complex to float");
669 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000670}
671
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000672static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000673complex_conjugate(PyObject *self)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 Py_complex c;
676 c = ((PyComplexObject *)self)->cval;
677 c.imag = -c.imag;
678 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000679}
680
Guido van Rossum46334cd2007-08-01 17:43:15 +0000681PyDoc_STRVAR(complex_conjugate_doc,
682"complex.conjugate() -> complex\n"
683"\n"
Ezio Melotti488d2442013-10-06 00:39:18 +0300684"Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
Guido van Rossum46334cd2007-08-01 17:43:15 +0000685
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000686static PyObject *
687complex_getnewargs(PyComplexObject *v)
688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 Py_complex c = v->cval;
690 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000691}
692
Eric Smith58a42242009-04-30 01:00:33 +0000693PyDoc_STRVAR(complex__format__doc,
694"complex.__format__() -> str\n"
695"\n"
Ezio Melotti488d2442013-10-06 00:39:18 +0300696"Convert to a string according to format_spec.");
Eric Smith58a42242009-04-30 01:00:33 +0000697
698static PyObject *
699complex__format__(PyObject* self, PyObject* args)
700{
701 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200702 _PyUnicodeWriter writer;
703 int ret;
Eric Smith58a42242009-04-30 01:00:33 +0000704
705 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
Victor Stinnerd3f08822012-05-29 12:57:52 +0200706 return NULL;
707
Victor Stinner8f674cc2013-04-17 23:02:17 +0200708 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +0200709 ret = _PyComplex_FormatAdvancedWriter(
710 &writer,
711 self,
712 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
713 if (ret == -1) {
714 _PyUnicodeWriter_Dealloc(&writer);
715 return NULL;
716 }
717 return _PyUnicodeWriter_Finish(&writer);
Eric Smith58a42242009-04-30 01:00:33 +0000718}
719
Christian Heimes53876d92008-04-19 00:31:39 +0000720#if 0
721static PyObject *
722complex_is_finite(PyObject *self)
723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 Py_complex c;
725 c = ((PyComplexObject *)self)->cval;
726 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
727 Py_IS_FINITE(c.imag)));
Christian Heimes53876d92008-04-19 00:31:39 +0000728}
729
730PyDoc_STRVAR(complex_is_finite_doc,
731"complex.is_finite() -> bool\n"
732"\n"
733"Returns True if the real and the imaginary part is finite.");
734#endif
735
Guido van Rossumf9fca921996-01-12 00:47:05 +0000736static PyMethodDef complex_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
738 complex_conjugate_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000739#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
741 complex_is_finite_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000742#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
744 {"__format__", (PyCFunction)complex__format__,
745 METH_VARARGS, complex__format__doc},
746 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000747};
748
Guido van Rossum6f799372001-09-20 20:46:19 +0000749static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
751 "the real part of a complex number"},
752 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
753 "the imaginary part of a complex number"},
754 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000756
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758complex_subtype_from_string(PyTypeObject *type, PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 const char *s, *start;
761 char *end;
762 double x=0.0, y=0.0, z;
763 int got_bracket=0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000764 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200768 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000770 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200771 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000772 if (s == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 }
775 else if (PyObject_AsCharBuffer(v, &s, &len)) {
Ezio Melottia5b95992013-11-07 19:18:34 +0200776 PyErr_Format(PyExc_TypeError,
777 "complex() argument must be a string or a number, not '%.200s'",
778 Py_TYPE(v)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 return NULL;
780 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* position on first nonblank */
783 start = s;
784 while (Py_ISSPACE(*s))
785 s++;
786 if (*s == '(') {
787 /* Skip over possible bracket from repr(). */
788 got_bracket = 1;
789 s++;
790 while (Py_ISSPACE(*s))
791 s++;
792 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 <float> - real part only
797 <float>j - imaginary part only
798 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 where <float> represents any numeric string that's accepted by the
801 float constructor (including 'nan', 'inf', 'infinity', etc.), and
802 <signed-float> is any string of the form <float> whose first
803 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 <float><sign>j
808 <sign>j
809 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 are also accepted, though support for these forms may be removed from
812 a future version of Python.
813 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 /* first look for forms starting with <float> */
816 z = PyOS_string_to_double(s, &end, NULL);
817 if (z == -1.0 && PyErr_Occurred()) {
818 if (PyErr_ExceptionMatches(PyExc_ValueError))
819 PyErr_Clear();
820 else
821 goto error;
822 }
823 if (end != s) {
824 /* all 4 forms starting with <float> land here */
825 s = end;
826 if (*s == '+' || *s == '-') {
827 /* <float><signed-float>j | <float><sign>j */
828 x = z;
829 y = PyOS_string_to_double(s, &end, NULL);
830 if (y == -1.0 && PyErr_Occurred()) {
831 if (PyErr_ExceptionMatches(PyExc_ValueError))
832 PyErr_Clear();
833 else
834 goto error;
835 }
836 if (end != s)
837 /* <float><signed-float>j */
838 s = end;
839 else {
840 /* <float><sign>j */
841 y = *s == '+' ? 1.0 : -1.0;
842 s++;
843 }
844 if (!(*s == 'j' || *s == 'J'))
845 goto parse_error;
846 s++;
847 }
848 else if (*s == 'j' || *s == 'J') {
849 /* <float>j */
850 s++;
851 y = z;
852 }
853 else
854 /* <float> */
855 x = z;
856 }
857 else {
858 /* not starting with <float>; must be <sign>j or j */
859 if (*s == '+' || *s == '-') {
860 /* <sign>j */
861 y = *s == '+' ? 1.0 : -1.0;
862 s++;
863 }
864 else
865 /* j */
866 y = 1.0;
867 if (!(*s == 'j' || *s == 'J'))
868 goto parse_error;
869 s++;
870 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 /* trailing whitespace and closing bracket */
873 while (Py_ISSPACE(*s))
874 s++;
875 if (got_bracket) {
876 /* if there was an opening parenthesis, then the corresponding
877 closing parenthesis should be right here */
878 if (*s != ')')
879 goto parse_error;
880 s++;
881 while (Py_ISSPACE(*s))
882 s++;
883 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* we should now be at the end of the string */
886 if (s-start != len)
887 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000888
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000889 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 return complex_subtype_from_doubles(type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000891
Mark Dickinson6649fa42009-04-24 13:25:20 +0000892 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 PyErr_SetString(PyExc_ValueError,
894 "complex() arg is a malformed string");
Mark Dickinson1daebdf2009-10-26 22:05:06 +0000895 error:
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000896 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000898}
899
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900static PyObject *
901complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 PyObject *r, *i, *tmp;
904 PyNumberMethods *nbr, *nbi = NULL;
905 Py_complex cr, ci;
906 int own_r = 0;
907 int cr_is_complex = 0;
908 int ci_is_complex = 0;
909 static char *kwlist[] = {"real", "imag", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 r = Py_False;
912 i = NULL;
913 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
914 &r, &i))
915 return NULL;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Special-case for a single argument when type(arg) is complex. */
918 if (PyComplex_CheckExact(r) && i == NULL &&
919 type == &PyComplex_Type) {
920 /* Note that we can't know whether it's safe to return
921 a complex *subclass* instance as-is, hence the restriction
922 to exact complexes here. If either the input or the
923 output is a complex subclass, it will be handled below
924 as a non-orthogonal vector. */
925 Py_INCREF(r);
926 return r;
927 }
928 if (PyUnicode_Check(r)) {
929 if (i != NULL) {
930 PyErr_SetString(PyExc_TypeError,
931 "complex() can't take second arg"
932 " if first is a string");
933 return NULL;
934 }
935 return complex_subtype_from_string(type, r);
936 }
937 if (i != NULL && PyUnicode_Check(i)) {
938 PyErr_SetString(PyExc_TypeError,
939 "complex() second arg can't be a string");
940 return NULL;
941 }
Tim Peters2400fa42001-09-12 19:12:49 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 tmp = try_complex_special_method(r);
944 if (tmp) {
945 r = tmp;
946 own_r = 1;
947 }
948 else if (PyErr_Occurred()) {
949 return NULL;
950 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 nbr = r->ob_type->tp_as_number;
953 if (i != NULL)
954 nbi = i->ob_type->tp_as_number;
955 if (nbr == NULL || nbr->nb_float == NULL ||
956 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
Ezio Melottia5b95992013-11-07 19:18:34 +0200957 PyErr_Format(PyExc_TypeError,
958 "complex() argument must be a string or a number, not '%.200s'",
959 Py_TYPE(r)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (own_r) {
961 Py_DECREF(r);
962 }
963 return NULL;
964 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* If we get this far, then the "real" and "imag" parts should
967 both be treated as numbers, and the constructor should return a
968 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 Note that we do NOT assume the input to already be in canonical
971 form; the "real" and "imag" parts might themselves be complex
972 numbers, which slightly complicates the code below. */
973 if (PyComplex_Check(r)) {
974 /* Note that if r is of a complex subtype, we're only
975 retaining its real & imag parts here, and the return
976 value is (properly) of the builtin complex type. */
977 cr = ((PyComplexObject*)r)->cval;
978 cr_is_complex = 1;
979 if (own_r) {
980 Py_DECREF(r);
981 }
982 }
983 else {
984 /* The "real" part really is entirely real, and contributes
985 nothing in the imaginary direction.
986 Just treat it as a double. */
987 tmp = PyNumber_Float(r);
988 if (own_r) {
989 /* r was a newly created complex number, rather
990 than the original "real" argument. */
991 Py_DECREF(r);
992 }
993 if (tmp == NULL)
994 return NULL;
995 if (!PyFloat_Check(tmp)) {
996 PyErr_SetString(PyExc_TypeError,
997 "float(r) didn't return a float");
998 Py_DECREF(tmp);
999 return NULL;
1000 }
1001 cr.real = PyFloat_AsDouble(tmp);
1002 cr.imag = 0.0; /* Shut up compiler warning */
1003 Py_DECREF(tmp);
1004 }
1005 if (i == NULL) {
1006 ci.real = 0.0;
1007 }
1008 else if (PyComplex_Check(i)) {
1009 ci = ((PyComplexObject*)i)->cval;
1010 ci_is_complex = 1;
1011 } else {
1012 /* The "imag" part really is entirely imaginary, and
1013 contributes nothing in the real direction.
1014 Just treat it as a double. */
1015 tmp = (*nbi->nb_float)(i);
1016 if (tmp == NULL)
1017 return NULL;
1018 ci.real = PyFloat_AsDouble(tmp);
1019 Py_DECREF(tmp);
1020 }
1021 /* If the input was in canonical form, then the "real" and "imag"
1022 parts are real numbers, so that ci.imag and cr.imag are zero.
1023 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (ci_is_complex) {
1026 cr.real -= ci.imag;
1027 }
1028 if (cr_is_complex) {
1029 ci.real += cr.imag;
1030 }
1031 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001032}
1033
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001034PyDoc_STRVAR(complex_doc,
Tim Peters2400fa42001-09-12 19:12:49 +00001035"complex(real[, imag]) -> complex number\n"
1036"\n"
1037"Create a complex number from a real part and an optional imaginary part.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001038"This is equivalent to (real + imag*1j) where imag defaults to 0.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001039
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001040static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 (binaryfunc)complex_add, /* nb_add */
1042 (binaryfunc)complex_sub, /* nb_subtract */
1043 (binaryfunc)complex_mul, /* nb_multiply */
1044 (binaryfunc)complex_remainder, /* nb_remainder */
1045 (binaryfunc)complex_divmod, /* nb_divmod */
1046 (ternaryfunc)complex_pow, /* nb_power */
1047 (unaryfunc)complex_neg, /* nb_negative */
1048 (unaryfunc)complex_pos, /* nb_positive */
1049 (unaryfunc)complex_abs, /* nb_absolute */
1050 (inquiry)complex_bool, /* nb_bool */
1051 0, /* nb_invert */
1052 0, /* nb_lshift */
1053 0, /* nb_rshift */
1054 0, /* nb_and */
1055 0, /* nb_xor */
1056 0, /* nb_or */
1057 complex_int, /* nb_int */
1058 0, /* nb_reserved */
1059 complex_float, /* nb_float */
1060 0, /* nb_inplace_add */
1061 0, /* nb_inplace_subtract */
1062 0, /* nb_inplace_multiply*/
1063 0, /* nb_inplace_remainder */
1064 0, /* nb_inplace_power */
1065 0, /* nb_inplace_lshift */
1066 0, /* nb_inplace_rshift */
1067 0, /* nb_inplace_and */
1068 0, /* nb_inplace_xor */
1069 0, /* nb_inplace_or */
1070 (binaryfunc)complex_int_div, /* nb_floor_divide */
1071 (binaryfunc)complex_div, /* nb_true_divide */
1072 0, /* nb_inplace_floor_divide */
1073 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001074};
1075
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001076PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1078 "complex",
1079 sizeof(PyComplexObject),
1080 0,
1081 complex_dealloc, /* tp_dealloc */
1082 0, /* tp_print */
1083 0, /* tp_getattr */
1084 0, /* tp_setattr */
1085 0, /* tp_reserved */
1086 (reprfunc)complex_repr, /* tp_repr */
1087 &complex_as_number, /* tp_as_number */
1088 0, /* tp_as_sequence */
1089 0, /* tp_as_mapping */
1090 (hashfunc)complex_hash, /* tp_hash */
1091 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001092 (reprfunc)complex_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyObject_GenericGetAttr, /* tp_getattro */
1094 0, /* tp_setattro */
1095 0, /* tp_as_buffer */
1096 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1097 complex_doc, /* tp_doc */
1098 0, /* tp_traverse */
1099 0, /* tp_clear */
1100 complex_richcompare, /* tp_richcompare */
1101 0, /* tp_weaklistoffset */
1102 0, /* tp_iter */
1103 0, /* tp_iternext */
1104 complex_methods, /* tp_methods */
1105 complex_members, /* tp_members */
1106 0, /* tp_getset */
1107 0, /* tp_base */
1108 0, /* tp_dict */
1109 0, /* tp_descr_get */
1110 0, /* tp_descr_set */
1111 0, /* tp_dictoffset */
1112 0, /* tp_init */
1113 PyType_GenericAlloc, /* tp_alloc */
1114 complex_new, /* tp_new */
1115 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001116};