blob: e247ba9ba84a0e893911808eeef448a9b75f8240 [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 Pitrouf95a1b32010-05-09 15:52:27 +0000214 register 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();
220 PyObject_INIT(op, &PyComplex_Type);
221 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;
268 static PyObject *complexstr;
Benjamin Petersonaea44282010-01-04 01:10:28 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 f = _PyObject_LookupSpecial(op, "__complex__", &complexstr);
271 if (f) {
272 PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
273 Py_DECREF(f);
274 return res;
275 }
276 return NULL;
Benjamin Petersonaea44282010-01-04 01:10:28 +0000277}
278
Guido van Rossum9e720e31996-07-21 02:31:35 +0000279Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000280PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Py_complex cv;
283 PyObject *newop = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 assert(op);
286 /* If op is already of type PyComplex_Type, return its value */
287 if (PyComplex_Check(op)) {
288 return ((PyComplexObject *)op)->cval;
289 }
290 /* If not, use op's __complex__ method, if it exists */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 /* return -1 on failure */
293 cv.real = -1.;
294 cv.imag = 0.;
295
296 newop = try_complex_special_method(op);
297
298 if (newop) {
299 if (!PyComplex_Check(newop)) {
300 PyErr_SetString(PyExc_TypeError,
301 "__complex__ should return a complex object");
302 Py_DECREF(newop);
303 return cv;
304 }
305 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;
333 Py_ssize_t len;
Eric Smith0923d1d2009-04-16 20:16:10 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* If these are non-NULL, they'll need to be freed. */
336 char *pre = NULL;
337 char *im = NULL;
338 char *buf = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 /* These do not need to be freed. re is either an alias
341 for pre or a pointer to a constant. lead and tail
342 are pointers to constants. */
343 char *re = NULL;
344 char *lead = "";
345 char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
Eric Smith70099a12010-12-04 13:27:34 +0000348 /* Real part is +0: just output the imaginary part and do not
349 include parens. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 re = "";
351 im = PyOS_double_to_string(v->cval.imag, format_code,
352 precision, 0, NULL);
353 if (!im) {
354 PyErr_NoMemory();
355 goto done;
356 }
357 } else {
Eric Smith70099a12010-12-04 13:27:34 +0000358 /* Format imaginary part with sign, real part without. Include
359 parens in the result. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 pre = PyOS_double_to_string(v->cval.real, format_code,
361 precision, 0, NULL);
362 if (!pre) {
363 PyErr_NoMemory();
364 goto done;
365 }
366 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 im = PyOS_double_to_string(v->cval.imag, format_code,
369 precision, Py_DTSF_SIGN, NULL);
370 if (!im) {
371 PyErr_NoMemory();
372 goto done;
373 }
374 lead = "(";
375 tail = ")";
376 }
377 /* Alloc the final buffer. Add one for the "j" in the format string,
Eric Smith70099a12010-12-04 13:27:34 +0000378 and one for the trailing zero byte. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
380 buf = PyMem_Malloc(len);
381 if (!buf) {
382 PyErr_NoMemory();
383 goto done;
384 }
385 PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
386 result = PyUnicode_FromString(buf);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000387 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 PyMem_Free(im);
389 PyMem_Free(pre);
390 PyMem_Free(buf);
Eric Smith0923d1d2009-04-16 20:16:10 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000393}
394
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000395static Py_hash_t
Fred Drake4288c802000-07-09 04:36:04 +0000396complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000397{
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000398 Py_uhash_t hashreal, hashimag, combined;
399 hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real);
400 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 return -1;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000402 hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag);
403 if (hashimag == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 return -1;
405 /* Note: if the imaginary part is 0, hashimag is 0 now,
406 * so the following returns hashreal unchanged. This is
407 * important because numbers of different types that
408 * compare equal must have the same hash value, so that
409 * hash(x + 0*j) must equal hash(x).
410 */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000411 combined = hashreal + _PyHASH_IMAG * hashimag;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000412 if (combined == (Py_uhash_t)-1)
413 combined = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000414 return (Py_hash_t)combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000415}
416
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000417/* This macro may return! */
418#define TO_COMPLEX(obj, c) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (PyComplex_Check(obj)) \
420 c = ((PyComplexObject *)(obj))->cval; \
421 else if (to_complex(&(obj), &(c)) < 0) \
422 return (obj)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000423
424static int
425to_complex(PyObject **pobj, Py_complex *pc)
426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 pc->real = pc->imag = 0.0;
430 if (PyLong_Check(obj)) {
431 pc->real = PyLong_AsDouble(obj);
432 if (pc->real == -1.0 && PyErr_Occurred()) {
433 *pobj = NULL;
434 return -1;
435 }
436 return 0;
437 }
438 if (PyFloat_Check(obj)) {
439 pc->real = PyFloat_AsDouble(obj);
440 return 0;
441 }
442 Py_INCREF(Py_NotImplemented);
443 *pobj = Py_NotImplemented;
444 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000445}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000447
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000449complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 Py_complex result;
452 Py_complex a, b;
453 TO_COMPLEX(v, a);
454 TO_COMPLEX(w, b);
455 PyFPE_START_PROTECT("complex_add", return 0)
456 result = c_sum(a, b);
457 PyFPE_END_PROTECT(result)
458 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000459}
460
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000462complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 Py_complex result;
465 Py_complex a, b;
466 TO_COMPLEX(v, a);
467 TO_COMPLEX(w, b);
468 PyFPE_START_PROTECT("complex_sub", return 0)
469 result = c_diff(a, b);
470 PyFPE_END_PROTECT(result)
471 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000472}
473
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000475complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 Py_complex result;
478 Py_complex a, b;
479 TO_COMPLEX(v, a);
480 TO_COMPLEX(w, b);
481 PyFPE_START_PROTECT("complex_mul", return 0)
482 result = c_prod(a, b);
483 PyFPE_END_PROTECT(result)
484 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000485}
486
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000488complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 Py_complex quot;
491 Py_complex a, b;
492 TO_COMPLEX(v, a);
493 TO_COMPLEX(w, b);
494 PyFPE_START_PROTECT("complex_div", return 0)
495 errno = 0;
496 quot = c_quot(a, b);
497 PyFPE_END_PROTECT(quot)
498 if (errno == EDOM) {
499 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
500 return NULL;
501 }
502 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000503}
504
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000506complex_remainder(PyObject *v, PyObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyErr_SetString(PyExc_TypeError,
509 "can't mod complex numbers.");
510 return NULL;
Guido van Rossumee09fc11996-09-11 13:55:55 +0000511}
512
Guido van Rossumee09fc11996-09-11 13:55:55 +0000513
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000515complex_divmod(PyObject *v, PyObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyErr_SetString(PyExc_TypeError,
518 "can't take floor or mod of complex number.");
519 return NULL;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000520}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000521
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000523complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 Py_complex p;
526 Py_complex exponent;
527 long int_exponent;
528 Py_complex a, b;
529 TO_COMPLEX(v, a);
530 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (z != Py_None) {
533 PyErr_SetString(PyExc_ValueError, "complex modulo");
534 return NULL;
535 }
536 PyFPE_START_PROTECT("complex_pow", return 0)
537 errno = 0;
538 exponent = b;
539 int_exponent = (long)exponent.real;
540 if (exponent.imag == 0. && exponent.real == int_exponent)
541 p = c_powi(a, int_exponent);
542 else
543 p = c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 PyFPE_END_PROTECT(p)
546 Py_ADJUST_ERANGE2(p.real, p.imag);
547 if (errno == EDOM) {
548 PyErr_SetString(PyExc_ZeroDivisionError,
549 "0.0 to a negative or complex power");
550 return NULL;
551 }
552 else if (errno == ERANGE) {
553 PyErr_SetString(PyExc_OverflowError,
554 "complex exponentiation");
555 return NULL;
556 }
557 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000558}
559
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000561complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PyErr_SetString(PyExc_TypeError,
564 "can't take floor of complex number.");
565 return NULL;
Guido van Rossum4668b002001-08-08 05:00:18 +0000566}
567
568static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000569complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 Py_complex neg;
572 neg.real = -v->cval.real;
573 neg.imag = -v->cval.imag;
574 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000575}
576
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000578complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (PyComplex_CheckExact(v)) {
581 Py_INCREF(v);
582 return (PyObject *)v;
583 }
584 else
585 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000586}
587
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000588static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000589complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 PyFPE_START_PROTECT("complex_abs", return 0)
594 result = c_abs(v->cval);
595 PyFPE_END_PROTECT(result)
Christian Heimes53876d92008-04-19 00:31:39 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (errno == ERANGE) {
598 PyErr_SetString(PyExc_OverflowError,
599 "absolute value too large");
600 return NULL;
601 }
602 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000603}
604
605static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000606complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000609}
610
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000612complex_richcompare(PyObject *v, PyObject *w, int op)
613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000615 Py_complex i;
616 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000619 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 }
Guido van Rossum22056422001-09-24 17:52:04 +0000621
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000622 assert(PyComplex_Check(v));
623 TO_COMPLEX(v, i);
624
625 if (PyLong_Check(w)) {
626 /* Check for 0.0 imaginary part first to avoid the rich
627 * comparison when possible.
628 */
629 if (i.imag == 0.0) {
630 PyObject *j, *sub_res;
631 j = PyFloat_FromDouble(i.real);
632 if (j == NULL)
633 return NULL;
634
635 sub_res = PyObject_RichCompare(j, w, op);
636 Py_DECREF(j);
637 return sub_res;
638 }
639 else {
640 equal = 0;
641 }
642 }
643 else if (PyFloat_Check(w)) {
644 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
645 }
646 else if (PyComplex_Check(w)) {
647 Py_complex j;
648
649 TO_COMPLEX(w, j);
650 equal = (i.real == j.real && i.imag == j.imag);
651 }
652 else {
653 goto Unimplemented;
654 }
655
656 if (equal == (op == Py_EQ))
657 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000659 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 Py_INCREF(res);
662 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000663
664Unimplemented:
665 Py_INCREF(Py_NotImplemented);
666 return Py_NotImplemented;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000667}
668
669static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000670complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyErr_SetString(PyExc_TypeError,
673 "can't convert complex to int");
674 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000675}
676
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000678complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 PyErr_SetString(PyExc_TypeError,
681 "can't convert complex to float");
682 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000683}
684
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000686complex_conjugate(PyObject *self)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 Py_complex c;
689 c = ((PyComplexObject *)self)->cval;
690 c.imag = -c.imag;
691 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000692}
693
Guido van Rossum46334cd2007-08-01 17:43:15 +0000694PyDoc_STRVAR(complex_conjugate_doc,
695"complex.conjugate() -> complex\n"
696"\n"
697"Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
698
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000699static PyObject *
700complex_getnewargs(PyComplexObject *v)
701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 Py_complex c = v->cval;
703 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000704}
705
Eric Smith58a42242009-04-30 01:00:33 +0000706PyDoc_STRVAR(complex__format__doc,
707"complex.__format__() -> str\n"
708"\n"
709"Converts to a string according to format_spec.");
710
711static PyObject *
712complex__format__(PyObject* self, PyObject* args)
713{
714 PyObject *format_spec;
715
716 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return NULL;
Eric Smith58a42242009-04-30 01:00:33 +0000718 return _PyComplex_FormatAdvanced(self,
719 PyUnicode_AS_UNICODE(format_spec),
720 PyUnicode_GET_SIZE(format_spec));
721}
722
Christian Heimes53876d92008-04-19 00:31:39 +0000723#if 0
724static PyObject *
725complex_is_finite(PyObject *self)
726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 Py_complex c;
728 c = ((PyComplexObject *)self)->cval;
729 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
730 Py_IS_FINITE(c.imag)));
Christian Heimes53876d92008-04-19 00:31:39 +0000731}
732
733PyDoc_STRVAR(complex_is_finite_doc,
734"complex.is_finite() -> bool\n"
735"\n"
736"Returns True if the real and the imaginary part is finite.");
737#endif
738
Guido van Rossumf9fca921996-01-12 00:47:05 +0000739static PyMethodDef complex_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
741 complex_conjugate_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000742#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
744 complex_is_finite_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000745#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
747 {"__format__", (PyCFunction)complex__format__,
748 METH_VARARGS, complex__format__doc},
749 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000750};
751
Guido van Rossum6f799372001-09-20 20:46:19 +0000752static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
754 "the real part of a complex number"},
755 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
756 "the imaginary part of a complex number"},
757 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000759
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761complex_subtype_from_string(PyTypeObject *type, PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 const char *s, *start;
764 char *end;
765 double x=0.0, y=0.0, z;
766 int got_bracket=0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000767 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (PyUnicode_Check(v)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000771 Py_ssize_t i, buflen = PyUnicode_GET_SIZE(v);
772 Py_UNICODE *bufptr;
773 s_buffer = PyUnicode_TransformDecimalToASCII(
774 PyUnicode_AS_UNICODE(v), buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000776 return NULL;
777 /* Replace non-ASCII whitespace with ' ' */
778 bufptr = PyUnicode_AS_UNICODE(s_buffer);
779 for (i = 0; i < buflen; i++) {
780 Py_UNICODE ch = bufptr[i];
781 if (ch > 127 && Py_UNICODE_ISSPACE(ch))
782 bufptr[i] = ' ';
783 }
784 s = _PyUnicode_AsStringAndSize(s_buffer, &len);
785 if (s == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 }
788 else if (PyObject_AsCharBuffer(v, &s, &len)) {
789 PyErr_SetString(PyExc_TypeError,
Victor Stinnerf9613772010-12-03 16:51:33 +0000790 "complex() argument must be a string or a number");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return NULL;
792 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 /* position on first nonblank */
795 start = s;
796 while (Py_ISSPACE(*s))
797 s++;
798 if (*s == '(') {
799 /* Skip over possible bracket from repr(). */
800 got_bracket = 1;
801 s++;
802 while (Py_ISSPACE(*s))
803 s++;
804 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 <float> - real part only
809 <float>j - imaginary part only
810 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 where <float> represents any numeric string that's accepted by the
813 float constructor (including 'nan', 'inf', 'infinity', etc.), and
814 <signed-float> is any string of the form <float> whose first
815 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 <float><sign>j
820 <sign>j
821 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 are also accepted, though support for these forms may be removed from
824 a future version of Python.
825 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 /* first look for forms starting with <float> */
828 z = PyOS_string_to_double(s, &end, NULL);
829 if (z == -1.0 && PyErr_Occurred()) {
830 if (PyErr_ExceptionMatches(PyExc_ValueError))
831 PyErr_Clear();
832 else
833 goto error;
834 }
835 if (end != s) {
836 /* all 4 forms starting with <float> land here */
837 s = end;
838 if (*s == '+' || *s == '-') {
839 /* <float><signed-float>j | <float><sign>j */
840 x = z;
841 y = PyOS_string_to_double(s, &end, NULL);
842 if (y == -1.0 && PyErr_Occurred()) {
843 if (PyErr_ExceptionMatches(PyExc_ValueError))
844 PyErr_Clear();
845 else
846 goto error;
847 }
848 if (end != s)
849 /* <float><signed-float>j */
850 s = end;
851 else {
852 /* <float><sign>j */
853 y = *s == '+' ? 1.0 : -1.0;
854 s++;
855 }
856 if (!(*s == 'j' || *s == 'J'))
857 goto parse_error;
858 s++;
859 }
860 else if (*s == 'j' || *s == 'J') {
861 /* <float>j */
862 s++;
863 y = z;
864 }
865 else
866 /* <float> */
867 x = z;
868 }
869 else {
870 /* not starting with <float>; must be <sign>j or j */
871 if (*s == '+' || *s == '-') {
872 /* <sign>j */
873 y = *s == '+' ? 1.0 : -1.0;
874 s++;
875 }
876 else
877 /* j */
878 y = 1.0;
879 if (!(*s == 'j' || *s == 'J'))
880 goto parse_error;
881 s++;
882 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 /* trailing whitespace and closing bracket */
885 while (Py_ISSPACE(*s))
886 s++;
887 if (got_bracket) {
888 /* if there was an opening parenthesis, then the corresponding
889 closing parenthesis should be right here */
890 if (*s != ')')
891 goto parse_error;
892 s++;
893 while (Py_ISSPACE(*s))
894 s++;
895 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* we should now be at the end of the string */
898 if (s-start != len)
899 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000900
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000901 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 return complex_subtype_from_doubles(type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000903
Mark Dickinson6649fa42009-04-24 13:25:20 +0000904 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 PyErr_SetString(PyExc_ValueError,
906 "complex() arg is a malformed string");
Mark Dickinson1daebdf2009-10-26 22:05:06 +0000907 error:
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000908 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000910}
911
Tim Peters6d6c1a32001-08-02 04:15:00 +0000912static PyObject *
913complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 PyObject *r, *i, *tmp;
916 PyNumberMethods *nbr, *nbi = NULL;
917 Py_complex cr, ci;
918 int own_r = 0;
919 int cr_is_complex = 0;
920 int ci_is_complex = 0;
921 static char *kwlist[] = {"real", "imag", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 r = Py_False;
924 i = NULL;
925 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
926 &r, &i))
927 return NULL;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Special-case for a single argument when type(arg) is complex. */
930 if (PyComplex_CheckExact(r) && i == NULL &&
931 type == &PyComplex_Type) {
932 /* Note that we can't know whether it's safe to return
933 a complex *subclass* instance as-is, hence the restriction
934 to exact complexes here. If either the input or the
935 output is a complex subclass, it will be handled below
936 as a non-orthogonal vector. */
937 Py_INCREF(r);
938 return r;
939 }
940 if (PyUnicode_Check(r)) {
941 if (i != NULL) {
942 PyErr_SetString(PyExc_TypeError,
943 "complex() can't take second arg"
944 " if first is a string");
945 return NULL;
946 }
947 return complex_subtype_from_string(type, r);
948 }
949 if (i != NULL && PyUnicode_Check(i)) {
950 PyErr_SetString(PyExc_TypeError,
951 "complex() second arg can't be a string");
952 return NULL;
953 }
Tim Peters2400fa42001-09-12 19:12:49 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 tmp = try_complex_special_method(r);
956 if (tmp) {
957 r = tmp;
958 own_r = 1;
959 }
960 else if (PyErr_Occurred()) {
961 return NULL;
962 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 nbr = r->ob_type->tp_as_number;
965 if (i != NULL)
966 nbi = i->ob_type->tp_as_number;
967 if (nbr == NULL || nbr->nb_float == NULL ||
968 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
969 PyErr_SetString(PyExc_TypeError,
970 "complex() argument must be a string or a number");
971 if (own_r) {
972 Py_DECREF(r);
973 }
974 return NULL;
975 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 /* If we get this far, then the "real" and "imag" parts should
978 both be treated as numbers, and the constructor should return a
979 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 Note that we do NOT assume the input to already be in canonical
982 form; the "real" and "imag" parts might themselves be complex
983 numbers, which slightly complicates the code below. */
984 if (PyComplex_Check(r)) {
985 /* Note that if r is of a complex subtype, we're only
986 retaining its real & imag parts here, and the return
987 value is (properly) of the builtin complex type. */
988 cr = ((PyComplexObject*)r)->cval;
989 cr_is_complex = 1;
990 if (own_r) {
991 Py_DECREF(r);
992 }
993 }
994 else {
995 /* The "real" part really is entirely real, and contributes
996 nothing in the imaginary direction.
997 Just treat it as a double. */
998 tmp = PyNumber_Float(r);
999 if (own_r) {
1000 /* r was a newly created complex number, rather
1001 than the original "real" argument. */
1002 Py_DECREF(r);
1003 }
1004 if (tmp == NULL)
1005 return NULL;
1006 if (!PyFloat_Check(tmp)) {
1007 PyErr_SetString(PyExc_TypeError,
1008 "float(r) didn't return a float");
1009 Py_DECREF(tmp);
1010 return NULL;
1011 }
1012 cr.real = PyFloat_AsDouble(tmp);
1013 cr.imag = 0.0; /* Shut up compiler warning */
1014 Py_DECREF(tmp);
1015 }
1016 if (i == NULL) {
1017 ci.real = 0.0;
1018 }
1019 else if (PyComplex_Check(i)) {
1020 ci = ((PyComplexObject*)i)->cval;
1021 ci_is_complex = 1;
1022 } else {
1023 /* The "imag" part really is entirely imaginary, and
1024 contributes nothing in the real direction.
1025 Just treat it as a double. */
1026 tmp = (*nbi->nb_float)(i);
1027 if (tmp == NULL)
1028 return NULL;
1029 ci.real = PyFloat_AsDouble(tmp);
1030 Py_DECREF(tmp);
1031 }
1032 /* If the input was in canonical form, then the "real" and "imag"
1033 parts are real numbers, so that ci.imag and cr.imag are zero.
1034 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 if (ci_is_complex) {
1037 cr.real -= ci.imag;
1038 }
1039 if (cr_is_complex) {
1040 ci.real += cr.imag;
1041 }
1042 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001043}
1044
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001045PyDoc_STRVAR(complex_doc,
Tim Peters2400fa42001-09-12 19:12:49 +00001046"complex(real[, imag]) -> complex number\n"
1047"\n"
1048"Create a complex number from a real part and an optional imaginary part.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001049"This is equivalent to (real + imag*1j) where imag defaults to 0.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001051static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 (binaryfunc)complex_add, /* nb_add */
1053 (binaryfunc)complex_sub, /* nb_subtract */
1054 (binaryfunc)complex_mul, /* nb_multiply */
1055 (binaryfunc)complex_remainder, /* nb_remainder */
1056 (binaryfunc)complex_divmod, /* nb_divmod */
1057 (ternaryfunc)complex_pow, /* nb_power */
1058 (unaryfunc)complex_neg, /* nb_negative */
1059 (unaryfunc)complex_pos, /* nb_positive */
1060 (unaryfunc)complex_abs, /* nb_absolute */
1061 (inquiry)complex_bool, /* nb_bool */
1062 0, /* nb_invert */
1063 0, /* nb_lshift */
1064 0, /* nb_rshift */
1065 0, /* nb_and */
1066 0, /* nb_xor */
1067 0, /* nb_or */
1068 complex_int, /* nb_int */
1069 0, /* nb_reserved */
1070 complex_float, /* nb_float */
1071 0, /* nb_inplace_add */
1072 0, /* nb_inplace_subtract */
1073 0, /* nb_inplace_multiply*/
1074 0, /* nb_inplace_remainder */
1075 0, /* nb_inplace_power */
1076 0, /* nb_inplace_lshift */
1077 0, /* nb_inplace_rshift */
1078 0, /* nb_inplace_and */
1079 0, /* nb_inplace_xor */
1080 0, /* nb_inplace_or */
1081 (binaryfunc)complex_int_div, /* nb_floor_divide */
1082 (binaryfunc)complex_div, /* nb_true_divide */
1083 0, /* nb_inplace_floor_divide */
1084 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001085};
1086
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001087PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1089 "complex",
1090 sizeof(PyComplexObject),
1091 0,
1092 complex_dealloc, /* tp_dealloc */
1093 0, /* tp_print */
1094 0, /* tp_getattr */
1095 0, /* tp_setattr */
1096 0, /* tp_reserved */
1097 (reprfunc)complex_repr, /* tp_repr */
1098 &complex_as_number, /* tp_as_number */
1099 0, /* tp_as_sequence */
1100 0, /* tp_as_mapping */
1101 (hashfunc)complex_hash, /* tp_hash */
1102 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001103 (reprfunc)complex_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 PyObject_GenericGetAttr, /* tp_getattro */
1105 0, /* tp_setattro */
1106 0, /* tp_as_buffer */
1107 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1108 complex_doc, /* tp_doc */
1109 0, /* tp_traverse */
1110 0, /* tp_clear */
1111 complex_richcompare, /* tp_richcompare */
1112 0, /* tp_weaklistoffset */
1113 0, /* tp_iter */
1114 0, /* tp_iternext */
1115 complex_methods, /* tp_methods */
1116 complex_members, /* tp_members */
1117 0, /* tp_getset */
1118 0, /* tp_base */
1119 0, /* tp_dict */
1120 0, /* tp_descr_get */
1121 0, /* tp_descr_set */
1122 0, /* tp_dictoffset */
1123 0, /* tp_init */
1124 PyType_GenericAlloc, /* tp_alloc */
1125 complex_new, /* tp_new */
1126 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001127};