blob: 3577a29a39d6b05040ff30e9b00c747ef5dfdd9b [file] [log] [blame]
Guido van Rossum96783941997-05-20 18:21:34 +00001
Guido van Rossumf9fca921996-01-12 00:47:05 +00002/* Complex object implementation */
3
4/* Borrows heavily from floatobject.c */
5
Guido van Rossum96783941997-05-20 18:21:34 +00006/* Submitted by Jim Hugunin */
7
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008#include "Python.h"
Tim Peters6d6c1a32001-08-02 04:15:00 +00009#include "structmember.h"
Guido van Rossumf9fca921996-01-12 00:47:05 +000010
Guido van Rossum65ce6de2002-06-13 17:07:07 +000011#ifndef WITHOUT_COMPLEX
12
Tim Peters70695122001-03-11 08:37:29 +000013/* Precisions used by repr() and str(), respectively.
14
15 The repr() precision (17 significant decimal digits) is the minimal number
16 that is guaranteed to have enough precision so that if the number is read
17 back in the exact same binary value is recreated. This is true for IEEE
18 floating point by design, and also happens to work for all other modern
19 hardware.
20
21 The str() precision is chosen so that in most cases, the rounding noise
22 created by various operations is suppressed, while giving plenty of
23 precision for practical use.
24*/
25
Antoine Pitrouc83ea132010-05-09 14:46:46 +000026#define PREC_REPR 17
27#define PREC_STR 12
Guido van Rossumf9fca921996-01-12 00:47:05 +000028
29/* elementary operations on complex numbers */
30
Guido van Rossum9e720e31996-07-21 02:31:35 +000031static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000032
Tim Peters0f336042001-03-18 08:21:57 +000033Py_complex
34c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000035{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000036 Py_complex r;
37 r.real = a.real + b.real;
38 r.imag = a.imag + b.imag;
39 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000040}
41
Tim Peters0f336042001-03-18 08:21:57 +000042Py_complex
43c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000044{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000045 Py_complex r;
46 r.real = a.real - b.real;
47 r.imag = a.imag - b.imag;
48 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000049}
50
Tim Peters0f336042001-03-18 08:21:57 +000051Py_complex
52c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000053{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000054 Py_complex r;
55 r.real = -a.real;
56 r.imag = -a.imag;
57 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000058}
59
Tim Peters0f336042001-03-18 08:21:57 +000060Py_complex
61c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000062{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000063 Py_complex r;
64 r.real = a.real*b.real - a.imag*b.imag;
65 r.imag = a.real*b.imag + a.imag*b.real;
66 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000067}
68
Tim Peters0f336042001-03-18 08:21:57 +000069Py_complex
70c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000071{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000072 /******************************************************************
73 This was the original algorithm. It's grossly prone to spurious
74 overflow and underflow errors. It also merrily divides by 0 despite
75 checking for that(!). The code still serves a doc purpose here, as
76 the algorithm following is a simple by-cases transformation of this
77 one:
Tim Peters0f336042001-03-18 08:21:57 +000078
Antoine Pitrouc83ea132010-05-09 14:46:46 +000079 Py_complex r;
80 double d = b.real*b.real + b.imag*b.imag;
81 if (d == 0.)
82 errno = EDOM;
83 r.real = (a.real*b.real + a.imag*b.imag)/d;
84 r.imag = (a.imag*b.real - a.real*b.imag)/d;
85 return r;
86 ******************************************************************/
Tim Peters0f336042001-03-18 08:21:57 +000087
Antoine Pitrouc83ea132010-05-09 14:46:46 +000088 /* This algorithm is better, and is pretty obvious: first divide the
89 * numerators and denominator by whichever of {b.real, b.imag} has
90 * larger magnitude. The earliest reference I found was to CACM
91 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
92 * University). As usual, though, we're still ignoring all IEEE
93 * endcases.
94 */
95 Py_complex r; /* the result */
96 const double abs_breal = b.real < 0 ? -b.real : b.real;
97 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
Tim Peters0f336042001-03-18 08:21:57 +000098
Antoine Pitrouc83ea132010-05-09 14:46:46 +000099 if (abs_breal >= abs_bimag) {
100 /* divide tops and bottom by b.real */
101 if (abs_breal == 0.0) {
102 errno = EDOM;
103 r.real = r.imag = 0.0;
104 }
105 else {
106 const double ratio = b.imag / b.real;
107 const double denom = b.real + b.imag * ratio;
108 r.real = (a.real + a.imag * ratio) / denom;
109 r.imag = (a.imag - a.real * ratio) / denom;
110 }
111 }
112 else {
113 /* divide tops and bottom by b.imag */
114 const double ratio = b.real / b.imag;
115 const double denom = b.real * ratio + b.imag;
116 assert(b.imag != 0.0);
117 r.real = (a.real * ratio + a.imag) / denom;
118 r.imag = (a.imag * ratio - a.real) / denom;
119 }
120 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000121}
122
Tim Peters0f336042001-03-18 08:21:57 +0000123Py_complex
124c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000125{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000126 Py_complex r;
127 double vabs,len,at,phase;
128 if (b.real == 0. && b.imag == 0.) {
129 r.real = 1.;
130 r.imag = 0.;
131 }
132 else if (a.real == 0. && a.imag == 0.) {
133 if (b.imag != 0. || b.real < 0.)
134 errno = EDOM;
135 r.real = 0.;
136 r.imag = 0.;
137 }
138 else {
139 vabs = hypot(a.real,a.imag);
140 len = pow(vabs,b.real);
141 at = atan2(a.imag, a.real);
142 phase = at*b.real;
143 if (b.imag != 0.0) {
144 len /= exp(at*b.imag);
145 phase += b.imag*log(vabs);
146 }
147 r.real = len*cos(phase);
148 r.imag = len*sin(phase);
149 }
150 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000151}
152
Tim Peters0f336042001-03-18 08:21:57 +0000153static Py_complex
154c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000155{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000156 Py_complex r, p;
157 long mask = 1;
158 r = c_1;
159 p = x;
160 while (mask > 0 && n >= mask) {
161 if (n & mask)
162 r = c_prod(r,p);
163 mask <<= 1;
164 p = c_prod(p,p);
165 }
166 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000167}
168
Tim Peters0f336042001-03-18 08:21:57 +0000169static Py_complex
170c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000171{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000173
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000174 if (n > 100 || n < -100) {
175 cn.real = (double) n;
176 cn.imag = 0.;
177 return c_pow(x,cn);
178 }
179 else if (n > 0)
180 return c_powu(x,n);
181 else
182 return c_quot(c_1,c_powu(x,-n));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000183
184}
185
Christian Heimes6f341092008-04-18 23:13:07 +0000186double
187c_abs(Py_complex z)
188{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000189 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
190 double result;
Christian Heimes6f341092008-04-18 23:13:07 +0000191
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000192 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
193 /* C99 rules: if either the real or the imaginary part is an
194 infinity, return infinity, even if the other part is a
195 NaN. */
196 if (Py_IS_INFINITY(z.real)) {
197 result = fabs(z.real);
198 errno = 0;
199 return result;
200 }
201 if (Py_IS_INFINITY(z.imag)) {
202 result = fabs(z.imag);
203 errno = 0;
204 return result;
205 }
206 /* either the real or imaginary part is a NaN,
207 and neither is infinite. Result should be NaN. */
208 return Py_NAN;
209 }
210 result = hypot(z.real, z.imag);
211 if (!Py_IS_FINITE(result))
212 errno = ERANGE;
213 else
214 errno = 0;
215 return result;
Christian Heimes6f341092008-04-18 23:13:07 +0000216}
217
Tim Peters6d6c1a32001-08-02 04:15:00 +0000218static PyObject *
219complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
220{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000221 PyObject *op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000222
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000223 op = type->tp_alloc(type, 0);
224 if (op != NULL)
225 ((PyComplexObject *)op)->cval = cval;
226 return op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000227}
228
Guido van Rossumf9fca921996-01-12 00:47:05 +0000229PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000230PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000231{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000232 register PyComplexObject *op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000233
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000234 /* Inline PyObject_New */
235 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
236 if (op == NULL)
237 return PyErr_NoMemory();
238 PyObject_INIT(op, &PyComplex_Type);
239 op->cval = cval;
240 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000241}
242
Tim Peters6d6c1a32001-08-02 04:15:00 +0000243static PyObject *
244complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
245{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000246 Py_complex c;
247 c.real = real;
248 c.imag = imag;
249 return complex_subtype_from_c_complex(type, c);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000250}
251
Guido van Rossumf9fca921996-01-12 00:47:05 +0000252PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000253PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000254{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000255 Py_complex c;
256 c.real = real;
257 c.imag = imag;
258 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000259}
260
261double
Fred Drake4288c802000-07-09 04:36:04 +0000262PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000263{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000264 if (PyComplex_Check(op)) {
265 return ((PyComplexObject *)op)->cval.real;
266 }
267 else {
268 return PyFloat_AsDouble(op);
269 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000270}
271
272double
Fred Drake4288c802000-07-09 04:36:04 +0000273PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000274{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000275 if (PyComplex_Check(op)) {
276 return ((PyComplexObject *)op)->cval.imag;
277 }
278 else {
279 return 0.0;
280 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000281}
282
Benjamin Peterson36943662010-01-04 01:00:47 +0000283static PyObject *
284try_complex_special_method(PyObject *op) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000285 PyObject *f;
286 static PyObject *complexstr;
Benjamin Peterson36943662010-01-04 01:00:47 +0000287
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 if (complexstr == NULL) {
289 complexstr = PyString_InternFromString("__complex__");
290 if (complexstr == NULL)
291 return NULL;
292 }
293 if (PyInstance_Check(op)) {
294 f = PyObject_GetAttr(op, complexstr);
295 if (f == NULL) {
296 if (PyErr_ExceptionMatches(PyExc_AttributeError))
297 PyErr_Clear();
298 else
299 return NULL;
300 }
301 }
302 else {
303 f = _PyObject_LookupSpecial(op, "__complex__", &complexstr);
304 if (f == NULL && PyErr_Occurred())
305 return NULL;
306 }
307 if (f != NULL) {
308 PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
309 Py_DECREF(f);
310 return res;
311 }
312 return NULL;
Benjamin Peterson36943662010-01-04 01:00:47 +0000313}
314
Guido van Rossum9e720e31996-07-21 02:31:35 +0000315Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000316PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000317{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000318 Py_complex cv;
319 PyObject *newop = NULL;
Georg Brandl2b869942007-03-17 16:08:45 +0000320
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000321 assert(op);
322 /* If op is already of type PyComplex_Type, return its value */
323 if (PyComplex_Check(op)) {
324 return ((PyComplexObject *)op)->cval;
325 }
326 /* If not, use op's __complex__ method, if it exists */
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000327
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000328 /* return -1 on failure */
329 cv.real = -1.;
330 cv.imag = 0.;
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000331
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 newop = try_complex_special_method(op);
333
334 if (newop) {
335 if (!PyComplex_Check(newop)) {
336 PyErr_SetString(PyExc_TypeError,
337 "__complex__ should return a complex object");
338 Py_DECREF(newop);
339 return cv;
340 }
341 cv = ((PyComplexObject *)newop)->cval;
342 Py_DECREF(newop);
343 return cv;
344 }
345 else if (PyErr_Occurred()) {
346 return cv;
347 }
348 /* If neither of the above works, interpret op as a float giving the
349 real part of the result, and fill in the imaginary part as 0. */
350 else {
351 /* PyFloat_AsDouble will return -1 on failure */
352 cv.real = PyFloat_AsDouble(op);
353 return cv;
354 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000355}
356
Guido van Rossumf9fca921996-01-12 00:47:05 +0000357static void
Fred Drake4288c802000-07-09 04:36:04 +0000358complex_dealloc(PyObject *op)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000359{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000360 op->ob_type->tp_free(op);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000361}
362
363
Mark Dickinson95bc9802009-04-24 12:46:53 +0000364static PyObject *
Eric Smitha985a3a2009-05-05 18:26:08 +0000365complex_format(PyComplexObject *v, int precision, char format_code)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000366{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000367 PyObject *result = NULL;
368 Py_ssize_t len;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000369
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000370 /* If these are non-NULL, they'll need to be freed. */
371 char *pre = NULL;
372 char *im = NULL;
373 char *buf = NULL;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000374
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000375 /* These do not need to be freed. re is either an alias
376 for pre or a pointer to a constant. lead and tail
377 are pointers to constants. */
378 char *re = NULL;
379 char *lead = "";
380 char *tail = "";
Mark Dickinson95bc9802009-04-24 12:46:53 +0000381
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000382 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
383 re = "";
384 im = PyOS_double_to_string(v->cval.imag, format_code,
385 precision, 0, NULL);
386 if (!im) {
387 PyErr_NoMemory();
388 goto done;
389 }
390 } else {
391 /* Format imaginary part with sign, real part without */
392 pre = PyOS_double_to_string(v->cval.real, format_code,
393 precision, 0, NULL);
394 if (!pre) {
395 PyErr_NoMemory();
396 goto done;
397 }
398 re = pre;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000399
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000400 im = PyOS_double_to_string(v->cval.imag, format_code,
401 precision, Py_DTSF_SIGN, NULL);
402 if (!im) {
403 PyErr_NoMemory();
404 goto done;
405 }
406 lead = "(";
407 tail = ")";
408 }
409 /* Alloc the final buffer. Add one for the "j" in the format string,
410 and one for the trailing zero. */
411 len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
412 buf = PyMem_Malloc(len);
413 if (!buf) {
414 PyErr_NoMemory();
415 goto done;
416 }
417 PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
418 result = PyString_FromString(buf);
Mark Dickinson95bc9802009-04-24 12:46:53 +0000419 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000420 PyMem_Free(im);
421 PyMem_Free(pre);
422 PyMem_Free(buf);
Mark Dickinson95bc9802009-04-24 12:46:53 +0000423
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000424 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000425}
426
427static int
Fred Drake4288c802000-07-09 04:36:04 +0000428complex_print(PyComplexObject *v, FILE *fp, int flags)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000429{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000430 PyObject *formatv;
431 char *buf;
432 if (flags & Py_PRINT_RAW)
433 formatv = complex_format(v, PyFloat_STR_PRECISION, 'g');
434 else
435 formatv = complex_format(v, 0, 'r');
436 if (formatv == NULL)
437 return -1;
438 buf = PyString_AS_STRING(formatv);
439 Py_BEGIN_ALLOW_THREADS
440 fputs(buf, fp);
441 Py_END_ALLOW_THREADS
442 Py_DECREF(formatv);
443 return 0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000444}
445
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000447complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000448{
Eric Smitha985a3a2009-05-05 18:26:08 +0000449 return complex_format(v, 0, 'r');
Tim Peters70695122001-03-11 08:37:29 +0000450}
451
452static PyObject *
453complex_str(PyComplexObject *v)
454{
Eric Smitha985a3a2009-05-05 18:26:08 +0000455 return complex_format(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossumf9fca921996-01-12 00:47:05 +0000456}
457
Guido van Rossumf9fca921996-01-12 00:47:05 +0000458static long
Fred Drake4288c802000-07-09 04:36:04 +0000459complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000460{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000461 long hashreal, hashimag, combined;
462 hashreal = _Py_HashDouble(v->cval.real);
463 if (hashreal == -1)
464 return -1;
465 hashimag = _Py_HashDouble(v->cval.imag);
466 if (hashimag == -1)
467 return -1;
468 /* Note: if the imaginary part is 0, hashimag is 0 now,
469 * so the following returns hashreal unchanged. This is
470 * important because numbers of different types that
471 * compare equal must have the same hash value, so that
472 * hash(x + 0*j) must equal hash(x).
473 */
474 combined = hashreal + 1000003 * hashimag;
475 if (combined == -1)
476 combined = -2;
477 return combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000478}
479
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000480/* This macro may return! */
481#define TO_COMPLEX(obj, c) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000482 if (PyComplex_Check(obj)) \
483 c = ((PyComplexObject *)(obj))->cval; \
484 else if (to_complex(&(obj), &(c)) < 0) \
485 return (obj)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000486
487static int
488to_complex(PyObject **pobj, Py_complex *pc)
489{
490 PyObject *obj = *pobj;
491
492 pc->real = pc->imag = 0.0;
493 if (PyInt_Check(obj)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000494 pc->real = PyInt_AS_LONG(obj);
495 return 0;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000496 }
497 if (PyLong_Check(obj)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 pc->real = PyLong_AsDouble(obj);
499 if (pc->real == -1.0 && PyErr_Occurred()) {
500 *pobj = NULL;
501 return -1;
502 }
503 return 0;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000504 }
505 if (PyFloat_Check(obj)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000506 pc->real = PyFloat_AsDouble(obj);
507 return 0;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000508 }
509 Py_INCREF(Py_NotImplemented);
510 *pobj = Py_NotImplemented;
511 return -1;
512}
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000513
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000514
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000515static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000516complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000517{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000518 Py_complex result;
519 Py_complex a, b;
520 TO_COMPLEX(v, a);
521 TO_COMPLEX(w, b);
522 PyFPE_START_PROTECT("complex_add", return 0)
523 result = c_sum(a, b);
524 PyFPE_END_PROTECT(result)
525 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000526}
527
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000529complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000530{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000531 Py_complex result;
532 Py_complex a, b;
533 TO_COMPLEX(v, a);
534 TO_COMPLEX(w, b);;
535 PyFPE_START_PROTECT("complex_sub", return 0)
536 result = c_diff(a, b);
537 PyFPE_END_PROTECT(result)
538 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000539}
540
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000542complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000543{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000544 Py_complex result;
545 Py_complex a, b;
546 TO_COMPLEX(v, a);
547 TO_COMPLEX(w, b);
548 PyFPE_START_PROTECT("complex_mul", return 0)
549 result = c_prod(a, b);
550 PyFPE_END_PROTECT(result)
551 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000552}
553
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000555complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000556{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000557 Py_complex quot;
558 Py_complex a, b;
559 TO_COMPLEX(v, a);
560 TO_COMPLEX(w, b);
561 PyFPE_START_PROTECT("complex_div", return 0)
562 errno = 0;
563 quot = c_quot(a, b);
564 PyFPE_END_PROTECT(quot)
565 if (errno == EDOM) {
566 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
567 return NULL;
568 }
569 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000570}
571
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000572static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000573complex_classic_div(PyObject *v, PyObject *w)
Guido van Rossum393661d2001-08-31 17:40:15 +0000574{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000575 Py_complex quot;
576 Py_complex a, b;
577 TO_COMPLEX(v, a);
578 TO_COMPLEX(w, b);
579 if (Py_DivisionWarningFlag >= 2 &&
580 PyErr_Warn(PyExc_DeprecationWarning,
581 "classic complex division") < 0)
582 return NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +0000583
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000584 PyFPE_START_PROTECT("complex_classic_div", return 0)
585 errno = 0;
586 quot = c_quot(a, b);
587 PyFPE_END_PROTECT(quot)
588 if (errno == EDOM) {
589 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
590 return NULL;
591 }
592 return PyComplex_FromCComplex(quot);
Guido van Rossum393661d2001-08-31 17:40:15 +0000593}
594
595static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000596complex_remainder(PyObject *v, PyObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000597{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000598 Py_complex div, mod;
599 Py_complex a, b;
600 TO_COMPLEX(v, a);
601 TO_COMPLEX(w, b);
602 if (PyErr_Warn(PyExc_DeprecationWarning,
603 "complex divmod(), // and % are deprecated") < 0)
604 return NULL;
Guido van Rossum69cf3c72002-04-15 12:39:12 +0000605
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000606 errno = 0;
607 div = c_quot(a, b); /* The raw divisor value. */
608 if (errno == EDOM) {
609 PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
610 return NULL;
611 }
612 div.real = floor(div.real); /* Use the floor of the real part. */
613 div.imag = 0.0;
614 mod = c_diff(a, c_prod(b, div));
Guido van Rossum3be12e91996-09-12 20:56:18 +0000615
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000616 return PyComplex_FromCComplex(mod);
Guido van Rossumee09fc11996-09-11 13:55:55 +0000617}
618
Guido van Rossumee09fc11996-09-11 13:55:55 +0000619
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000620static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000621complex_divmod(PyObject *v, PyObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000622{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000623 Py_complex div, mod;
624 PyObject *d, *m, *z;
625 Py_complex a, b;
626 TO_COMPLEX(v, a);
627 TO_COMPLEX(w, b);
628 if (PyErr_Warn(PyExc_DeprecationWarning,
629 "complex divmod(), // and % are deprecated") < 0)
630 return NULL;
Guido van Rossum9ec4c782002-04-15 01:41:56 +0000631
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000632 errno = 0;
633 div = c_quot(a, b); /* The raw divisor value. */
634 if (errno == EDOM) {
635 PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
636 return NULL;
637 }
638 div.real = floor(div.real); /* Use the floor of the real part. */
639 div.imag = 0.0;
640 mod = c_diff(a, c_prod(b, div));
641 d = PyComplex_FromCComplex(div);
642 m = PyComplex_FromCComplex(mod);
643 z = PyTuple_Pack(2, d, m);
644 Py_XDECREF(d);
645 Py_XDECREF(m);
646 return z;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000647}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000650complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000651{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000652 Py_complex p;
653 Py_complex exponent;
654 long int_exponent;
655 Py_complex a, b;
656 TO_COMPLEX(v, a);
657 TO_COMPLEX(w, b);
658 if (z!=Py_None) {
659 PyErr_SetString(PyExc_ValueError, "complex modulo");
660 return NULL;
661 }
662 PyFPE_START_PROTECT("complex_pow", return 0)
663 errno = 0;
664 exponent = b;
665 int_exponent = (long)exponent.real;
666 if (exponent.imag == 0. && exponent.real == int_exponent)
667 p = c_powi(a,int_exponent);
668 else
669 p = c_pow(a,exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000670
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000671 PyFPE_END_PROTECT(p)
672 Py_ADJUST_ERANGE2(p.real, p.imag);
673 if (errno == EDOM) {
674 PyErr_SetString(PyExc_ZeroDivisionError,
675 "0.0 to a negative or complex power");
676 return NULL;
677 }
678 else if (errno == ERANGE) {
679 PyErr_SetString(PyExc_OverflowError,
680 "complex exponentiation");
681 return NULL;
682 }
683 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000684}
685
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000687complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000688{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000689 PyObject *t, *r;
690 Py_complex a, b;
691 TO_COMPLEX(v, a);
692 TO_COMPLEX(w, b);
693 if (PyErr_Warn(PyExc_DeprecationWarning,
694 "complex divmod(), // and % are deprecated") < 0)
695 return NULL;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000696
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000697 t = complex_divmod(v, w);
698 if (t != NULL) {
699 r = PyTuple_GET_ITEM(t, 0);
700 Py_INCREF(r);
701 Py_DECREF(t);
702 return r;
703 }
704 return NULL;
Guido van Rossum4668b002001-08-08 05:00:18 +0000705}
706
707static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000708complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000709{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000710 Py_complex neg;
711 neg.real = -v->cval.real;
712 neg.imag = -v->cval.imag;
713 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000714}
715
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000716static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000717complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000718{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000719 if (PyComplex_CheckExact(v)) {
720 Py_INCREF(v);
721 return (PyObject *)v;
722 }
723 else
724 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000725}
726
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000727static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000728complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000729{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000730 double result;
Christian Heimes6f341092008-04-18 23:13:07 +0000731
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000732 PyFPE_START_PROTECT("complex_abs", return 0)
733 result = c_abs(v->cval);
734 PyFPE_END_PROTECT(result)
Christian Heimes6f341092008-04-18 23:13:07 +0000735
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000736 if (errno == ERANGE) {
737 PyErr_SetString(PyExc_OverflowError,
738 "absolute value too large");
739 return NULL;
740 }
741 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000742}
743
744static int
Fred Drake4288c802000-07-09 04:36:04 +0000745complex_nonzero(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000746{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000747 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000748}
749
750static int
Fred Drake4288c802000-07-09 04:36:04 +0000751complex_coerce(PyObject **pv, PyObject **pw)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000752{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000753 Py_complex cval;
754 cval.imag = 0.;
755 if (PyInt_Check(*pw)) {
756 cval.real = (double)PyInt_AsLong(*pw);
757 *pw = PyComplex_FromCComplex(cval);
758 Py_INCREF(*pv);
759 return 0;
760 }
761 else if (PyLong_Check(*pw)) {
762 cval.real = PyLong_AsDouble(*pw);
763 if (cval.real == -1.0 && PyErr_Occurred())
764 return -1;
765 *pw = PyComplex_FromCComplex(cval);
766 Py_INCREF(*pv);
767 return 0;
768 }
769 else if (PyFloat_Check(*pw)) {
770 cval.real = PyFloat_AsDouble(*pw);
771 *pw = PyComplex_FromCComplex(cval);
772 Py_INCREF(*pv);
773 return 0;
774 }
775 else if (PyComplex_Check(*pw)) {
776 Py_INCREF(*pv);
777 Py_INCREF(*pw);
778 return 0;
779 }
780 return 1; /* Can't do it */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000781}
782
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000783static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000784complex_richcompare(PyObject *v, PyObject *w, int op)
785{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000786 int c;
787 Py_complex i, j;
788 PyObject *res;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000789
Mark Dickinson81336372010-05-30 12:12:25 +0000790 TO_COMPLEX(v, i);
791 TO_COMPLEX(w, j);
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000792
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000793 if (op != Py_EQ && op != Py_NE) {
794 PyErr_SetString(PyExc_TypeError,
795 "no ordering relation is defined for complex numbers");
796 return NULL;
797 }
Guido van Rossum22056422001-09-24 17:52:04 +0000798
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000799 if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
800 res = Py_True;
801 else
802 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000803
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 Py_INCREF(res);
805 return res;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000806}
807
808static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000809complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000810{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 PyErr_SetString(PyExc_TypeError,
812 "can't convert complex to int");
813 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000814}
815
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000816static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000817complex_long(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000818{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000819 PyErr_SetString(PyExc_TypeError,
820 "can't convert complex to long");
821 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000822}
823
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000824static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000825complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000826{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000827 PyErr_SetString(PyExc_TypeError,
828 "can't convert complex to float");
829 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000830}
831
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000832static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000833complex_conjugate(PyObject *self)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000834{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000835 Py_complex c;
836 c = ((PyComplexObject *)self)->cval;
837 c.imag = -c.imag;
838 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000839}
840
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000841PyDoc_STRVAR(complex_conjugate_doc,
842"complex.conjugate() -> complex\n"
843"\n"
844"Returns the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
845
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000846static PyObject *
847complex_getnewargs(PyComplexObject *v)
848{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000849 Py_complex c = v->cval;
850 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000851}
852
Eric Smith9139cc62009-04-30 00:58:58 +0000853PyDoc_STRVAR(complex__format__doc,
854"complex.__format__() -> str\n"
855"\n"
856"Converts to a string according to format_spec.");
857
858static PyObject *
859complex__format__(PyObject* self, PyObject* args)
860{
861 PyObject *format_spec;
862
863 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000864 return NULL;
Eric Smith9139cc62009-04-30 00:58:58 +0000865 if (PyBytes_Check(format_spec))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000866 return _PyComplex_FormatAdvanced(self,
867 PyBytes_AS_STRING(format_spec),
868 PyBytes_GET_SIZE(format_spec));
Eric Smith9139cc62009-04-30 00:58:58 +0000869 if (PyUnicode_Check(format_spec)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000870 /* Convert format_spec to a str */
871 PyObject *result;
872 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smith9139cc62009-04-30 00:58:58 +0000873
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000874 if (str_spec == NULL)
875 return NULL;
Eric Smith9139cc62009-04-30 00:58:58 +0000876
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000877 result = _PyComplex_FormatAdvanced(self,
878 PyBytes_AS_STRING(str_spec),
879 PyBytes_GET_SIZE(str_spec));
Eric Smith9139cc62009-04-30 00:58:58 +0000880
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000881 Py_DECREF(str_spec);
882 return result;
Eric Smith9139cc62009-04-30 00:58:58 +0000883 }
884 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
885 return NULL;
886}
887
Christian Heimes6f341092008-04-18 23:13:07 +0000888#if 0
889static PyObject *
890complex_is_finite(PyObject *self)
891{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000892 Py_complex c;
893 c = ((PyComplexObject *)self)->cval;
894 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
895 Py_IS_FINITE(c.imag)));
Christian Heimes6f341092008-04-18 23:13:07 +0000896}
897
898PyDoc_STRVAR(complex_is_finite_doc,
899"complex.is_finite() -> bool\n"
900"\n"
901"Returns True if the real and the imaginary part is finite.");
902#endif
903
Guido van Rossumf9fca921996-01-12 00:47:05 +0000904static PyMethodDef complex_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000905 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
906 complex_conjugate_doc},
Christian Heimes6f341092008-04-18 23:13:07 +0000907#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000908 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
909 complex_is_finite_doc},
Christian Heimes6f341092008-04-18 23:13:07 +0000910#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000911 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
912 {"__format__", (PyCFunction)complex__format__,
913 METH_VARARGS, complex__format__doc},
914 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000915};
916
Guido van Rossum6f799372001-09-20 20:46:19 +0000917static PyMemberDef complex_members[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000918 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
919 "the real part of a complex number"},
920 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
921 "the imaginary part of a complex number"},
922 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000923};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000924
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000925static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000926complex_subtype_from_string(PyTypeObject *type, PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000927{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000928 const char *s, *start;
929 char *end;
930 double x=0.0, y=0.0, z;
931 int got_bracket=0;
Guido van Rossum70e36882001-10-25 18:07:22 +0000932#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000933 char *s_buffer = NULL;
Guido van Rossum70e36882001-10-25 18:07:22 +0000934#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000935 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000936
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000937 if (PyString_Check(v)) {
938 s = PyString_AS_STRING(v);
939 len = PyString_GET_SIZE(v);
940 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000941#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000942 else if (PyUnicode_Check(v)) {
943 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
944 if (s_buffer == NULL)
945 return PyErr_NoMemory();
946 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
947 PyUnicode_GET_SIZE(v),
948 s_buffer,
949 NULL))
950 goto error;
951 s = s_buffer;
952 len = strlen(s);
953 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000954#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000955 else if (PyObject_AsCharBuffer(v, &s, &len)) {
956 PyErr_SetString(PyExc_TypeError,
957 "complex() arg is not a string");
958 return NULL;
959 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000960
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000961 /* position on first nonblank */
962 start = s;
963 while (Py_ISSPACE(*s))
964 s++;
965 if (*s == '(') {
966 /* Skip over possible bracket from repr(). */
967 got_bracket = 1;
968 s++;
969 while (Py_ISSPACE(*s))
970 s++;
971 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000972
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 /* a valid complex string usually takes one of the three forms:
Tim Peters6d6c1a32001-08-02 04:15:00 +0000974
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000975 <float> - real part only
976 <float>j - imaginary part only
977 <float><signed-float>j - real and imaginary parts
Tim Peters6d6c1a32001-08-02 04:15:00 +0000978
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000979 where <float> represents any numeric string that's accepted by the
980 float constructor (including 'nan', 'inf', 'infinity', etc.), and
981 <signed-float> is any string of the form <float> whose first
982 character is '+' or '-'.
Tim Peters6d6c1a32001-08-02 04:15:00 +0000983
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000984 For backwards compatibility, the extra forms
Mark Dickinson95bc9802009-04-24 12:46:53 +0000985
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000986 <float><sign>j
987 <sign>j
988 j
Mark Dickinson95bc9802009-04-24 12:46:53 +0000989
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000990 are also accepted, though support for these forms may be removed from
991 a future version of Python.
992 */
Mark Dickinson95bc9802009-04-24 12:46:53 +0000993
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000994 /* first look for forms starting with <float> */
995 z = PyOS_string_to_double(s, &end, NULL);
996 if (z == -1.0 && PyErr_Occurred()) {
997 if (PyErr_ExceptionMatches(PyExc_ValueError))
998 PyErr_Clear();
999 else
1000 goto error;
1001 }
1002 if (end != s) {
1003 /* all 4 forms starting with <float> land here */
1004 s = end;
1005 if (*s == '+' || *s == '-') {
1006 /* <float><signed-float>j | <float><sign>j */
1007 x = z;
1008 y = PyOS_string_to_double(s, &end, NULL);
1009 if (y == -1.0 && PyErr_Occurred()) {
1010 if (PyErr_ExceptionMatches(PyExc_ValueError))
1011 PyErr_Clear();
1012 else
1013 goto error;
1014 }
1015 if (end != s)
1016 /* <float><signed-float>j */
1017 s = end;
1018 else {
1019 /* <float><sign>j */
1020 y = *s == '+' ? 1.0 : -1.0;
1021 s++;
1022 }
1023 if (!(*s == 'j' || *s == 'J'))
1024 goto parse_error;
1025 s++;
1026 }
1027 else if (*s == 'j' || *s == 'J') {
1028 /* <float>j */
1029 s++;
1030 y = z;
1031 }
1032 else
1033 /* <float> */
1034 x = z;
1035 }
1036 else {
1037 /* not starting with <float>; must be <sign>j or j */
1038 if (*s == '+' || *s == '-') {
1039 /* <sign>j */
1040 y = *s == '+' ? 1.0 : -1.0;
1041 s++;
1042 }
1043 else
1044 /* j */
1045 y = 1.0;
1046 if (!(*s == 'j' || *s == 'J'))
1047 goto parse_error;
1048 s++;
1049 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001050
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001051 /* trailing whitespace and closing bracket */
1052 while (Py_ISSPACE(*s))
1053 s++;
1054 if (got_bracket) {
1055 /* if there was an opening parenthesis, then the corresponding
1056 closing parenthesis should be right here */
1057 if (*s != ')')
1058 goto parse_error;
1059 s++;
1060 while (Py_ISSPACE(*s))
1061 s++;
1062 }
Mark Dickinson95bc9802009-04-24 12:46:53 +00001063
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001064 /* we should now be at the end of the string */
1065 if (s-start != len)
1066 goto parse_error;
Mark Dickinson95bc9802009-04-24 12:46:53 +00001067
Mark Dickinsonc04c7c52009-10-26 22:28:14 +00001068
1069#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001070 if (s_buffer)
1071 PyMem_FREE(s_buffer);
Mark Dickinsonc04c7c52009-10-26 22:28:14 +00001072#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001073 return complex_subtype_from_doubles(type, x, y);
Mark Dickinson95bc9802009-04-24 12:46:53 +00001074
1075 parse_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001076 PyErr_SetString(PyExc_ValueError,
1077 "complex() arg is a malformed string");
Mark Dickinsonc04c7c52009-10-26 22:28:14 +00001078 error:
1079#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001080 if (s_buffer)
1081 PyMem_FREE(s_buffer);
Mark Dickinsonc04c7c52009-10-26 22:28:14 +00001082#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001083 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +00001084}
1085
Tim Peters6d6c1a32001-08-02 04:15:00 +00001086static PyObject *
1087complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1088{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001089 PyObject *r, *i, *tmp;
1090 PyNumberMethods *nbr, *nbi = NULL;
1091 Py_complex cr, ci;
1092 int own_r = 0;
1093 int cr_is_complex = 0;
1094 int ci_is_complex = 0;
1095 static char *kwlist[] = {"real", "imag", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001096
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001097 r = Py_False;
1098 i = NULL;
1099 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
1100 &r, &i))
1101 return NULL;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +00001102
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001103 /* Special-case for a single argument when type(arg) is complex. */
1104 if (PyComplex_CheckExact(r) && i == NULL &&
1105 type == &PyComplex_Type) {
1106 /* Note that we can't know whether it's safe to return
1107 a complex *subclass* instance as-is, hence the restriction
1108 to exact complexes here. If either the input or the
1109 output is a complex subclass, it will be handled below
1110 as a non-orthogonal vector. */
1111 Py_INCREF(r);
1112 return r;
1113 }
1114 if (PyString_Check(r) || PyUnicode_Check(r)) {
1115 if (i != NULL) {
1116 PyErr_SetString(PyExc_TypeError,
1117 "complex() can't take second arg"
1118 " if first is a string");
1119 return NULL;
1120 }
1121 return complex_subtype_from_string(type, r);
1122 }
1123 if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
1124 PyErr_SetString(PyExc_TypeError,
1125 "complex() second arg can't be a string");
1126 return NULL;
1127 }
Tim Peters2400fa42001-09-12 19:12:49 +00001128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001129 tmp = try_complex_special_method(r);
1130 if (tmp) {
1131 r = tmp;
1132 own_r = 1;
1133 }
1134 else if (PyErr_Occurred()) {
1135 return NULL;
1136 }
Benjamin Peterson36943662010-01-04 01:00:47 +00001137
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001138 nbr = r->ob_type->tp_as_number;
1139 if (i != NULL)
1140 nbi = i->ob_type->tp_as_number;
1141 if (nbr == NULL || nbr->nb_float == NULL ||
1142 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
1143 PyErr_SetString(PyExc_TypeError,
1144 "complex() argument must be a string or a number");
1145 if (own_r) {
1146 Py_DECREF(r);
1147 }
1148 return NULL;
1149 }
Georg Brandl8f032cb2007-03-13 07:57:51 +00001150
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001151 /* If we get this far, then the "real" and "imag" parts should
1152 both be treated as numbers, and the constructor should return a
1153 complex number equal to (real + imag*1j).
Georg Brandl8f032cb2007-03-13 07:57:51 +00001154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001155 Note that we do NOT assume the input to already be in canonical
1156 form; the "real" and "imag" parts might themselves be complex
1157 numbers, which slightly complicates the code below. */
1158 if (PyComplex_Check(r)) {
1159 /* Note that if r is of a complex subtype, we're only
1160 retaining its real & imag parts here, and the return
1161 value is (properly) of the builtin complex type. */
1162 cr = ((PyComplexObject*)r)->cval;
1163 cr_is_complex = 1;
1164 if (own_r) {
1165 Py_DECREF(r);
1166 }
1167 }
1168 else {
1169 /* The "real" part really is entirely real, and contributes
1170 nothing in the imaginary direction.
1171 Just treat it as a double. */
1172 tmp = PyNumber_Float(r);
1173 if (own_r) {
1174 /* r was a newly created complex number, rather
1175 than the original "real" argument. */
1176 Py_DECREF(r);
1177 }
1178 if (tmp == NULL)
1179 return NULL;
1180 if (!PyFloat_Check(tmp)) {
1181 PyErr_SetString(PyExc_TypeError,
1182 "float(r) didn't return a float");
1183 Py_DECREF(tmp);
1184 return NULL;
1185 }
1186 cr.real = PyFloat_AsDouble(tmp);
1187 cr.imag = 0.0; /* Shut up compiler warning */
1188 Py_DECREF(tmp);
1189 }
1190 if (i == NULL) {
1191 ci.real = 0.0;
1192 }
1193 else if (PyComplex_Check(i)) {
1194 ci = ((PyComplexObject*)i)->cval;
1195 ci_is_complex = 1;
1196 } else {
1197 /* The "imag" part really is entirely imaginary, and
1198 contributes nothing in the real direction.
1199 Just treat it as a double. */
1200 tmp = (*nbi->nb_float)(i);
1201 if (tmp == NULL)
1202 return NULL;
1203 ci.real = PyFloat_AsDouble(tmp);
1204 Py_DECREF(tmp);
1205 }
1206 /* If the input was in canonical form, then the "real" and "imag"
1207 parts are real numbers, so that ci.imag and cr.imag are zero.
1208 We need this correction in case they were not real numbers. */
Guido van Rossum715ec182007-11-27 22:38:36 +00001209
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001210 if (ci_is_complex) {
1211 cr.real -= ci.imag;
1212 }
1213 if (cr_is_complex) {
1214 ci.real += cr.imag;
1215 }
1216 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001217}
1218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001219PyDoc_STRVAR(complex_doc,
Tim Peters2400fa42001-09-12 19:12:49 +00001220"complex(real[, imag]) -> complex number\n"
1221"\n"
1222"Create a complex number from a real part and an optional imaginary part.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001223"This is equivalent to (real + imag*1j) where imag defaults to 0.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001224
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001225static PyNumberMethods complex_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001226 (binaryfunc)complex_add, /* nb_add */
1227 (binaryfunc)complex_sub, /* nb_subtract */
1228 (binaryfunc)complex_mul, /* nb_multiply */
1229 (binaryfunc)complex_classic_div, /* nb_divide */
1230 (binaryfunc)complex_remainder, /* nb_remainder */
1231 (binaryfunc)complex_divmod, /* nb_divmod */
1232 (ternaryfunc)complex_pow, /* nb_power */
1233 (unaryfunc)complex_neg, /* nb_negative */
1234 (unaryfunc)complex_pos, /* nb_positive */
1235 (unaryfunc)complex_abs, /* nb_absolute */
1236 (inquiry)complex_nonzero, /* nb_nonzero */
1237 0, /* nb_invert */
1238 0, /* nb_lshift */
1239 0, /* nb_rshift */
1240 0, /* nb_and */
1241 0, /* nb_xor */
1242 0, /* nb_or */
1243 complex_coerce, /* nb_coerce */
1244 complex_int, /* nb_int */
1245 complex_long, /* nb_long */
1246 complex_float, /* nb_float */
1247 0, /* nb_oct */
1248 0, /* nb_hex */
1249 0, /* nb_inplace_add */
1250 0, /* nb_inplace_subtract */
1251 0, /* nb_inplace_multiply*/
1252 0, /* nb_inplace_divide */
1253 0, /* nb_inplace_remainder */
1254 0, /* nb_inplace_power */
1255 0, /* nb_inplace_lshift */
1256 0, /* nb_inplace_rshift */
1257 0, /* nb_inplace_and */
1258 0, /* nb_inplace_xor */
1259 0, /* nb_inplace_or */
1260 (binaryfunc)complex_int_div, /* nb_floor_divide */
1261 (binaryfunc)complex_div, /* nb_true_divide */
1262 0, /* nb_inplace_floor_divide */
1263 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001264};
1265
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001266PyTypeObject PyComplex_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001267 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1268 "complex",
1269 sizeof(PyComplexObject),
1270 0,
1271 complex_dealloc, /* tp_dealloc */
1272 (printfunc)complex_print, /* tp_print */
1273 0, /* tp_getattr */
1274 0, /* tp_setattr */
1275 0, /* tp_compare */
1276 (reprfunc)complex_repr, /* tp_repr */
1277 &complex_as_number, /* tp_as_number */
1278 0, /* tp_as_sequence */
1279 0, /* tp_as_mapping */
1280 (hashfunc)complex_hash, /* tp_hash */
1281 0, /* tp_call */
1282 (reprfunc)complex_str, /* tp_str */
1283 PyObject_GenericGetAttr, /* tp_getattro */
1284 0, /* tp_setattro */
1285 0, /* tp_as_buffer */
1286 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1287 Py_TPFLAGS_BASETYPE, /* tp_flags */
1288 complex_doc, /* tp_doc */
1289 0, /* tp_traverse */
1290 0, /* tp_clear */
1291 complex_richcompare, /* tp_richcompare */
1292 0, /* tp_weaklistoffset */
1293 0, /* tp_iter */
1294 0, /* tp_iternext */
1295 complex_methods, /* tp_methods */
1296 complex_members, /* tp_members */
1297 0, /* tp_getset */
1298 0, /* tp_base */
1299 0, /* tp_dict */
1300 0, /* tp_descr_get */
1301 0, /* tp_descr_set */
1302 0, /* tp_dictoffset */
1303 0, /* tp_init */
1304 PyType_GenericAlloc, /* tp_alloc */
1305 complex_new, /* tp_new */
1306 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001307};
1308
1309#endif