blob: 691809f1345e01b81e54dcb2de85bf4387db120c [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
Christian Heimesbbe741d2008-03-28 10:53:29 +000011#ifdef HAVE_IEEEFP_H
12#include <ieeefp.h>
13#endif
14
Guido van Rossum65ce6de2002-06-13 17:07:07 +000015#ifndef WITHOUT_COMPLEX
16
Guido van Rossumf9fca921996-01-12 00:47:05 +000017/* elementary operations on complex numbers */
18
Guido van Rossum9e720e31996-07-21 02:31:35 +000019static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000020
Tim Peters0f336042001-03-18 08:21:57 +000021Py_complex
22c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000023{
Guido van Rossum9e720e31996-07-21 02:31:35 +000024 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000025 r.real = a.real + b.real;
26 r.imag = a.imag + b.imag;
27 return r;
28}
29
Tim Peters0f336042001-03-18 08:21:57 +000030Py_complex
31c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000032{
Guido van Rossum9e720e31996-07-21 02:31:35 +000033 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000034 r.real = a.real - b.real;
35 r.imag = a.imag - b.imag;
36 return r;
37}
38
Tim Peters0f336042001-03-18 08:21:57 +000039Py_complex
40c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000041{
Guido van Rossum9e720e31996-07-21 02:31:35 +000042 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000043 r.real = -a.real;
44 r.imag = -a.imag;
45 return r;
46}
47
Tim Peters0f336042001-03-18 08:21:57 +000048Py_complex
49c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000050{
Guido van Rossum9e720e31996-07-21 02:31:35 +000051 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000052 r.real = a.real*b.real - a.imag*b.imag;
53 r.imag = a.real*b.imag + a.imag*b.real;
54 return r;
55}
56
Tim Peters0f336042001-03-18 08:21:57 +000057Py_complex
58c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000059{
Tim Peters0f336042001-03-18 08:21:57 +000060 /******************************************************************
61 This was the original algorithm. It's grossly prone to spurious
62 overflow and underflow errors. It also merrily divides by 0 despite
63 checking for that(!). The code still serves a doc purpose here, as
64 the algorithm following is a simple by-cases transformation of this
65 one:
66
Guido van Rossum9e720e31996-07-21 02:31:35 +000067 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000068 double d = b.real*b.real + b.imag*b.imag;
69 if (d == 0.)
Guido van Rossum96783941997-05-20 18:21:34 +000070 errno = EDOM;
Guido van Rossumf9fca921996-01-12 00:47:05 +000071 r.real = (a.real*b.real + a.imag*b.imag)/d;
72 r.imag = (a.imag*b.real - a.real*b.imag)/d;
73 return r;
Tim Peters0f336042001-03-18 08:21:57 +000074 ******************************************************************/
75
76 /* This algorithm is better, and is pretty obvious: first divide the
77 * numerators and denominator by whichever of {b.real, b.imag} has
78 * larger magnitude. The earliest reference I found was to CACM
79 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
80 * University). As usual, though, we're still ignoring all IEEE
81 * endcases.
82 */
83 Py_complex r; /* the result */
84 const double abs_breal = b.real < 0 ? -b.real : b.real;
85 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
86
87 if (abs_breal >= abs_bimag) {
88 /* divide tops and bottom by b.real */
89 if (abs_breal == 0.0) {
90 errno = EDOM;
91 r.real = r.imag = 0.0;
92 }
93 else {
94 const double ratio = b.imag / b.real;
95 const double denom = b.real + b.imag * ratio;
96 r.real = (a.real + a.imag * ratio) / denom;
97 r.imag = (a.imag - a.real * ratio) / denom;
98 }
99 }
100 else {
101 /* divide tops and bottom by b.imag */
102 const double ratio = b.real / b.imag;
103 const double denom = b.real * ratio + b.imag;
104 assert(b.imag != 0.0);
105 r.real = (a.real * ratio + a.imag) / denom;
106 r.imag = (a.imag * ratio - a.real) / denom;
107 }
108 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000109}
110
Tim Peters0f336042001-03-18 08:21:57 +0000111Py_complex
112c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000113{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000114 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000115 double vabs,len,at,phase;
116 if (b.real == 0. && b.imag == 0.) {
117 r.real = 1.;
118 r.imag = 0.;
119 }
120 else if (a.real == 0. && a.imag == 0.) {
121 if (b.imag != 0. || b.real < 0.)
Tim Petersbab22be2002-03-22 02:48:46 +0000122 errno = EDOM;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000123 r.real = 0.;
124 r.imag = 0.;
125 }
126 else {
127 vabs = hypot(a.real,a.imag);
128 len = pow(vabs,b.real);
Martin v. Löwis387c5472001-09-06 08:16:17 +0000129 at = atan2(a.imag, a.real);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000130 phase = at*b.real;
131 if (b.imag != 0.0) {
132 len /= exp(at*b.imag);
133 phase += b.imag*log(vabs);
134 }
135 r.real = len*cos(phase);
136 r.imag = len*sin(phase);
137 }
138 return r;
139}
140
Tim Peters0f336042001-03-18 08:21:57 +0000141static Py_complex
142c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000143{
Guido van Rossum926518b1996-08-19 19:30:45 +0000144 Py_complex r, p;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000145 long mask = 1;
Guido van Rossum926518b1996-08-19 19:30:45 +0000146 r = c_1;
147 p = x;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000148 while (mask > 0 && n >= mask) {
149 if (n & mask)
150 r = c_prod(r,p);
151 mask <<= 1;
152 p = c_prod(p,p);
153 }
154 return r;
155}
156
Tim Peters0f336042001-03-18 08:21:57 +0000157static Py_complex
158c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000159{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000160 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000161
162 if (n > 100 || n < -100) {
163 cn.real = (double) n;
164 cn.imag = 0.;
165 return c_pow(x,cn);
166 }
167 else if (n > 0)
168 return c_powu(x,n);
169 else
170 return c_quot(c_1,c_powu(x,-n));
171
172}
173
Christian Heimes53876d92008-04-19 00:31:39 +0000174double
175c_abs(Py_complex z)
176{
177 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
178 double result;
179
180 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
181 /* C99 rules: if either the real or the imaginary part is an
182 infinity, return infinity, even if the other part is a
183 NaN. */
184 if (Py_IS_INFINITY(z.real)) {
185 result = fabs(z.real);
186 errno = 0;
187 return result;
188 }
189 if (Py_IS_INFINITY(z.imag)) {
190 result = fabs(z.imag);
191 errno = 0;
192 return result;
193 }
194 /* either the real or imaginary part is a NaN,
195 and neither is infinite. Result should be NaN. */
196 return Py_NAN;
197 }
198 result = hypot(z.real, z.imag);
199 if (!Py_IS_FINITE(result))
200 errno = ERANGE;
201 else
202 errno = 0;
203 return result;
204}
205
Tim Peters6d6c1a32001-08-02 04:15:00 +0000206static PyObject *
207complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
208{
209 PyObject *op;
210
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000211 op = type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000212 if (op != NULL)
213 ((PyComplexObject *)op)->cval = cval;
214 return op;
215}
216
Guido van Rossumf9fca921996-01-12 00:47:05 +0000217PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000218PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000219{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000220 register PyComplexObject *op;
221
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000222 /* Inline PyObject_New */
Guido van Rossumb18618d2000-05-03 23:44:39 +0000223 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000224 if (op == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000225 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000226 PyObject_INIT(op, &PyComplex_Type);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000227 op->cval = cval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000228 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000229}
230
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231static PyObject *
232complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
233{
234 Py_complex c;
235 c.real = real;
236 c.imag = imag;
237 return complex_subtype_from_c_complex(type, c);
238}
239
Guido van Rossumf9fca921996-01-12 00:47:05 +0000240PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000241PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000242{
243 Py_complex c;
244 c.real = real;
245 c.imag = imag;
246 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000247}
248
249double
Fred Drake4288c802000-07-09 04:36:04 +0000250PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000251{
252 if (PyComplex_Check(op)) {
253 return ((PyComplexObject *)op)->cval.real;
Fred Drake4288c802000-07-09 04:36:04 +0000254 }
255 else {
Guido van Rossum926518b1996-08-19 19:30:45 +0000256 return PyFloat_AsDouble(op);
257 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000258}
259
260double
Fred Drake4288c802000-07-09 04:36:04 +0000261PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000262{
263 if (PyComplex_Check(op)) {
264 return ((PyComplexObject *)op)->cval.imag;
Fred Drake4288c802000-07-09 04:36:04 +0000265 }
266 else {
Guido van Rossum926518b1996-08-19 19:30:45 +0000267 return 0.0;
268 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000269}
270
Guido van Rossum9e720e31996-07-21 02:31:35 +0000271Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000272PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000273{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000274 Py_complex cv;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275 PyObject *newop = NULL;
276 static PyObject *complex_str = NULL;
277
278 assert(op);
279 /* If op is already of type PyComplex_Type, return its value */
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000280 if (PyComplex_Check(op)) {
281 return ((PyComplexObject *)op)->cval;
Fred Drake4288c802000-07-09 04:36:04 +0000282 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283 /* If not, use op's __complex__ method, if it exists */
284
285 /* return -1 on failure */
286 cv.real = -1.;
287 cv.imag = 0.;
Christian Heimesfe82e772008-01-28 02:38:20 +0000288
289 if (complex_str == NULL) {
290 if (!(complex_str = PyUnicode_FromString("__complex__")))
291 return cv;
292 }
293
Guido van Rossumd8faa362007-04-27 19:54:29 +0000294 {
295 PyObject *complexfunc;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000296 complexfunc = _PyType_Lookup(op->ob_type, complex_str);
297 /* complexfunc is a borrowed reference */
298 if (complexfunc) {
299 newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL);
300 if (!newop)
301 return cv;
302 }
303 }
304
305 if (newop) {
306 if (!PyComplex_Check(newop)) {
307 PyErr_SetString(PyExc_TypeError,
308 "__complex__ should return a complex object");
309 Py_DECREF(newop);
310 return cv;
311 }
312 cv = ((PyComplexObject *)newop)->cval;
313 Py_DECREF(newop);
314 return cv;
315 }
316 /* If neither of the above works, interpret op as a float giving the
317 real part of the result, and fill in the imaginary part as 0. */
Fred Drake4288c802000-07-09 04:36:04 +0000318 else {
Guido van Rossumd8faa362007-04-27 19:54:29 +0000319 /* PyFloat_AsDouble will return -1 on failure */
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000320 cv.real = PyFloat_AsDouble(op);
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000321 return cv;
Tim Peters70695122001-03-11 08:37:29 +0000322 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000323}
324
Guido van Rossumf9fca921996-01-12 00:47:05 +0000325static void
Fred Drake4288c802000-07-09 04:36:04 +0000326complex_dealloc(PyObject *op)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000327{
Guido van Rossum9475a232001-10-05 20:51:39 +0000328 op->ob_type->tp_free(op);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000329}
330
331
Eric Smith0923d1d2009-04-16 20:16:10 +0000332static PyObject *
333complex_format(PyComplexObject *v, char format_code)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000334{
Mark Dickinsonad476da2009-04-23 19:14:16 +0000335 PyObject *result = NULL;
336 Py_ssize_t len;
Eric Smith0923d1d2009-04-16 20:16:10 +0000337
Mark Dickinsonad476da2009-04-23 19:14:16 +0000338 /* If these are non-NULL, they'll need to be freed. */
339 char *pre = NULL;
340 char *im = NULL;
341 char *buf = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000342
Mark Dickinsonad476da2009-04-23 19:14:16 +0000343 /* These do not need to be freed. re is either an alias
344 for pre or a pointer to a constant. lead and tail
345 are pointers to constants. */
346 char *re = NULL;
347 char *lead = "";
348 char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000349
Mark Dickinsonad476da2009-04-23 19:14:16 +0000350 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
351 re = "";
352 im = PyOS_double_to_string(v->cval.imag, format_code,
353 0, 0, NULL);
354 if (!im) {
355 PyErr_NoMemory();
356 goto done;
357 }
358 } else {
359 /* Format imaginary part with sign, real part without */
360 pre = PyOS_double_to_string(v->cval.real, format_code,
361 0, 0, NULL);
362 if (!pre) {
363 PyErr_NoMemory();
364 goto done;
365 }
366 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000367
Mark Dickinsonad476da2009-04-23 19:14:16 +0000368 im = PyOS_double_to_string(v->cval.imag, format_code,
369 0, 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,
378 and one for the trailing zero. */
379 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);
387 done:
388 PyMem_Free(im);
389 PyMem_Free(pre);
390 PyMem_Free(buf);
Eric Smith0923d1d2009-04-16 20:16:10 +0000391
Mark Dickinsonad476da2009-04-23 19:14:16 +0000392 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000393}
394
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000396complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000397{
Eric Smith0923d1d2009-04-16 20:16:10 +0000398 return complex_format(v, 'r');
Tim Peters70695122001-03-11 08:37:29 +0000399}
400
401static PyObject *
402complex_str(PyComplexObject *v)
403{
Eric Smith0923d1d2009-04-16 20:16:10 +0000404 return complex_format(v, 's');
Guido van Rossumf9fca921996-01-12 00:47:05 +0000405}
406
Guido van Rossumf9fca921996-01-12 00:47:05 +0000407static long
Fred Drake4288c802000-07-09 04:36:04 +0000408complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000409{
Tim Peters39dce292000-08-15 03:34:48 +0000410 long hashreal, hashimag, combined;
411 hashreal = _Py_HashDouble(v->cval.real);
412 if (hashreal == -1)
413 return -1;
414 hashimag = _Py_HashDouble(v->cval.imag);
415 if (hashimag == -1)
416 return -1;
417 /* Note: if the imaginary part is 0, hashimag is 0 now,
418 * so the following returns hashreal unchanged. This is
419 * important because numbers of different types that
420 * compare equal must have the same hash value, so that
421 * hash(x + 0*j) must equal hash(x).
422 */
423 combined = hashreal + 1000003 * hashimag;
424 if (combined == -1)
425 combined = -2;
426 return combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000427}
428
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000429/* This macro may return! */
430#define TO_COMPLEX(obj, c) \
431 if (PyComplex_Check(obj)) \
432 c = ((PyComplexObject *)(obj))->cval; \
433 else if (to_complex(&(obj), &(c)) < 0) \
434 return (obj)
435
436static int
437to_complex(PyObject **pobj, Py_complex *pc)
438{
Christian Heimes587c2bf2008-01-19 16:21:02 +0000439 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000440
Christian Heimes587c2bf2008-01-19 16:21:02 +0000441 pc->real = pc->imag = 0.0;
442 if (PyLong_Check(obj)) {
443 pc->real = PyLong_AsDouble(obj);
444 if (pc->real == -1.0 && PyErr_Occurred()) {
445 *pobj = NULL;
446 return -1;
447 }
448 return 0;
449 }
450 if (PyFloat_Check(obj)) {
451 pc->real = PyFloat_AsDouble(obj);
452 return 0;
453 }
454 Py_INCREF(Py_NotImplemented);
455 *pobj = Py_NotImplemented;
456 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000457}
458
459
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000461complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000462{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000463 Py_complex result;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000464 Py_complex a, b;
Christian Heimes587c2bf2008-01-19 16:21:02 +0000465 TO_COMPLEX(v, a);
466 TO_COMPLEX(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000467 PyFPE_START_PROTECT("complex_add", return 0)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000468 result = c_sum(a, b);
Guido van Rossum45b83911997-03-14 04:32:50 +0000469 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000470 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000471}
472
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000474complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000475{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000476 Py_complex result;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000477 Py_complex a, b;
Christian Heimes587c2bf2008-01-19 16:21:02 +0000478 TO_COMPLEX(v, a);
479 TO_COMPLEX(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000480 PyFPE_START_PROTECT("complex_sub", return 0)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000481 result = c_diff(a, b);
Guido van Rossum45b83911997-03-14 04:32:50 +0000482 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000484}
485
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000487complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000488{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000489 Py_complex result;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000490 Py_complex a, b;
Christian Heimes587c2bf2008-01-19 16:21:02 +0000491 TO_COMPLEX(v, a);
492 TO_COMPLEX(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000493 PyFPE_START_PROTECT("complex_mul", return 0)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000494 result = c_prod(a, b);
Guido van Rossum45b83911997-03-14 04:32:50 +0000495 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000497}
498
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000500complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000501{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000502 Py_complex quot;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000503 Py_complex a, b;
Christian Heimes587c2bf2008-01-19 16:21:02 +0000504 TO_COMPLEX(v, a);
505 TO_COMPLEX(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000506 PyFPE_START_PROTECT("complex_div", return 0)
Guido van Rossum96783941997-05-20 18:21:34 +0000507 errno = 0;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000508 quot = c_quot(a, b);
Guido van Rossum45b83911997-03-14 04:32:50 +0000509 PyFPE_END_PROTECT(quot)
Guido van Rossum96783941997-05-20 18:21:34 +0000510 if (errno == EDOM) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000512 return NULL;
513 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000515}
516
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000517static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000518complex_remainder(PyObject *v, PyObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000519{
Guido van Rossum46334cd2007-08-01 17:43:15 +0000520 PyErr_SetString(PyExc_TypeError,
521 "can't mod complex numbers.");
522 return NULL;
Guido van Rossumee09fc11996-09-11 13:55:55 +0000523}
524
Guido van Rossumee09fc11996-09-11 13:55:55 +0000525
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000527complex_divmod(PyObject *v, PyObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000528{
Guido van Rossum46334cd2007-08-01 17:43:15 +0000529 PyErr_SetString(PyExc_TypeError,
530 "can't take floor or mod of complex number.");
531 return NULL;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000532}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000533
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000534static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000535complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000536{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000537 Py_complex p;
538 Py_complex exponent;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000539 long int_exponent;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000540 Py_complex a, b;
Christian Heimes587c2bf2008-01-19 16:21:02 +0000541 TO_COMPLEX(v, a);
542 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000543
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000544 if (z != Py_None) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 PyErr_SetString(PyExc_ValueError, "complex modulo");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000546 return NULL;
547 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000548 PyFPE_START_PROTECT("complex_pow", return 0)
Guido van Rossum96783941997-05-20 18:21:34 +0000549 errno = 0;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000550 exponent = b;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000551 int_exponent = (long)exponent.real;
552 if (exponent.imag == 0. && exponent.real == int_exponent)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000553 p = c_powi(a, int_exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000554 else
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000555 p = c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000556
Guido van Rossum45b83911997-03-14 04:32:50 +0000557 PyFPE_END_PROTECT(p)
Tim Petersbab22be2002-03-22 02:48:46 +0000558 Py_ADJUST_ERANGE2(p.real, p.imag);
559 if (errno == EDOM) {
560 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561 "0.0 to a negative or complex power");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000562 return NULL;
563 }
Tim Petersbab22be2002-03-22 02:48:46 +0000564 else if (errno == ERANGE) {
565 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000566 "complex exponentiation");
Tim Petersbab22be2002-03-22 02:48:46 +0000567 return NULL;
568 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000573complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000574{
Guido van Rossum46334cd2007-08-01 17:43:15 +0000575 PyErr_SetString(PyExc_TypeError,
576 "can't take floor of complex number.");
Guido van Rossum4668b002001-08-08 05:00:18 +0000577 return NULL;
578}
579
580static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000581complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000582{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000583 Py_complex neg;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000584 neg.real = -v->cval.real;
585 neg.imag = -v->cval.imag;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000587}
588
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000589static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000590complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000591{
Tim Peters2400fa42001-09-12 19:12:49 +0000592 if (PyComplex_CheckExact(v)) {
593 Py_INCREF(v);
594 return (PyObject *)v;
595 }
596 else
597 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000598}
599
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000600static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000601complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000602{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000603 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000604
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000605 PyFPE_START_PROTECT("complex_abs", return 0)
Christian Heimes53876d92008-04-19 00:31:39 +0000606 result = c_abs(v->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000607 PyFPE_END_PROTECT(result)
Christian Heimes53876d92008-04-19 00:31:39 +0000608
609 if (errno == ERANGE) {
610 PyErr_SetString(PyExc_OverflowError,
611 "absolute value too large");
612 return NULL;
613 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000614 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000615}
616
617static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000618complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000619{
Guido van Rossum3bbef601999-01-25 19:42:19 +0000620 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000621}
622
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000624complex_richcompare(PyObject *v, PyObject *w, int op)
625{
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000626 PyObject *res;
Guido van Rossum18a67ba2006-08-21 18:27:07 +0000627 Py_complex i, j;
Christian Heimes587c2bf2008-01-19 16:21:02 +0000628 TO_COMPLEX(v, i);
629 TO_COMPLEX(w, j);
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000630
Guido van Rossum22056422001-09-24 17:52:04 +0000631 if (op != Py_EQ && op != Py_NE) {
Guido van Rossum18a67ba2006-08-21 18:27:07 +0000632 /* XXX Should eventually return NotImplemented */
Guido van Rossum22056422001-09-24 17:52:04 +0000633 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger5d01aa42004-12-19 20:45:20 +0000634 "no ordering relation is defined for complex numbers");
Guido van Rossum22056422001-09-24 17:52:04 +0000635 return NULL;
636 }
637
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000638 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
639 res = Py_True;
640 else
641 res = Py_False;
642
643 Py_INCREF(res);
644 return res;
645}
646
647static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000648complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000649{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000650 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0970dba2003-08-30 23:57:36 +0000651 "can't convert complex to int; use int(abs(z))");
Guido van Rossumd4ab3cd1996-09-11 22:54:37 +0000652 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000653}
654
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000655static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000656complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000657{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000658 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0970dba2003-08-30 23:57:36 +0000659 "can't convert complex to float; use abs(z)");
Guido van Rossumd4ab3cd1996-09-11 22:54:37 +0000660 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000661}
662
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000664complex_conjugate(PyObject *self)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000665{
Guido van Rossum926518b1996-08-19 19:30:45 +0000666 Py_complex c;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 c = ((PyComplexObject *)self)->cval;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000668 c.imag = -c.imag;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000670}
671
Guido van Rossum46334cd2007-08-01 17:43:15 +0000672PyDoc_STRVAR(complex_conjugate_doc,
673"complex.conjugate() -> complex\n"
674"\n"
675"Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
676
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000677static PyObject *
678complex_getnewargs(PyComplexObject *v)
679{
Georg Brandl0c77a822008-06-10 16:37:50 +0000680 Py_complex c = v->cval;
681 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000682}
683
Eric Smith58a42242009-04-30 01:00:33 +0000684PyDoc_STRVAR(complex__format__doc,
685"complex.__format__() -> str\n"
686"\n"
687"Converts to a string according to format_spec.");
688
689static PyObject *
690complex__format__(PyObject* self, PyObject* args)
691{
692 PyObject *format_spec;
693
694 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
695 return NULL;
696 return _PyComplex_FormatAdvanced(self,
697 PyUnicode_AS_UNICODE(format_spec),
698 PyUnicode_GET_SIZE(format_spec));
699}
700
Christian Heimes53876d92008-04-19 00:31:39 +0000701#if 0
702static PyObject *
703complex_is_finite(PyObject *self)
704{
705 Py_complex c;
706 c = ((PyComplexObject *)self)->cval;
707 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
708 Py_IS_FINITE(c.imag)));
709}
710
711PyDoc_STRVAR(complex_is_finite_doc,
712"complex.is_finite() -> bool\n"
713"\n"
714"Returns True if the real and the imaginary part is finite.");
715#endif
716
Guido van Rossumf9fca921996-01-12 00:47:05 +0000717static PyMethodDef complex_methods[] = {
Guido van Rossum46334cd2007-08-01 17:43:15 +0000718 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
719 complex_conjugate_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000720#if 0
721 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
722 complex_is_finite_doc},
723#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000724 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
Eric Smith58a42242009-04-30 01:00:33 +0000725 {"__format__", (PyCFunction)complex__format__,
726 METH_VARARGS, complex__format__doc},
Guido van Rossumf9fca921996-01-12 00:47:05 +0000727 {NULL, NULL} /* sentinel */
728};
729
Guido van Rossum6f799372001-09-20 20:46:19 +0000730static PyMemberDef complex_members[] = {
Guido van Rossumfa2e4c22002-02-08 21:26:07 +0000731 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
Guido van Rossum6f799372001-09-20 20:46:19 +0000732 "the real part of a complex number"},
Guido van Rossumfa2e4c22002-02-08 21:26:07 +0000733 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
Guido van Rossum6f799372001-09-20 20:46:19 +0000734 "the imaginary part of a complex number"},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000735 {0},
736};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739complex_subtype_from_string(PyTypeObject *type, PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000740{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741 const char *s, *start;
742 char *end;
743 double x=0.0, y=0.0, z;
Mark Dickinsonad476da2009-04-23 19:14:16 +0000744 int got_bracket=0;
Guido van Rossum70e36882001-10-25 18:07:22 +0000745 char s_buffer[256];
Martin v. Löwis18e16552006-02-15 17:27:45 +0000746 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000747
Neal Norwitzed2b7392007-08-26 04:51:10 +0000748 if (PyUnicode_Check(v)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000749 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750 PyErr_SetString(PyExc_ValueError,
751 "complex() literal too large to convert");
752 return NULL;
753 }
754 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
755 PyUnicode_GET_SIZE(v),
756 s_buffer,
757 NULL))
758 return NULL;
759 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000760 len = strlen(s);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000761 }
762 else if (PyObject_AsCharBuffer(v, &s, &len)) {
763 PyErr_SetString(PyExc_TypeError,
764 "complex() arg is not a string");
765 return NULL;
766 }
767
768 /* position on first nonblank */
769 start = s;
770 while (*s && isspace(Py_CHARMASK(*s)))
771 s++;
Mark Dickinsonad476da2009-04-23 19:14:16 +0000772 if (*s == '(') {
Guido van Rossumd8faa362007-04-27 19:54:29 +0000773 /* Skip over possible bracket from repr(). */
774 got_bracket = 1;
775 s++;
776 while (*s && isspace(Py_CHARMASK(*s)))
777 s++;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000778 }
779
Mark Dickinson6649fa42009-04-24 13:25:20 +0000780 /* a valid complex string usually takes one of the three forms:
781
782 <float> - real part only
783 <float>j - imaginary part only
784 <float><signed-float>j - real and imaginary parts
785
786 where <float> represents any numeric string that's accepted by the
787 float constructor (including 'nan', 'inf', 'infinity', etc.), and
788 <signed-float> is any string of the form <float> whose first
789 character is '+' or '-'.
790
791 For backwards compatibility, the extra forms
792
793 <float><sign>j
794 <sign>j
795 j
796
797 are also accepted, though support for these forms may be removed from
798 a future version of Python.
799 */
800
801 /* first look for forms starting with <float> */
Mark Dickinson35f1c942009-04-26 14:11:18 +0000802 errno = 0;
Mark Dickinsonad476da2009-04-23 19:14:16 +0000803 z = PyOS_ascii_strtod(s, &end);
Mark Dickinson6649fa42009-04-24 13:25:20 +0000804 if (end == s && errno == ENOMEM)
805 return PyErr_NoMemory();
806 if (errno == ERANGE && fabs(z) >= 1.0)
807 goto overflow;
808
809 if (end != s) {
810 /* all 4 forms starting with <float> land here */
811 s = end;
812 if (*s == '+' || *s == '-') {
813 /* <float><signed-float>j | <float><sign>j */
814 x = z;
Mark Dickinson35f1c942009-04-26 14:11:18 +0000815 errno = 0;
Mark Dickinson6649fa42009-04-24 13:25:20 +0000816 y = PyOS_ascii_strtod(s, &end);
817 if (end == s && errno == ENOMEM)
818 return PyErr_NoMemory();
Mark Dickinsonde8a7102009-04-25 10:11:40 +0000819 if (errno == ERANGE && fabs(y) >= 1.0)
Mark Dickinson6649fa42009-04-24 13:25:20 +0000820 goto overflow;
821 if (end != s)
822 /* <float><signed-float>j */
823 s = end;
824 else {
825 /* <float><sign>j */
826 y = *s == '+' ? 1.0 : -1.0;
827 s++;
828 }
829 if (!(*s == 'j' || *s == 'J'))
830 goto parse_error;
831 s++;
832 }
833 else if (*s == 'j' || *s == 'J') {
834 /* <float>j */
835 s++;
836 y = z;
837 }
838 else
839 /* <float> */
840 x = z;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000842 else {
843 /* not starting with <float>; must be <sign>j or j */
844 if (*s == '+' || *s == '-') {
845 /* <sign>j */
846 y = *s == '+' ? 1.0 : -1.0;
847 s++;
848 }
849 else
850 /* j */
851 y = 1.0;
852 if (!(*s == 'j' || *s == 'J'))
853 goto parse_error;
Mark Dickinsonad476da2009-04-23 19:14:16 +0000854 s++;
Mark Dickinsonad476da2009-04-23 19:14:16 +0000855 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000856
857 /* trailing whitespace and closing bracket */
858 while (*s && isspace(Py_CHARMASK(*s)))
859 s++;
Mark Dickinson6649fa42009-04-24 13:25:20 +0000860 if (got_bracket) {
861 /* if there was an opening parenthesis, then the corresponding
862 closing parenthesis should be right here */
863 if (*s != ')')
864 goto parse_error;
Mark Dickinsonad476da2009-04-23 19:14:16 +0000865 s++;
866 while (*s && isspace(Py_CHARMASK(*s)))
Mark Dickinson6649fa42009-04-24 13:25:20 +0000867 s++;
Mark Dickinsonad476da2009-04-23 19:14:16 +0000868 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000869
Mark Dickinsonad476da2009-04-23 19:14:16 +0000870 /* we should now be at the end of the string */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000871 if (s-start != len)
872 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000873
874 return complex_subtype_from_doubles(type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000875
Mark Dickinson6649fa42009-04-24 13:25:20 +0000876 parse_error:
Mark Dickinsonad476da2009-04-23 19:14:16 +0000877 PyErr_SetString(PyExc_ValueError,
878 "complex() arg is a malformed string");
879 return NULL;
Mark Dickinson6649fa42009-04-24 13:25:20 +0000880
881 overflow:
882 PyErr_SetString(PyExc_OverflowError,
883 "complex() arg overflow");
884 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000885}
886
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887static PyObject *
888complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
889{
Raymond Hettinger478d47a2002-06-06 15:45:38 +0000890 PyObject *r, *i, *tmp, *f;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000891 PyNumberMethods *nbr, *nbi = NULL;
892 Py_complex cr, ci;
893 int own_r = 0;
Christian Heimes69a79632007-11-28 10:04:30 +0000894 int cr_is_complex = 0;
895 int ci_is_complex = 0;
Raymond Hettinger478d47a2002-06-06 15:45:38 +0000896 static PyObject *complexstr;
Martin v. Löwis15e62742006-02-27 16:46:16 +0000897 static char *kwlist[] = {"real", "imag", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +0000898
899 r = Py_False;
900 i = NULL;
901 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
902 &r, &i))
903 return NULL;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000904
Guido van Rossumd8faa362007-04-27 19:54:29 +0000905 /* Special-case for a single argument when type(arg) is complex. */
Guido van Rossum4eadfa22003-03-02 13:51:47 +0000906 if (PyComplex_CheckExact(r) && i == NULL &&
907 type == &PyComplex_Type) {
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000908 /* Note that we can't know whether it's safe to return
909 a complex *subclass* instance as-is, hence the restriction
Guido van Rossumd8faa362007-04-27 19:54:29 +0000910 to exact complexes here. If either the input or the
911 output is a complex subclass, it will be handled below
912 as a non-orthogonal vector. */
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000913 Py_INCREF(r);
914 return r;
915 }
Neal Norwitzed2b7392007-08-26 04:51:10 +0000916 if (PyUnicode_Check(r)) {
Fred Drake526c7a02001-12-13 19:52:22 +0000917 if (i != NULL) {
918 PyErr_SetString(PyExc_TypeError,
919 "complex() can't take second arg"
920 " if first is a string");
921 return NULL;
Christian Heimes587c2bf2008-01-19 16:21:02 +0000922 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000923 return complex_subtype_from_string(type, r);
Fred Drake526c7a02001-12-13 19:52:22 +0000924 }
Neal Norwitzed2b7392007-08-26 04:51:10 +0000925 if (i != NULL && PyUnicode_Check(i)) {
Fred Drake526c7a02001-12-13 19:52:22 +0000926 PyErr_SetString(PyExc_TypeError,
927 "complex() second arg can't be a string");
928 return NULL;
929 }
Tim Peters2400fa42001-09-12 19:12:49 +0000930
Raymond Hettinger478d47a2002-06-06 15:45:38 +0000931 /* XXX Hack to support classes with __complex__ method */
932 if (complexstr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000933 complexstr = PyUnicode_InternFromString("__complex__");
Raymond Hettinger478d47a2002-06-06 15:45:38 +0000934 if (complexstr == NULL)
935 return NULL;
936 }
937 f = PyObject_GetAttr(r, complexstr);
938 if (f == NULL)
939 PyErr_Clear();
940 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000941 PyObject *args = PyTuple_New(0);
Raymond Hettinger478d47a2002-06-06 15:45:38 +0000942 if (args == NULL)
943 return NULL;
944 r = PyEval_CallObject(f, args);
945 Py_DECREF(args);
946 Py_DECREF(f);
947 if (r == NULL)
948 return NULL;
949 own_r = 1;
950 }
Tim Peters2400fa42001-09-12 19:12:49 +0000951 nbr = r->ob_type->tp_as_number;
952 if (i != NULL)
953 nbi = i->ob_type->tp_as_number;
954 if (nbr == NULL || nbr->nb_float == NULL ||
955 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000956 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger478d47a2002-06-06 15:45:38 +0000957 "complex() argument must be a string or a number");
Tim Peters465fa3d2003-08-15 01:16:37 +0000958 if (own_r) {
959 Py_DECREF(r);
960 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000961 return NULL;
962 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000963
964 /* If we get this far, then the "real" and "imag" parts should
965 both be treated as numbers, and the constructor should return a
966 complex number equal to (real + imag*1j).
967
968 Note that we do NOT assume the input to already be in canonical
969 form; the "real" and "imag" parts might themselves be complex
970 numbers, which slightly complicates the code below. */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971 if (PyComplex_Check(r)) {
Tim Peters2400fa42001-09-12 19:12:49 +0000972 /* Note that if r is of a complex subtype, we're only
973 retaining its real & imag parts here, and the return
974 value is (properly) of the builtin complex type. */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000975 cr = ((PyComplexObject*)r)->cval;
Christian Heimes69a79632007-11-28 10:04:30 +0000976 cr_is_complex = 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977 if (own_r) {
978 Py_DECREF(r);
979 }
980 }
981 else {
Guido van Rossumd8faa362007-04-27 19:54:29 +0000982 /* The "real" part really is entirely real, and contributes
983 nothing in the imaginary direction.
984 Just treat it as a double. */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985 tmp = PyNumber_Float(r);
986 if (own_r) {
Guido van Rossumd8faa362007-04-27 19:54:29 +0000987 /* r was a newly created complex number, rather
988 than the original "real" argument. */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000989 Py_DECREF(r);
990 }
991 if (tmp == NULL)
992 return NULL;
993 if (!PyFloat_Check(tmp)) {
994 PyErr_SetString(PyExc_TypeError,
995 "float(r) didn't return a float");
996 Py_DECREF(tmp);
997 return NULL;
998 }
999 cr.real = PyFloat_AsDouble(tmp);
Christian Heimes587c2bf2008-01-19 16:21:02 +00001000 cr.imag = 0.0; /* Shut up compiler warning */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001 Py_DECREF(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001002 }
1003 if (i == NULL) {
1004 ci.real = 0.0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001005 }
Christian Heimes69a79632007-11-28 10:04:30 +00001006 else if (PyComplex_Check(i)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001007 ci = ((PyComplexObject*)i)->cval;
Christian Heimes69a79632007-11-28 10:04:30 +00001008 ci_is_complex = 1;
1009 } else {
Guido van Rossumd8faa362007-04-27 19:54:29 +00001010 /* The "imag" part really is entirely imaginary, and
1011 contributes nothing in the real direction.
1012 Just treat it as a double. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001013 tmp = (*nbi->nb_float)(i);
1014 if (tmp == NULL)
1015 return NULL;
1016 ci.real = PyFloat_AsDouble(tmp);
1017 Py_DECREF(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001018 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001019 /* If the input was in canonical form, then the "real" and "imag"
Christian Heimes69a79632007-11-28 10:04:30 +00001020 parts are real numbers, so that ci.imag and cr.imag are zero.
Guido van Rossumd8faa362007-04-27 19:54:29 +00001021 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001022
1023 if (ci_is_complex) {
1024 cr.real -= ci.imag;
1025 }
1026 if (cr_is_complex) {
1027 ci.real += cr.imag;
1028 }
1029 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030}
1031
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001032PyDoc_STRVAR(complex_doc,
Tim Peters2400fa42001-09-12 19:12:49 +00001033"complex(real[, imag]) -> complex number\n"
1034"\n"
1035"Create a complex number from a real part and an optional imaginary part.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001036"This is equivalent to (real + imag*1j) where imag defaults to 0.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001038static PyNumberMethods complex_as_number = {
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001039 (binaryfunc)complex_add, /* nb_add */
1040 (binaryfunc)complex_sub, /* nb_subtract */
1041 (binaryfunc)complex_mul, /* nb_multiply */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001042 (binaryfunc)complex_remainder, /* nb_remainder */
1043 (binaryfunc)complex_divmod, /* nb_divmod */
1044 (ternaryfunc)complex_pow, /* nb_power */
1045 (unaryfunc)complex_neg, /* nb_negative */
1046 (unaryfunc)complex_pos, /* nb_positive */
1047 (unaryfunc)complex_abs, /* nb_absolute */
Jack Diederich4dafcc42006-11-28 19:15:13 +00001048 (inquiry)complex_bool, /* nb_bool */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001049 0, /* nb_invert */
1050 0, /* nb_lshift */
1051 0, /* nb_rshift */
1052 0, /* nb_and */
1053 0, /* nb_xor */
1054 0, /* nb_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001055 complex_int, /* nb_int */
Mark Dickinson8055afd2009-01-17 10:04:45 +00001056 0, /* nb_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001057 complex_float, /* nb_float */
Guido van Rossum4668b002001-08-08 05:00:18 +00001058 0, /* nb_inplace_add */
1059 0, /* nb_inplace_subtract */
1060 0, /* nb_inplace_multiply*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001061 0, /* nb_inplace_remainder */
1062 0, /* nb_inplace_power */
1063 0, /* nb_inplace_lshift */
1064 0, /* nb_inplace_rshift */
1065 0, /* nb_inplace_and */
1066 0, /* nb_inplace_xor */
1067 0, /* nb_inplace_or */
1068 (binaryfunc)complex_int_div, /* nb_floor_divide */
1069 (binaryfunc)complex_div, /* nb_true_divide */
1070 0, /* nb_inplace_floor_divide */
1071 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001072};
1073
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001074PyTypeObject PyComplex_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001075 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumf9fca921996-01-12 00:47:05 +00001076 "complex",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001077 sizeof(PyComplexObject),
Guido van Rossumf9fca921996-01-12 00:47:05 +00001078 0,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001079 complex_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001080 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001081 0, /* tp_getattr */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001082 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001083 0, /* tp_reserved */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001084 (reprfunc)complex_repr, /* tp_repr */
1085 &complex_as_number, /* tp_as_number */
1086 0, /* tp_as_sequence */
1087 0, /* tp_as_mapping */
1088 (hashfunc)complex_hash, /* tp_hash */
1089 0, /* tp_call */
Tim Peters70695122001-03-11 08:37:29 +00001090 (reprfunc)complex_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001091 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001092 0, /* tp_setattro */
1093 0, /* tp_as_buffer */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001094 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1095 complex_doc, /* tp_doc */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001096 0, /* tp_traverse */
1097 0, /* tp_clear */
1098 complex_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001099 0, /* tp_weaklistoffset */
1100 0, /* tp_iter */
1101 0, /* tp_iternext */
1102 complex_methods, /* tp_methods */
1103 complex_members, /* tp_members */
1104 0, /* tp_getset */
1105 0, /* tp_base */
1106 0, /* tp_dict */
1107 0, /* tp_descr_get */
1108 0, /* tp_descr_set */
1109 0, /* tp_dictoffset */
1110 0, /* tp_init */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001111 PyType_GenericAlloc, /* tp_alloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001112 complex_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00001113 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001114};
1115
1116#endif