blob: 894f7966a4b9c3691cbe9dc33de4a7533e0e586c [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
Neal Norwitz9fdfaaf2008-03-28 05:34:59 +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
Tim Peters70695122001-03-11 08:37:29 +000017/* Precisions used by repr() and str(), respectively.
18
19 The repr() precision (17 significant decimal digits) is the minimal number
20 that is guaranteed to have enough precision so that if the number is read
21 back in the exact same binary value is recreated. This is true for IEEE
22 floating point by design, and also happens to work for all other modern
23 hardware.
24
25 The str() precision is chosen so that in most cases, the rounding noise
26 created by various operations is suppressed, while giving plenty of
27 precision for practical use.
28*/
29
30#define PREC_REPR 17
31#define PREC_STR 12
Guido van Rossumf9fca921996-01-12 00:47:05 +000032
33/* elementary operations on complex numbers */
34
Guido van Rossum9e720e31996-07-21 02:31:35 +000035static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000036
Tim Peters0f336042001-03-18 08:21:57 +000037Py_complex
38c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000039{
Guido van Rossum9e720e31996-07-21 02:31:35 +000040 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000041 r.real = a.real + b.real;
42 r.imag = a.imag + b.imag;
43 return r;
44}
45
Tim Peters0f336042001-03-18 08:21:57 +000046Py_complex
47c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000048{
Guido van Rossum9e720e31996-07-21 02:31:35 +000049 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000050 r.real = a.real - b.real;
51 r.imag = a.imag - b.imag;
52 return r;
53}
54
Tim Peters0f336042001-03-18 08:21:57 +000055Py_complex
56c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000057{
Guido van Rossum9e720e31996-07-21 02:31:35 +000058 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000059 r.real = -a.real;
60 r.imag = -a.imag;
61 return r;
62}
63
Tim Peters0f336042001-03-18 08:21:57 +000064Py_complex
65c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000066{
Guido van Rossum9e720e31996-07-21 02:31:35 +000067 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000068 r.real = a.real*b.real - a.imag*b.imag;
69 r.imag = a.real*b.imag + a.imag*b.real;
70 return r;
71}
72
Tim Peters0f336042001-03-18 08:21:57 +000073Py_complex
74c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000075{
Tim Peters0f336042001-03-18 08:21:57 +000076 /******************************************************************
77 This was the original algorithm. It's grossly prone to spurious
78 overflow and underflow errors. It also merrily divides by 0 despite
79 checking for that(!). The code still serves a doc purpose here, as
80 the algorithm following is a simple by-cases transformation of this
81 one:
82
Guido van Rossum9e720e31996-07-21 02:31:35 +000083 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000084 double d = b.real*b.real + b.imag*b.imag;
85 if (d == 0.)
Guido van Rossum96783941997-05-20 18:21:34 +000086 errno = EDOM;
Guido van Rossumf9fca921996-01-12 00:47:05 +000087 r.real = (a.real*b.real + a.imag*b.imag)/d;
88 r.imag = (a.imag*b.real - a.real*b.imag)/d;
89 return r;
Tim Peters0f336042001-03-18 08:21:57 +000090 ******************************************************************/
91
92 /* This algorithm is better, and is pretty obvious: first divide the
93 * numerators and denominator by whichever of {b.real, b.imag} has
94 * larger magnitude. The earliest reference I found was to CACM
95 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
96 * University). As usual, though, we're still ignoring all IEEE
97 * endcases.
98 */
99 Py_complex r; /* the result */
100 const double abs_breal = b.real < 0 ? -b.real : b.real;
101 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
102
103 if (abs_breal >= abs_bimag) {
104 /* divide tops and bottom by b.real */
105 if (abs_breal == 0.0) {
106 errno = EDOM;
107 r.real = r.imag = 0.0;
108 }
109 else {
110 const double ratio = b.imag / b.real;
111 const double denom = b.real + b.imag * ratio;
112 r.real = (a.real + a.imag * ratio) / denom;
113 r.imag = (a.imag - a.real * ratio) / denom;
114 }
115 }
116 else {
117 /* divide tops and bottom by b.imag */
118 const double ratio = b.real / b.imag;
119 const double denom = b.real * ratio + b.imag;
120 assert(b.imag != 0.0);
121 r.real = (a.real * ratio + a.imag) / denom;
122 r.imag = (a.imag * ratio - a.real) / denom;
123 }
124 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000125}
126
Tim Peters0f336042001-03-18 08:21:57 +0000127Py_complex
128c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000129{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000130 Py_complex r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000131 double vabs,len,at,phase;
132 if (b.real == 0. && b.imag == 0.) {
133 r.real = 1.;
134 r.imag = 0.;
135 }
136 else if (a.real == 0. && a.imag == 0.) {
137 if (b.imag != 0. || b.real < 0.)
Tim Petersbab22be2002-03-22 02:48:46 +0000138 errno = EDOM;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000139 r.real = 0.;
140 r.imag = 0.;
141 }
142 else {
143 vabs = hypot(a.real,a.imag);
144 len = pow(vabs,b.real);
Martin v. Löwis387c5472001-09-06 08:16:17 +0000145 at = atan2(a.imag, a.real);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000146 phase = at*b.real;
147 if (b.imag != 0.0) {
148 len /= exp(at*b.imag);
149 phase += b.imag*log(vabs);
150 }
151 r.real = len*cos(phase);
152 r.imag = len*sin(phase);
153 }
154 return r;
155}
156
Tim Peters0f336042001-03-18 08:21:57 +0000157static Py_complex
158c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000159{
Guido van Rossum926518b1996-08-19 19:30:45 +0000160 Py_complex r, p;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000161 long mask = 1;
Guido van Rossum926518b1996-08-19 19:30:45 +0000162 r = c_1;
163 p = x;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000164 while (mask > 0 && n >= mask) {
165 if (n & mask)
166 r = c_prod(r,p);
167 mask <<= 1;
168 p = c_prod(p,p);
169 }
170 return r;
171}
172
Tim Peters0f336042001-03-18 08:21:57 +0000173static Py_complex
174c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000175{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000176 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000177
178 if (n > 100 || n < -100) {
179 cn.real = (double) n;
180 cn.imag = 0.;
181 return c_pow(x,cn);
182 }
183 else if (n > 0)
184 return c_powu(x,n);
185 else
186 return c_quot(c_1,c_powu(x,-n));
187
188}
189
Christian Heimes6f341092008-04-18 23:13:07 +0000190double
191c_abs(Py_complex z)
192{
193 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
194 double result;
195
196 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
197 /* C99 rules: if either the real or the imaginary part is an
198 infinity, return infinity, even if the other part is a
199 NaN. */
200 if (Py_IS_INFINITY(z.real)) {
201 result = fabs(z.real);
202 errno = 0;
203 return result;
204 }
205 if (Py_IS_INFINITY(z.imag)) {
206 result = fabs(z.imag);
207 errno = 0;
208 return result;
209 }
210 /* either the real or imaginary part is a NaN,
211 and neither is infinite. Result should be NaN. */
212 return Py_NAN;
213 }
214 result = hypot(z.real, z.imag);
215 if (!Py_IS_FINITE(result))
216 errno = ERANGE;
217 else
218 errno = 0;
219 return result;
220}
221
Tim Peters6d6c1a32001-08-02 04:15:00 +0000222static PyObject *
223complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
224{
225 PyObject *op;
226
Georg Brandl6b50c632006-06-01 08:27:32 +0000227 op = type->tp_alloc(type, 0);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000228 if (op != NULL)
229 ((PyComplexObject *)op)->cval = cval;
230 return op;
231}
232
Guido van Rossumf9fca921996-01-12 00:47:05 +0000233PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000234PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000235{
Guido van Rossumb18618d2000-05-03 23:44:39 +0000236 register PyComplexObject *op;
237
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000238 /* Inline PyObject_New */
Guido van Rossumb18618d2000-05-03 23:44:39 +0000239 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000240 if (op == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000241 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000242 PyObject_INIT(op, &PyComplex_Type);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000243 op->cval = cval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000245}
246
Tim Peters6d6c1a32001-08-02 04:15:00 +0000247static PyObject *
248complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
249{
250 Py_complex c;
251 c.real = real;
252 c.imag = imag;
253 return complex_subtype_from_c_complex(type, c);
254}
255
Guido van Rossumf9fca921996-01-12 00:47:05 +0000256PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000257PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000258{
259 Py_complex c;
260 c.real = real;
261 c.imag = imag;
262 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000263}
264
265double
Fred Drake4288c802000-07-09 04:36:04 +0000266PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000267{
268 if (PyComplex_Check(op)) {
269 return ((PyComplexObject *)op)->cval.real;
Fred Drake4288c802000-07-09 04:36:04 +0000270 }
271 else {
Guido van Rossum926518b1996-08-19 19:30:45 +0000272 return PyFloat_AsDouble(op);
273 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000274}
275
276double
Fred Drake4288c802000-07-09 04:36:04 +0000277PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000278{
279 if (PyComplex_Check(op)) {
280 return ((PyComplexObject *)op)->cval.imag;
Fred Drake4288c802000-07-09 04:36:04 +0000281 }
282 else {
Guido van Rossum926518b1996-08-19 19:30:45 +0000283 return 0.0;
284 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000285}
286
Guido van Rossum9e720e31996-07-21 02:31:35 +0000287Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000288PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000289{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000290 Py_complex cv;
Georg Brandl2b869942007-03-17 16:08:45 +0000291 PyObject *newop = NULL;
292 static PyObject *complex_str = NULL;
293
294 assert(op);
295 /* If op is already of type PyComplex_Type, return its value */
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000296 if (PyComplex_Check(op)) {
297 return ((PyComplexObject *)op)->cval;
Fred Drake4288c802000-07-09 04:36:04 +0000298 }
Georg Brandl2b869942007-03-17 16:08:45 +0000299 /* If not, use op's __complex__ method, if it exists */
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000300
Georg Brandl2b869942007-03-17 16:08:45 +0000301 /* return -1 on failure */
302 cv.real = -1.;
303 cv.imag = 0.;
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000304
305 if (complex_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000306 if (!(complex_str = PyString_InternFromString("__complex__")))
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000307 return cv;
308 }
Georg Brandl2b869942007-03-17 16:08:45 +0000309
310 if (PyInstance_Check(op)) {
311 /* this can go away in python 3000 */
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000312 if (PyObject_HasAttr(op, complex_str)) {
Georg Brandl2b869942007-03-17 16:08:45 +0000313 newop = PyObject_CallMethod(op, "__complex__", NULL);
314 if (!newop)
315 return cv;
316 }
317 /* else try __float__ */
318 } else {
319 PyObject *complexfunc;
Georg Brandl2b869942007-03-17 16:08:45 +0000320 complexfunc = _PyType_Lookup(op->ob_type, complex_str);
321 /* complexfunc is a borrowed reference */
322 if (complexfunc) {
323 newop = PyObject_CallFunctionObjArgs(complexfunc, op, NULL);
324 if (!newop)
325 return cv;
326 }
327 }
328
329 if (newop) {
330 if (!PyComplex_Check(newop)) {
331 PyErr_SetString(PyExc_TypeError,
332 "__complex__ should return a complex object");
333 Py_DECREF(newop);
334 return cv;
335 }
336 cv = ((PyComplexObject *)newop)->cval;
337 Py_DECREF(newop);
338 return cv;
339 }
340 /* If neither of the above works, interpret op as a float giving the
341 real part of the result, and fill in the imaginary part as 0. */
Fred Drake4288c802000-07-09 04:36:04 +0000342 else {
Georg Brandl2b869942007-03-17 16:08:45 +0000343 /* PyFloat_AsDouble will return -1 on failure */
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000344 cv.real = PyFloat_AsDouble(op);
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000345 return cv;
Tim Peters70695122001-03-11 08:37:29 +0000346 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000347}
348
Guido van Rossumf9fca921996-01-12 00:47:05 +0000349static void
Fred Drake4288c802000-07-09 04:36:04 +0000350complex_dealloc(PyObject *op)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000351{
Guido van Rossum9475a232001-10-05 20:51:39 +0000352 op->ob_type->tp_free(op);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000353}
354
355
Mark Dickinson95bc9802009-04-24 12:46:53 +0000356static PyObject *
357complex_format(PyComplexObject *v, char format_code)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000358{
Mark Dickinson95bc9802009-04-24 12:46:53 +0000359 PyObject *result = NULL;
360 Py_ssize_t len;
361
362 /* If these are non-NULL, they'll need to be freed. */
363 char *pre = NULL;
364 char *im = NULL;
365 char *buf = NULL;
366
367 /* These do not need to be freed. re is either an alias
368 for pre or a pointer to a constant. lead and tail
369 are pointers to constants. */
370 char *re = NULL;
371 char *lead = "";
372 char *tail = "";
373
374 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
375 re = "";
376 im = PyOS_double_to_string(v->cval.imag, format_code,
377 0, 0, NULL);
378 if (!im) {
379 PyErr_NoMemory();
380 goto done;
Christian Heimes2f0da532008-02-15 06:57:08 +0000381 }
Martin v. Löwis737ea822004-06-08 18:52:54 +0000382 } else {
Georg Brandlc404ff22005-09-16 06:42:26 +0000383 /* Format imaginary part with sign, real part without */
Mark Dickinson95bc9802009-04-24 12:46:53 +0000384 pre = PyOS_double_to_string(v->cval.real, format_code,
385 0, 0, NULL);
386 if (!pre) {
387 PyErr_NoMemory();
388 goto done;
Christian Heimes2f0da532008-02-15 06:57:08 +0000389 }
Mark Dickinson95bc9802009-04-24 12:46:53 +0000390 re = pre;
391
392 im = PyOS_double_to_string(v->cval.imag, format_code,
393 0, Py_DTSF_SIGN, NULL);
394 if (!im) {
395 PyErr_NoMemory();
396 goto done;
Christian Heimes2f0da532008-02-15 06:57:08 +0000397 }
Mark Dickinson95bc9802009-04-24 12:46:53 +0000398 lead = "(";
399 tail = ")";
Martin v. Löwis737ea822004-06-08 18:52:54 +0000400 }
Mark Dickinson95bc9802009-04-24 12:46:53 +0000401 /* Alloc the final buffer. Add one for the "j" in the format string,
402 and one for the trailing zero. */
403 len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
404 buf = PyMem_Malloc(len);
405 if (!buf) {
406 PyErr_NoMemory();
407 goto done;
408 }
409 PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
410 result = PyString_FromString(buf);
411 done:
412 PyMem_Free(im);
413 PyMem_Free(pre);
414 PyMem_Free(buf);
415
416 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000417}
418
419static int
Fred Drake4288c802000-07-09 04:36:04 +0000420complex_print(PyComplexObject *v, FILE *fp, int flags)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000421{
Mark Dickinson95bc9802009-04-24 12:46:53 +0000422 PyObject *formatv;
423 char *buf;
424 formatv = complex_format(v, (flags & Py_PRINT_RAW) ? 's' : 'r');
425 if (formatv == NULL)
426 return -1;
427 buf = PyString_AS_STRING(formatv);
Brett Cannon01531592007-09-17 03:28:34 +0000428 Py_BEGIN_ALLOW_THREADS
Guido van Rossumf9fca921996-01-12 00:47:05 +0000429 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000430 Py_END_ALLOW_THREADS
Mark Dickinson95bc9802009-04-24 12:46:53 +0000431 Py_DECREF(formatv);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000432 return 0;
433}
434
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000435static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000436complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000437{
Mark Dickinson95bc9802009-04-24 12:46:53 +0000438 return complex_format(v, 'r');
Tim Peters70695122001-03-11 08:37:29 +0000439}
440
441static PyObject *
442complex_str(PyComplexObject *v)
443{
Mark Dickinson95bc9802009-04-24 12:46:53 +0000444 return complex_format(v, 's');
Guido van Rossumf9fca921996-01-12 00:47:05 +0000445}
446
Guido van Rossumf9fca921996-01-12 00:47:05 +0000447static long
Fred Drake4288c802000-07-09 04:36:04 +0000448complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000449{
Tim Peters39dce292000-08-15 03:34:48 +0000450 long hashreal, hashimag, combined;
451 hashreal = _Py_HashDouble(v->cval.real);
452 if (hashreal == -1)
453 return -1;
454 hashimag = _Py_HashDouble(v->cval.imag);
455 if (hashimag == -1)
456 return -1;
457 /* Note: if the imaginary part is 0, hashimag is 0 now,
458 * so the following returns hashreal unchanged. This is
459 * important because numbers of different types that
460 * compare equal must have the same hash value, so that
461 * hash(x + 0*j) must equal hash(x).
462 */
463 combined = hashreal + 1000003 * hashimag;
464 if (combined == -1)
465 combined = -2;
466 return combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000467}
468
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000469/* This macro may return! */
470#define TO_COMPLEX(obj, c) \
471 if (PyComplex_Check(obj)) \
472 c = ((PyComplexObject *)(obj))->cval; \
473 else if (to_complex(&(obj), &(c)) < 0) \
474 return (obj)
475
476static int
477to_complex(PyObject **pobj, Py_complex *pc)
478{
479 PyObject *obj = *pobj;
480
481 pc->real = pc->imag = 0.0;
482 if (PyInt_Check(obj)) {
483 pc->real = PyInt_AS_LONG(obj);
484 return 0;
485 }
486 if (PyLong_Check(obj)) {
487 pc->real = PyLong_AsDouble(obj);
488 if (pc->real == -1.0 && PyErr_Occurred()) {
489 *pobj = NULL;
490 return -1;
491 }
492 return 0;
493 }
494 if (PyFloat_Check(obj)) {
495 pc->real = PyFloat_AsDouble(obj);
496 return 0;
497 }
498 Py_INCREF(Py_NotImplemented);
499 *pobj = Py_NotImplemented;
500 return -1;
501}
502
503
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000505complex_add(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000506{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000507 Py_complex result;
508 PyFPE_START_PROTECT("complex_add", return 0)
509 result = c_sum(v->cval,w->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000510 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000512}
513
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000515complex_sub(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000516{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000517 Py_complex result;
518 PyFPE_START_PROTECT("complex_sub", return 0)
519 result = c_diff(v->cval,w->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000520 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000521 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000522}
523
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000524static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000525complex_mul(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000526{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000527 Py_complex result;
528 PyFPE_START_PROTECT("complex_mul", return 0)
529 result = c_prod(v->cval,w->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000530 PyFPE_END_PROTECT(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000531 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000532}
533
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000534static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000535complex_div(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000536{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000537 Py_complex quot;
Christian Heimes6f341092008-04-18 23:13:07 +0000538
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000539 PyFPE_START_PROTECT("complex_div", return 0)
Guido van Rossum96783941997-05-20 18:21:34 +0000540 errno = 0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000541 quot = c_quot(v->cval,w->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000542 PyFPE_END_PROTECT(quot)
Guido van Rossum96783941997-05-20 18:21:34 +0000543 if (errno == EDOM) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000545 return NULL;
546 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000548}
549
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000551complex_classic_div(PyComplexObject *v, PyComplexObject *w)
552{
553 Py_complex quot;
554
Guido van Rossum1832de42001-09-04 03:51:09 +0000555 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000556 PyErr_Warn(PyExc_DeprecationWarning,
557 "classic complex division") < 0)
558 return NULL;
559
560 PyFPE_START_PROTECT("complex_classic_div", return 0)
561 errno = 0;
562 quot = c_quot(v->cval,w->cval);
563 PyFPE_END_PROTECT(quot)
564 if (errno == EDOM) {
565 PyErr_SetString(PyExc_ZeroDivisionError, "complex division");
566 return NULL;
567 }
568 return PyComplex_FromCComplex(quot);
569}
570
571static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000572complex_remainder(PyComplexObject *v, PyComplexObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000573{
Georg Brandl96f21842008-01-19 10:18:07 +0000574 Py_complex div, mod;
Guido van Rossum69cf3c72002-04-15 12:39:12 +0000575
576 if (PyErr_Warn(PyExc_DeprecationWarning,
577 "complex divmod(), // and % are deprecated") < 0)
578 return NULL;
579
Guido van Rossum96783941997-05-20 18:21:34 +0000580 errno = 0;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000581 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
Guido van Rossum96783941997-05-20 18:21:34 +0000582 if (errno == EDOM) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583 PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
Guido van Rossum3be12e91996-09-12 20:56:18 +0000584 return NULL;
585 }
586 div.real = floor(div.real); /* Use the floor of the real part. */
587 div.imag = 0.0;
588 mod = c_diff(v->cval, c_prod(w->cval, div));
589
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000590 return PyComplex_FromCComplex(mod);
Guido van Rossumee09fc11996-09-11 13:55:55 +0000591}
592
Guido van Rossumee09fc11996-09-11 13:55:55 +0000593
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000594static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000595complex_divmod(PyComplexObject *v, PyComplexObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000596{
Georg Brandl96f21842008-01-19 10:18:07 +0000597 Py_complex div, mod;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000598 PyObject *d, *m, *z;
Guido van Rossum9ec4c782002-04-15 01:41:56 +0000599
600 if (PyErr_Warn(PyExc_DeprecationWarning,
Guido van Rossum69cf3c72002-04-15 12:39:12 +0000601 "complex divmod(), // and % are deprecated") < 0)
Guido van Rossum9ec4c782002-04-15 01:41:56 +0000602 return NULL;
603
Guido van Rossum96783941997-05-20 18:21:34 +0000604 errno = 0;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000605 div = c_quot(v->cval,w->cval); /* The raw divisor value. */
Guido van Rossum96783941997-05-20 18:21:34 +0000606 if (errno == EDOM) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000607 PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
Guido van Rossum3be12e91996-09-12 20:56:18 +0000608 return NULL;
609 }
610 div.real = floor(div.real); /* Use the floor of the real part. */
611 div.imag = 0.0;
612 mod = c_diff(v->cval, c_prod(w->cval, div));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613 d = PyComplex_FromCComplex(div);
614 m = PyComplex_FromCComplex(mod);
Raymond Hettinger8ae46892003-10-12 19:09:37 +0000615 z = PyTuple_Pack(2, d, m);
Guido van Rossum3be12e91996-09-12 20:56:18 +0000616 Py_XDECREF(d);
617 Py_XDECREF(m);
618 return z;
619}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000620
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000621static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000622complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000623{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000624 Py_complex p;
625 Py_complex exponent;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000626 long int_exponent;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000627 Py_complex a, b;
Georg Brandl96f21842008-01-19 10:18:07 +0000628 TO_COMPLEX(v, a);
629 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000630
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000631 if (z!=Py_None) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000632 PyErr_SetString(PyExc_ValueError, "complex modulo");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000633 return NULL;
634 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000635 PyFPE_START_PROTECT("complex_pow", return 0)
Guido van Rossum96783941997-05-20 18:21:34 +0000636 errno = 0;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000637 exponent = b;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000638 int_exponent = (long)exponent.real;
639 if (exponent.imag == 0. && exponent.real == int_exponent)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000640 p = c_powi(a,int_exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000641 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000642 p = c_pow(a,exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000643
Guido van Rossum45b83911997-03-14 04:32:50 +0000644 PyFPE_END_PROTECT(p)
Tim Petersbab22be2002-03-22 02:48:46 +0000645 Py_ADJUST_ERANGE2(p.real, p.imag);
646 if (errno == EDOM) {
647 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000648 "0.0 to a negative or complex power");
Guido van Rossumf9fca921996-01-12 00:47:05 +0000649 return NULL;
650 }
Tim Petersbab22be2002-03-22 02:48:46 +0000651 else if (errno == ERANGE) {
652 PyErr_SetString(PyExc_OverflowError,
Neal Norwitz0593de32007-03-09 05:59:01 +0000653 "complex exponentiation");
Tim Petersbab22be2002-03-22 02:48:46 +0000654 return NULL;
655 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000656 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000657}
658
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659static PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +0000660complex_int_div(PyComplexObject *v, PyComplexObject *w)
661{
662 PyObject *t, *r;
663
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000664 if (PyErr_Warn(PyExc_DeprecationWarning,
665 "complex divmod(), // and % are deprecated") < 0)
666 return NULL;
667
Guido van Rossum4668b002001-08-08 05:00:18 +0000668 t = complex_divmod(v, w);
669 if (t != NULL) {
670 r = PyTuple_GET_ITEM(t, 0);
671 Py_INCREF(r);
672 Py_DECREF(t);
673 return r;
674 }
675 return NULL;
676}
677
678static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000679complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000680{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000681 Py_complex neg;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000682 neg.real = -v->cval.real;
683 neg.imag = -v->cval.imag;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000684 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000685}
686
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000687static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000688complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000689{
Tim Peters2400fa42001-09-12 19:12:49 +0000690 if (PyComplex_CheckExact(v)) {
691 Py_INCREF(v);
692 return (PyObject *)v;
693 }
694 else
695 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000696}
697
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000698static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000699complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000700{
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000701 double result;
Christian Heimes6f341092008-04-18 23:13:07 +0000702
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000703 PyFPE_START_PROTECT("complex_abs", return 0)
Christian Heimes6f341092008-04-18 23:13:07 +0000704 result = c_abs(v->cval);
Guido van Rossum45b83911997-03-14 04:32:50 +0000705 PyFPE_END_PROTECT(result)
Christian Heimes6f341092008-04-18 23:13:07 +0000706
707 if (errno == ERANGE) {
708 PyErr_SetString(PyExc_OverflowError,
709 "absolute value too large");
710 return NULL;
711 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000712 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000713}
714
715static int
Fred Drake4288c802000-07-09 04:36:04 +0000716complex_nonzero(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000717{
Guido van Rossum3bbef601999-01-25 19:42:19 +0000718 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000719}
720
721static int
Fred Drake4288c802000-07-09 04:36:04 +0000722complex_coerce(PyObject **pv, PyObject **pw)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000723{
Guido van Rossum9e720e31996-07-21 02:31:35 +0000724 Py_complex cval;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000725 cval.imag = 0.;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000726 if (PyInt_Check(*pw)) {
727 cval.real = (double)PyInt_AsLong(*pw);
728 *pw = PyComplex_FromCComplex(cval);
729 Py_INCREF(*pv);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000730 return 0;
731 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000732 else if (PyLong_Check(*pw)) {
733 cval.real = PyLong_AsDouble(*pw);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000734 if (cval.real == -1.0 && PyErr_Occurred())
735 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736 *pw = PyComplex_FromCComplex(cval);
737 Py_INCREF(*pv);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000738 return 0;
739 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740 else if (PyFloat_Check(*pw)) {
741 cval.real = PyFloat_AsDouble(*pw);
742 *pw = PyComplex_FromCComplex(cval);
743 Py_INCREF(*pv);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000744 return 0;
745 }
Guido van Rossum63805962001-09-19 01:13:10 +0000746 else if (PyComplex_Check(*pw)) {
747 Py_INCREF(*pv);
748 Py_INCREF(*pw);
749 return 0;
750 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000751 return 1; /* Can't do it */
752}
753
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000755complex_richcompare(PyObject *v, PyObject *w, int op)
756{
757 int c;
758 Py_complex i, j;
759 PyObject *res;
760
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000761 c = PyNumber_CoerceEx(&v, &w);
762 if (c < 0)
763 return NULL;
764 if (c > 0) {
765 Py_INCREF(Py_NotImplemented);
766 return Py_NotImplemented;
767 }
Guido van Rossum2ed6bf82001-09-27 20:30:07 +0000768 /* Make sure both arguments are complex. */
769 if (!(PyComplex_Check(v) && PyComplex_Check(w))) {
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000770 Py_DECREF(v);
771 Py_DECREF(w);
772 Py_INCREF(Py_NotImplemented);
773 return Py_NotImplemented;
774 }
775
776 i = ((PyComplexObject *)v)->cval;
777 j = ((PyComplexObject *)w)->cval;
778 Py_DECREF(v);
779 Py_DECREF(w);
780
Guido van Rossum22056422001-09-24 17:52:04 +0000781 if (op != Py_EQ && op != Py_NE) {
782 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger5d01aa42004-12-19 20:45:20 +0000783 "no ordering relation is defined for complex numbers");
Guido van Rossum22056422001-09-24 17:52:04 +0000784 return NULL;
785 }
786
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000787 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
788 res = Py_True;
789 else
790 res = Py_False;
791
792 Py_INCREF(res);
793 return res;
794}
795
796static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000797complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000798{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000799 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0970dba2003-08-30 23:57:36 +0000800 "can't convert complex to int; use int(abs(z))");
Guido van Rossumd4ab3cd1996-09-11 22:54:37 +0000801 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000802}
803
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000805complex_long(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000806{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000807 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0970dba2003-08-30 23:57:36 +0000808 "can't convert complex to long; use long(abs(z))");
Guido van Rossumd4ab3cd1996-09-11 22:54:37 +0000809 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000810}
811
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000812static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000813complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000814{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000815 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0970dba2003-08-30 23:57:36 +0000816 "can't convert complex to float; use abs(z)");
Guido van Rossumd4ab3cd1996-09-11 22:54:37 +0000817 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000818}
819
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000820static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000821complex_conjugate(PyObject *self)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000822{
Guido van Rossum926518b1996-08-19 19:30:45 +0000823 Py_complex c;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824 c = ((PyComplexObject *)self)->cval;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000825 c.imag = -c.imag;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000826 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000827}
828
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000829PyDoc_STRVAR(complex_conjugate_doc,
830"complex.conjugate() -> complex\n"
831"\n"
832"Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
833
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000834static PyObject *
835complex_getnewargs(PyComplexObject *v)
836{
Alexandre Vassalotti80af6da2008-06-04 20:41:44 +0000837 Py_complex c = v->cval;
838 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000839}
840
Christian Heimes6f341092008-04-18 23:13:07 +0000841#if 0
842static PyObject *
843complex_is_finite(PyObject *self)
844{
845 Py_complex c;
846 c = ((PyComplexObject *)self)->cval;
847 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
848 Py_IS_FINITE(c.imag)));
849}
850
851PyDoc_STRVAR(complex_is_finite_doc,
852"complex.is_finite() -> bool\n"
853"\n"
854"Returns True if the real and the imaginary part is finite.");
855#endif
856
Guido van Rossumf9fca921996-01-12 00:47:05 +0000857static PyMethodDef complex_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000858 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
859 complex_conjugate_doc},
Christian Heimes6f341092008-04-18 23:13:07 +0000860#if 0
861 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
862 complex_is_finite_doc},
863#endif
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000864 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
Guido van Rossumf9fca921996-01-12 00:47:05 +0000865 {NULL, NULL} /* sentinel */
866};
867
Guido van Rossum6f799372001-09-20 20:46:19 +0000868static PyMemberDef complex_members[] = {
Guido van Rossumfa2e4c22002-02-08 21:26:07 +0000869 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
Guido van Rossum6f799372001-09-20 20:46:19 +0000870 "the real part of a complex number"},
Guido van Rossumfa2e4c22002-02-08 21:26:07 +0000871 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
Guido van Rossum6f799372001-09-20 20:46:19 +0000872 "the imaginary part of a complex number"},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000873 {0},
874};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000875
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000876static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000877complex_subtype_from_string(PyTypeObject *type, PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000878{
Tim Peters6d6c1a32001-08-02 04:15:00 +0000879 const char *s, *start;
880 char *end;
881 double x=0.0, y=0.0, z;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000882 int got_bracket=0;
Guido van Rossum70e36882001-10-25 18:07:22 +0000883#ifdef Py_USING_UNICODE
884 char s_buffer[256];
885#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000886 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000887
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000888 if (PyString_Check(v)) {
889 s = PyString_AS_STRING(v);
890 len = PyString_GET_SIZE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000891 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000892#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +0000893 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000894 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +0000895 PyErr_SetString(PyExc_ValueError,
896 "complex() literal too large to convert");
897 return NULL;
898 }
899 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
900 PyUnicode_GET_SIZE(v),
901 s_buffer,
902 NULL))
903 return NULL;
904 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000905 len = strlen(s);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000906 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000907#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +0000908 else if (PyObject_AsCharBuffer(v, &s, &len)) {
909 PyErr_SetString(PyExc_TypeError,
910 "complex() arg is not a string");
911 return NULL;
912 }
913
Mark Dickinson95bc9802009-04-24 12:46:53 +0000914 errno = 0;
915
Tim Peters6d6c1a32001-08-02 04:15:00 +0000916 /* position on first nonblank */
917 start = s;
918 while (*s && isspace(Py_CHARMASK(*s)))
919 s++;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000920 if (*s == '(') {
Collin Wintere38051d2007-03-09 20:33:07 +0000921 /* Skip over possible bracket from repr(). */
922 got_bracket = 1;
923 s++;
924 while (*s && isspace(Py_CHARMASK(*s)))
925 s++;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000926 }
927
Mark Dickinson95bc9802009-04-24 12:46:53 +0000928 /* a valid complex string usually takes one of the three forms:
Tim Peters6d6c1a32001-08-02 04:15:00 +0000929
Mark Dickinson95bc9802009-04-24 12:46:53 +0000930 <float> - real part only
931 <float>j - imaginary part only
932 <float><signed-float>j - real and imaginary parts
Tim Peters6d6c1a32001-08-02 04:15:00 +0000933
Mark Dickinson95bc9802009-04-24 12:46:53 +0000934 where <float> represents any numeric string that's accepted by the
935 float constructor (including 'nan', 'inf', 'infinity', etc.), and
936 <signed-float> is any string of the form <float> whose first
937 character is '+' or '-'.
Tim Peters6d6c1a32001-08-02 04:15:00 +0000938
Mark Dickinson95bc9802009-04-24 12:46:53 +0000939 For backwards compatibility, the extra forms
940
941 <float><sign>j
942 <sign>j
943 j
944
945 are also accepted, though support for these forms may be removed from
946 a future version of Python.
947 */
948
949 /* first look for forms starting with <float> */
950 z = PyOS_ascii_strtod(s, &end);
951 if (end == s && errno == ENOMEM)
952 return PyErr_NoMemory();
953 if (errno == ERANGE && fabs(z) >= 1.0)
954 goto overflow;
955
956 if (end != s) {
957 /* all 4 forms starting with <float> land here */
958 s = end;
959 if (*s == '+' || *s == '-') {
960 /* <float><signed-float>j | <float><sign>j */
961 x = z;
962 y = PyOS_ascii_strtod(s, &end);
963 if (end == s && errno == ENOMEM)
964 return PyErr_NoMemory();
965 if (errno == ERANGE && fabs(z) >= 1.0)
966 goto overflow;
967 if (end != s)
968 /* <float><signed-float>j */
969 s = end;
970 else {
971 /* <float><sign>j */
972 y = *s == '+' ? 1.0 : -1.0;
Collin Wintere38051d2007-03-09 20:33:07 +0000973 s++;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000974 }
975 if (!(*s == 'j' || *s == 'J'))
976 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000977 s++;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000978 }
979 else if (*s == 'j' || *s == 'J') {
980 /* <float>j */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000981 s++;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000982 y = z;
983 }
984 else
985 /* <float> */
986 x = z;
987 }
988 else {
989 /* not starting with <float>; must be <sign>j or j */
990 if (*s == '+' || *s == '-') {
991 /* <sign>j */
992 y = *s == '+' ? 1.0 : -1.0;
993 s++;
994 }
995 else
996 /* j */
997 y = 1.0;
998 if (!(*s == 'j' || *s == 'J'))
999 goto parse_error;
1000 s++;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001001 }
1002
Mark Dickinson95bc9802009-04-24 12:46:53 +00001003 /* trailing whitespace and closing bracket */
1004 while (*s && isspace(Py_CHARMASK(*s)))
1005 s++;
1006 if (got_bracket) {
1007 /* if there was an opening parenthesis, then the corresponding
1008 closing parenthesis should be right here */
1009 if (*s != ')')
1010 goto parse_error;
1011 s++;
1012 while (*s && isspace(Py_CHARMASK(*s)))
1013 s++;
1014 }
1015
1016 /* we should now be at the end of the string */
1017 if (s-start != len)
1018 goto parse_error;
1019
Tim Peters6d6c1a32001-08-02 04:15:00 +00001020 return complex_subtype_from_doubles(type, x, y);
Mark Dickinson95bc9802009-04-24 12:46:53 +00001021
1022 parse_error:
1023 PyErr_SetString(PyExc_ValueError,
1024 "complex() arg is a malformed string");
1025 return NULL;
1026
1027 overflow:
1028 PyErr_SetString(PyExc_OverflowError,
1029 "complex() arg overflow");
1030
Guido van Rossumf9fca921996-01-12 00:47:05 +00001031}
1032
Tim Peters6d6c1a32001-08-02 04:15:00 +00001033static PyObject *
1034complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1035{
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001036 PyObject *r, *i, *tmp, *f;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001037 PyNumberMethods *nbr, *nbi = NULL;
1038 Py_complex cr, ci;
1039 int own_r = 0;
Guido van Rossum715ec182007-11-27 22:38:36 +00001040 int cr_is_complex = 0;
1041 int ci_is_complex = 0;
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001042 static PyObject *complexstr;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001043 static char *kwlist[] = {"real", "imag", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001044
1045 r = Py_False;
1046 i = NULL;
1047 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
1048 &r, &i))
1049 return NULL;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +00001050
Georg Brandl8f032cb2007-03-13 07:57:51 +00001051 /* Special-case for a single argument when type(arg) is complex. */
Guido van Rossum4eadfa22003-03-02 13:51:47 +00001052 if (PyComplex_CheckExact(r) && i == NULL &&
1053 type == &PyComplex_Type) {
Raymond Hettinger604cd6a2002-08-29 14:22:51 +00001054 /* Note that we can't know whether it's safe to return
1055 a complex *subclass* instance as-is, hence the restriction
Georg Brandl8f032cb2007-03-13 07:57:51 +00001056 to exact complexes here. If either the input or the
1057 output is a complex subclass, it will be handled below
1058 as a non-orthogonal vector. */
Raymond Hettinger604cd6a2002-08-29 14:22:51 +00001059 Py_INCREF(r);
1060 return r;
1061 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001062 if (PyString_Check(r) || PyUnicode_Check(r)) {
Fred Drake526c7a02001-12-13 19:52:22 +00001063 if (i != NULL) {
1064 PyErr_SetString(PyExc_TypeError,
1065 "complex() can't take second arg"
1066 " if first is a string");
1067 return NULL;
Georg Brandl96f21842008-01-19 10:18:07 +00001068 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069 return complex_subtype_from_string(type, r);
Fred Drake526c7a02001-12-13 19:52:22 +00001070 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001071 if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
Fred Drake526c7a02001-12-13 19:52:22 +00001072 PyErr_SetString(PyExc_TypeError,
1073 "complex() second arg can't be a string");
1074 return NULL;
1075 }
Tim Peters2400fa42001-09-12 19:12:49 +00001076
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001077 /* XXX Hack to support classes with __complex__ method */
1078 if (complexstr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001079 complexstr = PyString_InternFromString("__complex__");
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001080 if (complexstr == NULL)
1081 return NULL;
1082 }
1083 f = PyObject_GetAttr(r, complexstr);
1084 if (f == NULL)
1085 PyErr_Clear();
1086 else {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001087 PyObject *args = PyTuple_New(0);
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001088 if (args == NULL)
1089 return NULL;
1090 r = PyEval_CallObject(f, args);
1091 Py_DECREF(args);
1092 Py_DECREF(f);
1093 if (r == NULL)
1094 return NULL;
1095 own_r = 1;
1096 }
Tim Peters2400fa42001-09-12 19:12:49 +00001097 nbr = r->ob_type->tp_as_number;
1098 if (i != NULL)
1099 nbi = i->ob_type->tp_as_number;
1100 if (nbr == NULL || nbr->nb_float == NULL ||
1101 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001102 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger478d47a2002-06-06 15:45:38 +00001103 "complex() argument must be a string or a number");
Tim Peters465fa3d2003-08-15 01:16:37 +00001104 if (own_r) {
1105 Py_DECREF(r);
1106 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001107 return NULL;
1108 }
Georg Brandl8f032cb2007-03-13 07:57:51 +00001109
1110 /* If we get this far, then the "real" and "imag" parts should
1111 both be treated as numbers, and the constructor should return a
1112 complex number equal to (real + imag*1j).
1113
1114 Note that we do NOT assume the input to already be in canonical
1115 form; the "real" and "imag" parts might themselves be complex
1116 numbers, which slightly complicates the code below. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001117 if (PyComplex_Check(r)) {
Tim Peters2400fa42001-09-12 19:12:49 +00001118 /* Note that if r is of a complex subtype, we're only
1119 retaining its real & imag parts here, and the return
1120 value is (properly) of the builtin complex type. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001121 cr = ((PyComplexObject*)r)->cval;
Guido van Rossum715ec182007-11-27 22:38:36 +00001122 cr_is_complex = 1;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001123 if (own_r) {
1124 Py_DECREF(r);
1125 }
1126 }
1127 else {
Georg Brandl8f032cb2007-03-13 07:57:51 +00001128 /* The "real" part really is entirely real, and contributes
1129 nothing in the imaginary direction.
1130 Just treat it as a double. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001131 tmp = PyNumber_Float(r);
1132 if (own_r) {
Georg Brandl8f032cb2007-03-13 07:57:51 +00001133 /* r was a newly created complex number, rather
1134 than the original "real" argument. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001135 Py_DECREF(r);
1136 }
1137 if (tmp == NULL)
1138 return NULL;
1139 if (!PyFloat_Check(tmp)) {
1140 PyErr_SetString(PyExc_TypeError,
1141 "float(r) didn't return a float");
1142 Py_DECREF(tmp);
1143 return NULL;
1144 }
1145 cr.real = PyFloat_AsDouble(tmp);
Georg Brandl96f21842008-01-19 10:18:07 +00001146 cr.imag = 0.0; /* Shut up compiler warning */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001147 Py_DECREF(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001148 }
1149 if (i == NULL) {
1150 ci.real = 0.0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001151 }
Guido van Rossum715ec182007-11-27 22:38:36 +00001152 else if (PyComplex_Check(i)) {
Tim Peters6d6c1a32001-08-02 04:15:00 +00001153 ci = ((PyComplexObject*)i)->cval;
Guido van Rossum715ec182007-11-27 22:38:36 +00001154 ci_is_complex = 1;
1155 } else {
Georg Brandl8f032cb2007-03-13 07:57:51 +00001156 /* The "imag" part really is entirely imaginary, and
1157 contributes nothing in the real direction.
1158 Just treat it as a double. */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001159 tmp = (*nbi->nb_float)(i);
1160 if (tmp == NULL)
1161 return NULL;
1162 ci.real = PyFloat_AsDouble(tmp);
1163 Py_DECREF(tmp);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001164 }
Georg Brandl8f032cb2007-03-13 07:57:51 +00001165 /* If the input was in canonical form, then the "real" and "imag"
Guido van Rossum715ec182007-11-27 22:38:36 +00001166 parts are real numbers, so that ci.imag and cr.imag are zero.
Georg Brandl8f032cb2007-03-13 07:57:51 +00001167 We need this correction in case they were not real numbers. */
Guido van Rossum715ec182007-11-27 22:38:36 +00001168
1169 if (ci_is_complex) {
1170 cr.real -= ci.imag;
1171 }
1172 if (cr_is_complex) {
1173 ci.real += cr.imag;
1174 }
1175 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001176}
1177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001178PyDoc_STRVAR(complex_doc,
Tim Peters2400fa42001-09-12 19:12:49 +00001179"complex(real[, imag]) -> complex number\n"
1180"\n"
1181"Create a complex number from a real part and an optional imaginary part.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001182"This is equivalent to (real + imag*1j) where imag defaults to 0.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001183
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001184static PyNumberMethods complex_as_number = {
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001185 (binaryfunc)complex_add, /* nb_add */
1186 (binaryfunc)complex_sub, /* nb_subtract */
1187 (binaryfunc)complex_mul, /* nb_multiply */
Guido van Rossum393661d2001-08-31 17:40:15 +00001188 (binaryfunc)complex_classic_div, /* nb_divide */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001189 (binaryfunc)complex_remainder, /* nb_remainder */
1190 (binaryfunc)complex_divmod, /* nb_divmod */
1191 (ternaryfunc)complex_pow, /* nb_power */
1192 (unaryfunc)complex_neg, /* nb_negative */
1193 (unaryfunc)complex_pos, /* nb_positive */
1194 (unaryfunc)complex_abs, /* nb_absolute */
1195 (inquiry)complex_nonzero, /* nb_nonzero */
1196 0, /* nb_invert */
1197 0, /* nb_lshift */
1198 0, /* nb_rshift */
1199 0, /* nb_and */
1200 0, /* nb_xor */
1201 0, /* nb_or */
Georg Brandl347b3002006-03-30 11:57:00 +00001202 complex_coerce, /* nb_coerce */
1203 complex_int, /* nb_int */
1204 complex_long, /* nb_long */
1205 complex_float, /* nb_float */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001206 0, /* nb_oct */
1207 0, /* nb_hex */
Guido van Rossum4668b002001-08-08 05:00:18 +00001208 0, /* nb_inplace_add */
1209 0, /* nb_inplace_subtract */
1210 0, /* nb_inplace_multiply*/
1211 0, /* nb_inplace_divide */
1212 0, /* nb_inplace_remainder */
1213 0, /* nb_inplace_power */
1214 0, /* nb_inplace_lshift */
1215 0, /* nb_inplace_rshift */
1216 0, /* nb_inplace_and */
1217 0, /* nb_inplace_xor */
1218 0, /* nb_inplace_or */
1219 (binaryfunc)complex_int_div, /* nb_floor_divide */
1220 (binaryfunc)complex_div, /* nb_true_divide */
1221 0, /* nb_inplace_floor_divide */
1222 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001223};
1224
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001225PyTypeObject PyComplex_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001226 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumf9fca921996-01-12 00:47:05 +00001227 "complex",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001228 sizeof(PyComplexObject),
Guido van Rossumf9fca921996-01-12 00:47:05 +00001229 0,
Georg Brandl347b3002006-03-30 11:57:00 +00001230 complex_dealloc, /* tp_dealloc */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001231 (printfunc)complex_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001232 0, /* tp_getattr */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001233 0, /* tp_setattr */
1234 0, /* tp_compare */
1235 (reprfunc)complex_repr, /* tp_repr */
1236 &complex_as_number, /* tp_as_number */
1237 0, /* tp_as_sequence */
1238 0, /* tp_as_mapping */
1239 (hashfunc)complex_hash, /* tp_hash */
1240 0, /* tp_call */
Tim Peters70695122001-03-11 08:37:29 +00001241 (reprfunc)complex_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001242 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001243 0, /* tp_setattro */
1244 0, /* tp_as_buffer */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001245 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1246 complex_doc, /* tp_doc */
Guido van Rossumbe4cbb12001-01-18 01:12:39 +00001247 0, /* tp_traverse */
1248 0, /* tp_clear */
1249 complex_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001250 0, /* tp_weaklistoffset */
1251 0, /* tp_iter */
1252 0, /* tp_iternext */
1253 complex_methods, /* tp_methods */
1254 complex_members, /* tp_members */
1255 0, /* tp_getset */
1256 0, /* tp_base */
1257 0, /* tp_dict */
1258 0, /* tp_descr_get */
1259 0, /* tp_descr_set */
1260 0, /* tp_dictoffset */
1261 0, /* tp_init */
Georg Brandl6b50c632006-06-01 08:27:32 +00001262 PyType_GenericAlloc, /* tp_alloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263 complex_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00001264 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001265};
1266
1267#endif