blob: ec529d5bbf950be8d51b3f25bb8552a1b7933459 [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
327
Eric Smith0923d1d2009-04-16 20:16:10 +0000328static PyObject *
Eric Smith63376222009-05-05 14:04:18 +0000329complex_format(PyComplexObject *v, int precision, char format_code)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *result = NULL;
332 Py_ssize_t len;
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;
337 char *buf = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 /* These do not need to be freed. re is either an alias
340 for pre or a pointer to a constant. lead and tail
341 are pointers to constants. */
342 char *re = NULL;
343 char *lead = "";
344 char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
347 re = "";
348 im = PyOS_double_to_string(v->cval.imag, format_code,
349 precision, 0, NULL);
350 if (!im) {
351 PyErr_NoMemory();
352 goto done;
353 }
354 } else {
355 /* Format imaginary part with sign, real part without */
356 pre = PyOS_double_to_string(v->cval.real, format_code,
357 precision, 0, NULL);
358 if (!pre) {
359 PyErr_NoMemory();
360 goto done;
361 }
362 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 im = PyOS_double_to_string(v->cval.imag, format_code,
365 precision, Py_DTSF_SIGN, NULL);
366 if (!im) {
367 PyErr_NoMemory();
368 goto done;
369 }
370 lead = "(";
371 tail = ")";
372 }
373 /* Alloc the final buffer. Add one for the "j" in the format string,
374 and one for the trailing zero. */
375 len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
376 buf = PyMem_Malloc(len);
377 if (!buf) {
378 PyErr_NoMemory();
379 goto done;
380 }
381 PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
382 result = PyUnicode_FromString(buf);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000383 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyMem_Free(im);
385 PyMem_Free(pre);
386 PyMem_Free(buf);
Eric Smith0923d1d2009-04-16 20:16:10 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000389}
390
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000391static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000392complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000393{
Eric Smith63376222009-05-05 14:04:18 +0000394 return complex_format(v, 0, 'r');
Tim Peters70695122001-03-11 08:37:29 +0000395}
396
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000397static Py_hash_t
Fred Drake4288c802000-07-09 04:36:04 +0000398complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000399{
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000400 Py_uhash_t hashreal, hashimag, combined;
401 hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real);
402 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 return -1;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000404 hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag);
405 if (hashimag == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return -1;
407 /* Note: if the imaginary part is 0, hashimag is 0 now,
408 * so the following returns hashreal unchanged. This is
409 * important because numbers of different types that
410 * compare equal must have the same hash value, so that
411 * hash(x + 0*j) must equal hash(x).
412 */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000413 combined = hashreal + _PyHASH_IMAG * hashimag;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000414 if (combined == (Py_uhash_t)-1)
415 combined = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000416 return (Py_hash_t)combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000417}
418
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000419/* This macro may return! */
420#define TO_COMPLEX(obj, c) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (PyComplex_Check(obj)) \
422 c = ((PyComplexObject *)(obj))->cval; \
423 else if (to_complex(&(obj), &(c)) < 0) \
424 return (obj)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000425
426static int
427to_complex(PyObject **pobj, Py_complex *pc)
428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 pc->real = pc->imag = 0.0;
432 if (PyLong_Check(obj)) {
433 pc->real = PyLong_AsDouble(obj);
434 if (pc->real == -1.0 && PyErr_Occurred()) {
435 *pobj = NULL;
436 return -1;
437 }
438 return 0;
439 }
440 if (PyFloat_Check(obj)) {
441 pc->real = PyFloat_AsDouble(obj);
442 return 0;
443 }
444 Py_INCREF(Py_NotImplemented);
445 *pobj = Py_NotImplemented;
446 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000447}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000449
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000451complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 Py_complex result;
454 Py_complex a, b;
455 TO_COMPLEX(v, a);
456 TO_COMPLEX(w, b);
457 PyFPE_START_PROTECT("complex_add", return 0)
458 result = c_sum(a, b);
459 PyFPE_END_PROTECT(result)
460 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000461}
462
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000463static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000464complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 Py_complex result;
467 Py_complex a, b;
468 TO_COMPLEX(v, a);
469 TO_COMPLEX(w, b);
470 PyFPE_START_PROTECT("complex_sub", return 0)
471 result = c_diff(a, b);
472 PyFPE_END_PROTECT(result)
473 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000474}
475
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000477complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 Py_complex result;
480 Py_complex a, b;
481 TO_COMPLEX(v, a);
482 TO_COMPLEX(w, b);
483 PyFPE_START_PROTECT("complex_mul", return 0)
484 result = c_prod(a, b);
485 PyFPE_END_PROTECT(result)
486 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000487}
488
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000490complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_complex quot;
493 Py_complex a, b;
494 TO_COMPLEX(v, a);
495 TO_COMPLEX(w, b);
496 PyFPE_START_PROTECT("complex_div", return 0)
497 errno = 0;
498 quot = c_quot(a, b);
499 PyFPE_END_PROTECT(quot)
500 if (errno == EDOM) {
501 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
502 return NULL;
503 }
504 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000505}
506
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000507static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000508complex_remainder(PyObject *v, PyObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyErr_SetString(PyExc_TypeError,
511 "can't mod complex numbers.");
512 return NULL;
Guido van Rossumee09fc11996-09-11 13:55:55 +0000513}
514
Guido van Rossumee09fc11996-09-11 13:55:55 +0000515
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000517complex_divmod(PyObject *v, PyObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 PyErr_SetString(PyExc_TypeError,
520 "can't take floor or mod of complex number.");
521 return NULL;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000522}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000523
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000524static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000525complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 Py_complex p;
528 Py_complex exponent;
529 long int_exponent;
530 Py_complex a, b;
531 TO_COMPLEX(v, a);
532 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (z != Py_None) {
535 PyErr_SetString(PyExc_ValueError, "complex modulo");
536 return NULL;
537 }
538 PyFPE_START_PROTECT("complex_pow", return 0)
539 errno = 0;
540 exponent = b;
541 int_exponent = (long)exponent.real;
542 if (exponent.imag == 0. && exponent.real == int_exponent)
543 p = c_powi(a, int_exponent);
544 else
545 p = c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 PyFPE_END_PROTECT(p)
548 Py_ADJUST_ERANGE2(p.real, p.imag);
549 if (errno == EDOM) {
550 PyErr_SetString(PyExc_ZeroDivisionError,
551 "0.0 to a negative or complex power");
552 return NULL;
553 }
554 else if (errno == ERANGE) {
555 PyErr_SetString(PyExc_OverflowError,
556 "complex exponentiation");
557 return NULL;
558 }
559 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000563complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 PyErr_SetString(PyExc_TypeError,
566 "can't take floor of complex number.");
567 return NULL;
Guido van Rossum4668b002001-08-08 05:00:18 +0000568}
569
570static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000571complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 Py_complex neg;
574 neg.real = -v->cval.real;
575 neg.imag = -v->cval.imag;
576 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000577}
578
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000579static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000580complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 if (PyComplex_CheckExact(v)) {
583 Py_INCREF(v);
584 return (PyObject *)v;
585 }
586 else
587 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000588}
589
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000590static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000591complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PyFPE_START_PROTECT("complex_abs", return 0)
596 result = c_abs(v->cval);
597 PyFPE_END_PROTECT(result)
Christian Heimes53876d92008-04-19 00:31:39 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (errno == ERANGE) {
600 PyErr_SetString(PyExc_OverflowError,
601 "absolute value too large");
602 return NULL;
603 }
604 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000605}
606
607static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000608complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000611}
612
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000614complex_richcompare(PyObject *v, PyObject *w, int op)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000617 Py_complex i;
618 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000621 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 }
Guido van Rossum22056422001-09-24 17:52:04 +0000623
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000624 assert(PyComplex_Check(v));
625 TO_COMPLEX(v, i);
626
627 if (PyLong_Check(w)) {
628 /* Check for 0.0 imaginary part first to avoid the rich
629 * comparison when possible.
630 */
631 if (i.imag == 0.0) {
632 PyObject *j, *sub_res;
633 j = PyFloat_FromDouble(i.real);
634 if (j == NULL)
635 return NULL;
636
637 sub_res = PyObject_RichCompare(j, w, op);
638 Py_DECREF(j);
639 return sub_res;
640 }
641 else {
642 equal = 0;
643 }
644 }
645 else if (PyFloat_Check(w)) {
646 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
647 }
648 else if (PyComplex_Check(w)) {
649 Py_complex j;
650
651 TO_COMPLEX(w, j);
652 equal = (i.real == j.real && i.imag == j.imag);
653 }
654 else {
655 goto Unimplemented;
656 }
657
658 if (equal == (op == Py_EQ))
659 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000661 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 Py_INCREF(res);
664 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000665
666Unimplemented:
667 Py_INCREF(Py_NotImplemented);
668 return Py_NotImplemented;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000669}
670
671static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000672complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyErr_SetString(PyExc_TypeError,
675 "can't convert complex to int");
676 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000677}
678
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000680complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 PyErr_SetString(PyExc_TypeError,
683 "can't convert complex to float");
684 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000685}
686
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000687static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000688complex_conjugate(PyObject *self)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 Py_complex c;
691 c = ((PyComplexObject *)self)->cval;
692 c.imag = -c.imag;
693 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000694}
695
Guido van Rossum46334cd2007-08-01 17:43:15 +0000696PyDoc_STRVAR(complex_conjugate_doc,
697"complex.conjugate() -> complex\n"
698"\n"
699"Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
700
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000701static PyObject *
702complex_getnewargs(PyComplexObject *v)
703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 Py_complex c = v->cval;
705 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000706}
707
Eric Smith58a42242009-04-30 01:00:33 +0000708PyDoc_STRVAR(complex__format__doc,
709"complex.__format__() -> str\n"
710"\n"
711"Converts to a string according to format_spec.");
712
713static PyObject *
714complex__format__(PyObject* self, PyObject* args)
715{
716 PyObject *format_spec;
717
718 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 return NULL;
Eric Smith58a42242009-04-30 01:00:33 +0000720 return _PyComplex_FormatAdvanced(self,
721 PyUnicode_AS_UNICODE(format_spec),
722 PyUnicode_GET_SIZE(format_spec));
723}
724
Christian Heimes53876d92008-04-19 00:31:39 +0000725#if 0
726static PyObject *
727complex_is_finite(PyObject *self)
728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 Py_complex c;
730 c = ((PyComplexObject *)self)->cval;
731 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
732 Py_IS_FINITE(c.imag)));
Christian Heimes53876d92008-04-19 00:31:39 +0000733}
734
735PyDoc_STRVAR(complex_is_finite_doc,
736"complex.is_finite() -> bool\n"
737"\n"
738"Returns True if the real and the imaginary part is finite.");
739#endif
740
Guido van Rossumf9fca921996-01-12 00:47:05 +0000741static PyMethodDef complex_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
743 complex_conjugate_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000744#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
746 complex_is_finite_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000747#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
749 {"__format__", (PyCFunction)complex__format__,
750 METH_VARARGS, complex__format__doc},
751 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000752};
753
Guido van Rossum6f799372001-09-20 20:46:19 +0000754static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
756 "the real part of a complex number"},
757 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
758 "the imaginary part of a complex number"},
759 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000760};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000761
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000762static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000763complex_subtype_from_string(PyTypeObject *type, PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 const char *s, *start;
766 char *end;
767 double x=0.0, y=0.0, z;
768 int got_bracket=0;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000769 PyObject *s_buffer = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (PyUnicode_Check(v)) {
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000773 Py_ssize_t i, buflen = PyUnicode_GET_SIZE(v);
774 Py_UNICODE *bufptr;
775 s_buffer = PyUnicode_TransformDecimalToASCII(
776 PyUnicode_AS_UNICODE(v), buflen);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if (s_buffer == NULL)
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000778 return NULL;
779 /* Replace non-ASCII whitespace with ' ' */
780 bufptr = PyUnicode_AS_UNICODE(s_buffer);
781 for (i = 0; i < buflen; i++) {
782 Py_UNICODE ch = bufptr[i];
783 if (ch > 127 && Py_UNICODE_ISSPACE(ch))
784 bufptr[i] = ' ';
785 }
786 s = _PyUnicode_AsStringAndSize(s_buffer, &len);
787 if (s == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 }
790 else if (PyObject_AsCharBuffer(v, &s, &len)) {
791 PyErr_SetString(PyExc_TypeError,
Victor Stinnerf9613772010-12-03 16:51:33 +0000792 "complex() argument must be a string or a number");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 return NULL;
794 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 /* position on first nonblank */
797 start = s;
798 while (Py_ISSPACE(*s))
799 s++;
800 if (*s == '(') {
801 /* Skip over possible bracket from repr(). */
802 got_bracket = 1;
803 s++;
804 while (Py_ISSPACE(*s))
805 s++;
806 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 <float> - real part only
811 <float>j - imaginary part only
812 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 where <float> represents any numeric string that's accepted by the
815 float constructor (including 'nan', 'inf', 'infinity', etc.), and
816 <signed-float> is any string of the form <float> whose first
817 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 <float><sign>j
822 <sign>j
823 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 are also accepted, though support for these forms may be removed from
826 a future version of Python.
827 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 /* first look for forms starting with <float> */
830 z = PyOS_string_to_double(s, &end, NULL);
831 if (z == -1.0 && PyErr_Occurred()) {
832 if (PyErr_ExceptionMatches(PyExc_ValueError))
833 PyErr_Clear();
834 else
835 goto error;
836 }
837 if (end != s) {
838 /* all 4 forms starting with <float> land here */
839 s = end;
840 if (*s == '+' || *s == '-') {
841 /* <float><signed-float>j | <float><sign>j */
842 x = z;
843 y = PyOS_string_to_double(s, &end, NULL);
844 if (y == -1.0 && PyErr_Occurred()) {
845 if (PyErr_ExceptionMatches(PyExc_ValueError))
846 PyErr_Clear();
847 else
848 goto error;
849 }
850 if (end != s)
851 /* <float><signed-float>j */
852 s = end;
853 else {
854 /* <float><sign>j */
855 y = *s == '+' ? 1.0 : -1.0;
856 s++;
857 }
858 if (!(*s == 'j' || *s == 'J'))
859 goto parse_error;
860 s++;
861 }
862 else if (*s == 'j' || *s == 'J') {
863 /* <float>j */
864 s++;
865 y = z;
866 }
867 else
868 /* <float> */
869 x = z;
870 }
871 else {
872 /* not starting with <float>; must be <sign>j or j */
873 if (*s == '+' || *s == '-') {
874 /* <sign>j */
875 y = *s == '+' ? 1.0 : -1.0;
876 s++;
877 }
878 else
879 /* j */
880 y = 1.0;
881 if (!(*s == 'j' || *s == 'J'))
882 goto parse_error;
883 s++;
884 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 /* trailing whitespace and closing bracket */
887 while (Py_ISSPACE(*s))
888 s++;
889 if (got_bracket) {
890 /* if there was an opening parenthesis, then the corresponding
891 closing parenthesis should be right here */
892 if (*s != ')')
893 goto parse_error;
894 s++;
895 while (Py_ISSPACE(*s))
896 s++;
897 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* we should now be at the end of the string */
900 if (s-start != len)
901 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000902
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000903 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 return complex_subtype_from_doubles(type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000905
Mark Dickinson6649fa42009-04-24 13:25:20 +0000906 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 PyErr_SetString(PyExc_ValueError,
908 "complex() arg is a malformed string");
Mark Dickinson1daebdf2009-10-26 22:05:06 +0000909 error:
Alexander Belopolsky942af5a2010-12-04 03:38:46 +0000910 Py_XDECREF(s_buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000912}
913
Tim Peters6d6c1a32001-08-02 04:15:00 +0000914static PyObject *
915complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 PyObject *r, *i, *tmp;
918 PyNumberMethods *nbr, *nbi = NULL;
919 Py_complex cr, ci;
920 int own_r = 0;
921 int cr_is_complex = 0;
922 int ci_is_complex = 0;
923 static char *kwlist[] = {"real", "imag", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 r = Py_False;
926 i = NULL;
927 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
928 &r, &i))
929 return NULL;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Special-case for a single argument when type(arg) is complex. */
932 if (PyComplex_CheckExact(r) && i == NULL &&
933 type == &PyComplex_Type) {
934 /* Note that we can't know whether it's safe to return
935 a complex *subclass* instance as-is, hence the restriction
936 to exact complexes here. If either the input or the
937 output is a complex subclass, it will be handled below
938 as a non-orthogonal vector. */
939 Py_INCREF(r);
940 return r;
941 }
942 if (PyUnicode_Check(r)) {
943 if (i != NULL) {
944 PyErr_SetString(PyExc_TypeError,
945 "complex() can't take second arg"
946 " if first is a string");
947 return NULL;
948 }
949 return complex_subtype_from_string(type, r);
950 }
951 if (i != NULL && PyUnicode_Check(i)) {
952 PyErr_SetString(PyExc_TypeError,
953 "complex() second arg can't be a string");
954 return NULL;
955 }
Tim Peters2400fa42001-09-12 19:12:49 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 tmp = try_complex_special_method(r);
958 if (tmp) {
959 r = tmp;
960 own_r = 1;
961 }
962 else if (PyErr_Occurred()) {
963 return NULL;
964 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 nbr = r->ob_type->tp_as_number;
967 if (i != NULL)
968 nbi = i->ob_type->tp_as_number;
969 if (nbr == NULL || nbr->nb_float == NULL ||
970 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
971 PyErr_SetString(PyExc_TypeError,
972 "complex() argument must be a string or a number");
973 if (own_r) {
974 Py_DECREF(r);
975 }
976 return NULL;
977 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* If we get this far, then the "real" and "imag" parts should
980 both be treated as numbers, and the constructor should return a
981 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 Note that we do NOT assume the input to already be in canonical
984 form; the "real" and "imag" parts might themselves be complex
985 numbers, which slightly complicates the code below. */
986 if (PyComplex_Check(r)) {
987 /* Note that if r is of a complex subtype, we're only
988 retaining its real & imag parts here, and the return
989 value is (properly) of the builtin complex type. */
990 cr = ((PyComplexObject*)r)->cval;
991 cr_is_complex = 1;
992 if (own_r) {
993 Py_DECREF(r);
994 }
995 }
996 else {
997 /* The "real" part really is entirely real, and contributes
998 nothing in the imaginary direction.
999 Just treat it as a double. */
1000 tmp = PyNumber_Float(r);
1001 if (own_r) {
1002 /* r was a newly created complex number, rather
1003 than the original "real" argument. */
1004 Py_DECREF(r);
1005 }
1006 if (tmp == NULL)
1007 return NULL;
1008 if (!PyFloat_Check(tmp)) {
1009 PyErr_SetString(PyExc_TypeError,
1010 "float(r) didn't return a float");
1011 Py_DECREF(tmp);
1012 return NULL;
1013 }
1014 cr.real = PyFloat_AsDouble(tmp);
1015 cr.imag = 0.0; /* Shut up compiler warning */
1016 Py_DECREF(tmp);
1017 }
1018 if (i == NULL) {
1019 ci.real = 0.0;
1020 }
1021 else if (PyComplex_Check(i)) {
1022 ci = ((PyComplexObject*)i)->cval;
1023 ci_is_complex = 1;
1024 } else {
1025 /* The "imag" part really is entirely imaginary, and
1026 contributes nothing in the real direction.
1027 Just treat it as a double. */
1028 tmp = (*nbi->nb_float)(i);
1029 if (tmp == NULL)
1030 return NULL;
1031 ci.real = PyFloat_AsDouble(tmp);
1032 Py_DECREF(tmp);
1033 }
1034 /* If the input was in canonical form, then the "real" and "imag"
1035 parts are real numbers, so that ci.imag and cr.imag are zero.
1036 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 if (ci_is_complex) {
1039 cr.real -= ci.imag;
1040 }
1041 if (cr_is_complex) {
1042 ci.real += cr.imag;
1043 }
1044 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001045}
1046
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001047PyDoc_STRVAR(complex_doc,
Tim Peters2400fa42001-09-12 19:12:49 +00001048"complex(real[, imag]) -> complex number\n"
1049"\n"
1050"Create a complex number from a real part and an optional imaginary part.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001051"This is equivalent to (real + imag*1j) where imag defaults to 0.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001052
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001053static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 (binaryfunc)complex_add, /* nb_add */
1055 (binaryfunc)complex_sub, /* nb_subtract */
1056 (binaryfunc)complex_mul, /* nb_multiply */
1057 (binaryfunc)complex_remainder, /* nb_remainder */
1058 (binaryfunc)complex_divmod, /* nb_divmod */
1059 (ternaryfunc)complex_pow, /* nb_power */
1060 (unaryfunc)complex_neg, /* nb_negative */
1061 (unaryfunc)complex_pos, /* nb_positive */
1062 (unaryfunc)complex_abs, /* nb_absolute */
1063 (inquiry)complex_bool, /* nb_bool */
1064 0, /* nb_invert */
1065 0, /* nb_lshift */
1066 0, /* nb_rshift */
1067 0, /* nb_and */
1068 0, /* nb_xor */
1069 0, /* nb_or */
1070 complex_int, /* nb_int */
1071 0, /* nb_reserved */
1072 complex_float, /* nb_float */
1073 0, /* nb_inplace_add */
1074 0, /* nb_inplace_subtract */
1075 0, /* nb_inplace_multiply*/
1076 0, /* nb_inplace_remainder */
1077 0, /* nb_inplace_power */
1078 0, /* nb_inplace_lshift */
1079 0, /* nb_inplace_rshift */
1080 0, /* nb_inplace_and */
1081 0, /* nb_inplace_xor */
1082 0, /* nb_inplace_or */
1083 (binaryfunc)complex_int_div, /* nb_floor_divide */
1084 (binaryfunc)complex_div, /* nb_true_divide */
1085 0, /* nb_inplace_floor_divide */
1086 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001087};
1088
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001089PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1091 "complex",
1092 sizeof(PyComplexObject),
1093 0,
1094 complex_dealloc, /* tp_dealloc */
1095 0, /* tp_print */
1096 0, /* tp_getattr */
1097 0, /* tp_setattr */
1098 0, /* tp_reserved */
1099 (reprfunc)complex_repr, /* tp_repr */
1100 &complex_as_number, /* tp_as_number */
1101 0, /* tp_as_sequence */
1102 0, /* tp_as_mapping */
1103 (hashfunc)complex_hash, /* tp_hash */
1104 0, /* tp_call */
Mark Dickinson388122d2010-08-04 20:56:28 +00001105 (reprfunc)complex_repr, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 PyObject_GenericGetAttr, /* tp_getattro */
1107 0, /* tp_setattro */
1108 0, /* tp_as_buffer */
1109 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1110 complex_doc, /* tp_doc */
1111 0, /* tp_traverse */
1112 0, /* tp_clear */
1113 complex_richcompare, /* tp_richcompare */
1114 0, /* tp_weaklistoffset */
1115 0, /* tp_iter */
1116 0, /* tp_iternext */
1117 complex_methods, /* tp_methods */
1118 complex_members, /* tp_members */
1119 0, /* tp_getset */
1120 0, /* tp_base */
1121 0, /* tp_dict */
1122 0, /* tp_descr_get */
1123 0, /* tp_descr_set */
1124 0, /* tp_dictoffset */
1125 0, /* tp_init */
1126 PyType_GenericAlloc, /* tp_alloc */
1127 complex_new, /* tp_new */
1128 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001129};