blob: 9e97d1b3d41d63374c190b35a2b5de79672cb208 [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 Pitroud0a5e9b2014-10-10 23:49:32 +020099 if (abs_breal >= abs_bimag) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000100 /* 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 }
Antoine Pitroud0a5e9b2014-10-10 23:49:32 +0200112 else if (abs_bimag >= abs_breal) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000113 /* 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 }
Antoine Pitroud0a5e9b2014-10-10 23:49:32 +0200120 else {
121 /* At least one of b.real or b.imag is a NaN */
122 r.real = r.imag = Py_NAN;
123 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000124 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000130 Py_complex r;
131 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.)
138 errno = EDOM;
139 r.real = 0.;
140 r.imag = 0.;
141 }
142 else {
143 vabs = hypot(a.real,a.imag);
144 len = pow(vabs,b.real);
145 at = atan2(a.imag, a.real);
146 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;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000155}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000160 Py_complex r, p;
161 long mask = 1;
162 r = c_1;
163 p = x;
164 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;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000171}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000176 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000177
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000178 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));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000187
188}
189
Christian Heimes6f341092008-04-18 23:13:07 +0000190double
191c_abs(Py_complex z)
192{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000193 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
194 double result;
Christian Heimes6f341092008-04-18 23:13:07 +0000195
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000196 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;
Christian Heimes6f341092008-04-18 23:13:07 +0000220}
221
Tim Peters6d6c1a32001-08-02 04:15:00 +0000222static PyObject *
223complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
224{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000225 PyObject *op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000226
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000227 op = type->tp_alloc(type, 0);
228 if (op != NULL)
229 ((PyComplexObject *)op)->cval = cval;
230 return op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000231}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000236 register PyComplexObject *op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000237
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000238 /* Inline PyObject_New */
239 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
240 if (op == NULL)
241 return PyErr_NoMemory();
242 PyObject_INIT(op, &PyComplex_Type);
243 op->cval = cval;
244 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000250 Py_complex c;
251 c.real = real;
252 c.imag = imag;
253 return complex_subtype_from_c_complex(type, c);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000254}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000259 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268 if (PyComplex_Check(op)) {
269 return ((PyComplexObject *)op)->cval.real;
270 }
271 else {
272 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000279 if (PyComplex_Check(op)) {
280 return ((PyComplexObject *)op)->cval.imag;
281 }
282 else {
283 return 0.0;
284 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000285}
286
Benjamin Peterson36943662010-01-04 01:00:47 +0000287static PyObject *
288try_complex_special_method(PyObject *op) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000289 PyObject *f;
290 static PyObject *complexstr;
Benjamin Peterson36943662010-01-04 01:00:47 +0000291
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 if (complexstr == NULL) {
293 complexstr = PyString_InternFromString("__complex__");
294 if (complexstr == NULL)
295 return NULL;
296 }
297 if (PyInstance_Check(op)) {
298 f = PyObject_GetAttr(op, complexstr);
299 if (f == NULL) {
300 if (PyErr_ExceptionMatches(PyExc_AttributeError))
301 PyErr_Clear();
302 else
303 return NULL;
304 }
305 }
306 else {
307 f = _PyObject_LookupSpecial(op, "__complex__", &complexstr);
308 if (f == NULL && PyErr_Occurred())
309 return NULL;
310 }
311 if (f != NULL) {
312 PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
313 Py_DECREF(f);
314 return res;
315 }
316 return NULL;
Benjamin Peterson36943662010-01-04 01:00:47 +0000317}
318
Guido van Rossum9e720e31996-07-21 02:31:35 +0000319Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000320PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000321{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000322 Py_complex cv;
323 PyObject *newop = NULL;
Georg Brandl2b869942007-03-17 16:08:45 +0000324
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000325 assert(op);
326 /* If op is already of type PyComplex_Type, return its value */
327 if (PyComplex_Check(op)) {
328 return ((PyComplexObject *)op)->cval;
329 }
330 /* If not, use op's __complex__ method, if it exists */
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000331
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 /* return -1 on failure */
333 cv.real = -1.;
334 cv.imag = 0.;
Christian Heimesd7e1b2b2008-01-28 02:07:53 +0000335
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000336 newop = try_complex_special_method(op);
337
338 if (newop) {
339 if (!PyComplex_Check(newop)) {
340 PyErr_SetString(PyExc_TypeError,
341 "__complex__ should return a complex object");
342 Py_DECREF(newop);
343 return cv;
344 }
345 cv = ((PyComplexObject *)newop)->cval;
346 Py_DECREF(newop);
347 return cv;
348 }
349 else if (PyErr_Occurred()) {
350 return cv;
351 }
352 /* If neither of the above works, interpret op as a float giving the
353 real part of the result, and fill in the imaginary part as 0. */
354 else {
355 /* PyFloat_AsDouble will return -1 on failure */
356 cv.real = PyFloat_AsDouble(op);
357 return cv;
358 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000359}
360
Guido van Rossumf9fca921996-01-12 00:47:05 +0000361static void
Fred Drake4288c802000-07-09 04:36:04 +0000362complex_dealloc(PyObject *op)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000363{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000364 op->ob_type->tp_free(op);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000365}
366
367
Mark Dickinson95bc9802009-04-24 12:46:53 +0000368static PyObject *
Eric Smitha985a3a2009-05-05 18:26:08 +0000369complex_format(PyComplexObject *v, int precision, char format_code)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000370{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000371 PyObject *result = NULL;
372 Py_ssize_t len;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000373
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000374 /* If these are non-NULL, they'll need to be freed. */
375 char *pre = NULL;
376 char *im = NULL;
377 char *buf = NULL;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000378
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000379 /* These do not need to be freed. re is either an alias
380 for pre or a pointer to a constant. lead and tail
381 are pointers to constants. */
382 char *re = NULL;
383 char *lead = "";
384 char *tail = "";
Mark Dickinson95bc9802009-04-24 12:46:53 +0000385
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000386 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
387 re = "";
388 im = PyOS_double_to_string(v->cval.imag, format_code,
389 precision, 0, NULL);
390 if (!im) {
391 PyErr_NoMemory();
392 goto done;
393 }
394 } else {
395 /* Format imaginary part with sign, real part without */
396 pre = PyOS_double_to_string(v->cval.real, format_code,
397 precision, 0, NULL);
398 if (!pre) {
399 PyErr_NoMemory();
400 goto done;
401 }
402 re = pre;
Mark Dickinson95bc9802009-04-24 12:46:53 +0000403
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000404 im = PyOS_double_to_string(v->cval.imag, format_code,
405 precision, Py_DTSF_SIGN, NULL);
406 if (!im) {
407 PyErr_NoMemory();
408 goto done;
409 }
410 lead = "(";
411 tail = ")";
412 }
413 /* Alloc the final buffer. Add one for the "j" in the format string,
414 and one for the trailing zero. */
415 len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
416 buf = PyMem_Malloc(len);
417 if (!buf) {
418 PyErr_NoMemory();
419 goto done;
420 }
421 PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
422 result = PyString_FromString(buf);
Mark Dickinson95bc9802009-04-24 12:46:53 +0000423 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000424 PyMem_Free(im);
425 PyMem_Free(pre);
426 PyMem_Free(buf);
Mark Dickinson95bc9802009-04-24 12:46:53 +0000427
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000428 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000429}
430
431static int
Fred Drake4288c802000-07-09 04:36:04 +0000432complex_print(PyComplexObject *v, FILE *fp, int flags)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000433{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000434 PyObject *formatv;
435 char *buf;
436 if (flags & Py_PRINT_RAW)
437 formatv = complex_format(v, PyFloat_STR_PRECISION, 'g');
438 else
439 formatv = complex_format(v, 0, 'r');
440 if (formatv == NULL)
441 return -1;
442 buf = PyString_AS_STRING(formatv);
443 Py_BEGIN_ALLOW_THREADS
444 fputs(buf, fp);
445 Py_END_ALLOW_THREADS
446 Py_DECREF(formatv);
447 return 0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000448}
449
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000451complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000452{
Eric Smitha985a3a2009-05-05 18:26:08 +0000453 return complex_format(v, 0, 'r');
Tim Peters70695122001-03-11 08:37:29 +0000454}
455
456static PyObject *
457complex_str(PyComplexObject *v)
458{
Eric Smitha985a3a2009-05-05 18:26:08 +0000459 return complex_format(v, PyFloat_STR_PRECISION, 'g');
Guido van Rossumf9fca921996-01-12 00:47:05 +0000460}
461
Guido van Rossumf9fca921996-01-12 00:47:05 +0000462static long
Fred Drake4288c802000-07-09 04:36:04 +0000463complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000464{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000465 long hashreal, hashimag, combined;
466 hashreal = _Py_HashDouble(v->cval.real);
467 if (hashreal == -1)
468 return -1;
469 hashimag = _Py_HashDouble(v->cval.imag);
470 if (hashimag == -1)
471 return -1;
472 /* Note: if the imaginary part is 0, hashimag is 0 now,
473 * so the following returns hashreal unchanged. This is
474 * important because numbers of different types that
475 * compare equal must have the same hash value, so that
476 * hash(x + 0*j) must equal hash(x).
477 */
478 combined = hashreal + 1000003 * hashimag;
479 if (combined == -1)
480 combined = -2;
481 return combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000482}
483
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000484/* This macro may return! */
485#define TO_COMPLEX(obj, c) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 if (PyComplex_Check(obj)) \
487 c = ((PyComplexObject *)(obj))->cval; \
488 else if (to_complex(&(obj), &(c)) < 0) \
489 return (obj)
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000490
491static int
492to_complex(PyObject **pobj, Py_complex *pc)
493{
494 PyObject *obj = *pobj;
495
496 pc->real = pc->imag = 0.0;
497 if (PyInt_Check(obj)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 pc->real = PyInt_AS_LONG(obj);
499 return 0;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000500 }
501 if (PyLong_Check(obj)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000502 pc->real = PyLong_AsDouble(obj);
503 if (pc->real == -1.0 && PyErr_Occurred()) {
504 *pobj = NULL;
505 return -1;
506 }
507 return 0;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000508 }
509 if (PyFloat_Check(obj)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000510 pc->real = PyFloat_AsDouble(obj);
511 return 0;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000512 }
513 Py_INCREF(Py_NotImplemented);
514 *pobj = Py_NotImplemented;
515 return -1;
516}
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000517
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000518
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000519static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000520complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000521{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000522 Py_complex result;
523 Py_complex a, b;
524 TO_COMPLEX(v, a);
525 TO_COMPLEX(w, b);
526 PyFPE_START_PROTECT("complex_add", return 0)
527 result = c_sum(a, b);
528 PyFPE_END_PROTECT(result)
529 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000530}
531
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000533complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000534{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000535 Py_complex result;
536 Py_complex a, b;
537 TO_COMPLEX(v, a);
538 TO_COMPLEX(w, b);;
539 PyFPE_START_PROTECT("complex_sub", return 0)
540 result = c_diff(a, b);
541 PyFPE_END_PROTECT(result)
542 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000543}
544
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000546complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000547{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000548 Py_complex result;
549 Py_complex a, b;
550 TO_COMPLEX(v, a);
551 TO_COMPLEX(w, b);
552 PyFPE_START_PROTECT("complex_mul", return 0)
553 result = c_prod(a, b);
554 PyFPE_END_PROTECT(result)
555 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000556}
557
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000559complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000560{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000561 Py_complex quot;
562 Py_complex a, b;
563 TO_COMPLEX(v, a);
564 TO_COMPLEX(w, b);
565 PyFPE_START_PROTECT("complex_div", return 0)
566 errno = 0;
567 quot = c_quot(a, b);
568 PyFPE_END_PROTECT(quot)
569 if (errno == EDOM) {
570 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
571 return NULL;
572 }
573 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000574}
575
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000576static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000577complex_classic_div(PyObject *v, PyObject *w)
Guido van Rossum393661d2001-08-31 17:40:15 +0000578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000579 Py_complex quot;
580 Py_complex a, b;
581 TO_COMPLEX(v, a);
582 TO_COMPLEX(w, b);
583 if (Py_DivisionWarningFlag >= 2 &&
584 PyErr_Warn(PyExc_DeprecationWarning,
585 "classic complex division") < 0)
586 return NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +0000587
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000588 PyFPE_START_PROTECT("complex_classic_div", return 0)
589 errno = 0;
590 quot = c_quot(a, b);
591 PyFPE_END_PROTECT(quot)
592 if (errno == EDOM) {
593 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
594 return NULL;
595 }
596 return PyComplex_FromCComplex(quot);
Guido van Rossum393661d2001-08-31 17:40:15 +0000597}
598
599static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000600complex_remainder(PyObject *v, PyObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000601{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000602 Py_complex div, mod;
603 Py_complex a, b;
604 TO_COMPLEX(v, a);
605 TO_COMPLEX(w, b);
606 if (PyErr_Warn(PyExc_DeprecationWarning,
607 "complex divmod(), // and % are deprecated") < 0)
608 return NULL;
Guido van Rossum69cf3c72002-04-15 12:39:12 +0000609
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000610 errno = 0;
611 div = c_quot(a, b); /* The raw divisor value. */
612 if (errno == EDOM) {
613 PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
614 return NULL;
615 }
616 div.real = floor(div.real); /* Use the floor of the real part. */
617 div.imag = 0.0;
618 mod = c_diff(a, c_prod(b, div));
Guido van Rossum3be12e91996-09-12 20:56:18 +0000619
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000620 return PyComplex_FromCComplex(mod);
Guido van Rossumee09fc11996-09-11 13:55:55 +0000621}
622
Guido van Rossumee09fc11996-09-11 13:55:55 +0000623
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000625complex_divmod(PyObject *v, PyObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000626{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000627 Py_complex div, mod;
628 PyObject *d, *m, *z;
629 Py_complex a, b;
630 TO_COMPLEX(v, a);
631 TO_COMPLEX(w, b);
632 if (PyErr_Warn(PyExc_DeprecationWarning,
633 "complex divmod(), // and % are deprecated") < 0)
634 return NULL;
Guido van Rossum9ec4c782002-04-15 01:41:56 +0000635
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000636 errno = 0;
637 div = c_quot(a, b); /* The raw divisor value. */
638 if (errno == EDOM) {
639 PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
640 return NULL;
641 }
642 div.real = floor(div.real); /* Use the floor of the real part. */
643 div.imag = 0.0;
644 mod = c_diff(a, c_prod(b, div));
645 d = PyComplex_FromCComplex(div);
646 m = PyComplex_FromCComplex(mod);
647 z = PyTuple_Pack(2, d, m);
648 Py_XDECREF(d);
649 Py_XDECREF(m);
650 return z;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000651}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000652
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000653static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000654complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000655{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000656 Py_complex p;
657 Py_complex exponent;
658 long int_exponent;
659 Py_complex a, b;
660 TO_COMPLEX(v, a);
661 TO_COMPLEX(w, b);
662 if (z!=Py_None) {
663 PyErr_SetString(PyExc_ValueError, "complex modulo");
664 return NULL;
665 }
666 PyFPE_START_PROTECT("complex_pow", return 0)
667 errno = 0;
668 exponent = b;
669 int_exponent = (long)exponent.real;
670 if (exponent.imag == 0. && exponent.real == int_exponent)
671 p = c_powi(a,int_exponent);
672 else
673 p = c_pow(a,exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000674
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000675 PyFPE_END_PROTECT(p)
676 Py_ADJUST_ERANGE2(p.real, p.imag);
677 if (errno == EDOM) {
678 PyErr_SetString(PyExc_ZeroDivisionError,
679 "0.0 to a negative or complex power");
680 return NULL;
681 }
682 else if (errno == ERANGE) {
683 PyErr_SetString(PyExc_OverflowError,
684 "complex exponentiation");
685 return NULL;
686 }
687 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000688}
689
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000690static PyObject *
Mark Dickinson82b34c52010-02-21 12:57:35 +0000691complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000692{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000693 PyObject *t, *r;
694 Py_complex a, b;
695 TO_COMPLEX(v, a);
696 TO_COMPLEX(w, b);
697 if (PyErr_Warn(PyExc_DeprecationWarning,
698 "complex divmod(), // and % are deprecated") < 0)
699 return NULL;
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000700
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000701 t = complex_divmod(v, w);
702 if (t != NULL) {
703 r = PyTuple_GET_ITEM(t, 0);
704 Py_INCREF(r);
705 Py_DECREF(t);
706 return r;
707 }
708 return NULL;
Guido van Rossum4668b002001-08-08 05:00:18 +0000709}
710
711static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000712complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000713{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000714 Py_complex neg;
715 neg.real = -v->cval.real;
716 neg.imag = -v->cval.imag;
717 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000718}
719
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000720static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000721complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000722{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000723 if (PyComplex_CheckExact(v)) {
724 Py_INCREF(v);
725 return (PyObject *)v;
726 }
727 else
728 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000729}
730
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000732complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000733{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000734 double result;
Christian Heimes6f341092008-04-18 23:13:07 +0000735
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000736 PyFPE_START_PROTECT("complex_abs", return 0)
737 result = c_abs(v->cval);
738 PyFPE_END_PROTECT(result)
Christian Heimes6f341092008-04-18 23:13:07 +0000739
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000740 if (errno == ERANGE) {
741 PyErr_SetString(PyExc_OverflowError,
742 "absolute value too large");
743 return NULL;
744 }
745 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000746}
747
748static int
Fred Drake4288c802000-07-09 04:36:04 +0000749complex_nonzero(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000750{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000751 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000752}
753
754static int
Fred Drake4288c802000-07-09 04:36:04 +0000755complex_coerce(PyObject **pv, PyObject **pw)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000756{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000757 Py_complex cval;
758 cval.imag = 0.;
759 if (PyInt_Check(*pw)) {
760 cval.real = (double)PyInt_AsLong(*pw);
761 *pw = PyComplex_FromCComplex(cval);
762 Py_INCREF(*pv);
763 return 0;
764 }
765 else if (PyLong_Check(*pw)) {
766 cval.real = PyLong_AsDouble(*pw);
767 if (cval.real == -1.0 && PyErr_Occurred())
768 return -1;
769 *pw = PyComplex_FromCComplex(cval);
770 Py_INCREF(*pv);
771 return 0;
772 }
773 else if (PyFloat_Check(*pw)) {
774 cval.real = PyFloat_AsDouble(*pw);
775 *pw = PyComplex_FromCComplex(cval);
776 Py_INCREF(*pv);
777 return 0;
778 }
779 else if (PyComplex_Check(*pw)) {
780 Py_INCREF(*pv);
781 Py_INCREF(*pw);
782 return 0;
783 }
784 return 1; /* Can't do it */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000785}
786
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000787static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000788complex_richcompare(PyObject *v, PyObject *w, int op)
789{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000790 PyObject *res;
Mark Dickinson4ca7c3c2010-05-30 13:18:10 +0000791 Py_complex i;
792 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000793
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000794 if (op != Py_EQ && op != Py_NE) {
Mark Dickinson4ca7c3c2010-05-30 13:18:10 +0000795 /* for backwards compatibility, comparisons with non-numbers return
796 * NotImplemented. Only comparisons with core numeric types raise
797 * TypeError.
798 */
799 if (PyInt_Check(w) || PyLong_Check(w) ||
800 PyFloat_Check(w) || PyComplex_Check(w)) {
801 PyErr_SetString(PyExc_TypeError,
802 "no ordering relation is defined "
803 "for complex numbers");
804 return NULL;
805 }
806 goto Unimplemented;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000807 }
Guido van Rossum22056422001-09-24 17:52:04 +0000808
Mark Dickinson4ca7c3c2010-05-30 13:18:10 +0000809 assert(PyComplex_Check(v));
810 TO_COMPLEX(v, i);
811
812 if (PyInt_Check(w) || PyLong_Check(w)) {
813 /* Check for 0.0 imaginary part first to avoid the rich
814 * comparison when possible.
815 */
816 if (i.imag == 0.0) {
817 PyObject *j, *sub_res;
818 j = PyFloat_FromDouble(i.real);
819 if (j == NULL)
820 return NULL;
821
822 sub_res = PyObject_RichCompare(j, w, op);
823 Py_DECREF(j);
824 return sub_res;
825 }
826 else {
827 equal = 0;
828 }
829 }
830 else if (PyFloat_Check(w)) {
831 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
832 }
833 else if (PyComplex_Check(w)) {
834 Py_complex j;
835
836 TO_COMPLEX(w, j);
837 equal = (i.real == j.real && i.imag == j.imag);
838 }
839 else {
840 goto Unimplemented;
841 }
842
843 if (equal == (op == Py_EQ))
844 res = Py_True;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000845 else
Mark Dickinson4ca7c3c2010-05-30 13:18:10 +0000846 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000847
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000848 Py_INCREF(res);
849 return res;
Mark Dickinson4ca7c3c2010-05-30 13:18:10 +0000850
851 Unimplemented:
852 Py_INCREF(Py_NotImplemented);
853 return Py_NotImplemented;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000854}
855
856static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000857complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000858{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000859 PyErr_SetString(PyExc_TypeError,
860 "can't convert complex to int");
861 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000862}
863
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000864static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000865complex_long(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000866{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000867 PyErr_SetString(PyExc_TypeError,
868 "can't convert complex to long");
869 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000870}
871
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000872static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000873complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000874{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000875 PyErr_SetString(PyExc_TypeError,
876 "can't convert complex to float");
877 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000878}
879
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000880static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000881complex_conjugate(PyObject *self)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000882{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000883 Py_complex c;
884 c = ((PyComplexObject *)self)->cval;
885 c.imag = -c.imag;
886 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000887}
888
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000889PyDoc_STRVAR(complex_conjugate_doc,
890"complex.conjugate() -> complex\n"
891"\n"
Ezio Melottieb053162013-10-06 00:39:18 +0300892"Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000893
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000894static PyObject *
895complex_getnewargs(PyComplexObject *v)
896{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000897 Py_complex c = v->cval;
898 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000899}
900
Eric Smith9139cc62009-04-30 00:58:58 +0000901PyDoc_STRVAR(complex__format__doc,
902"complex.__format__() -> str\n"
903"\n"
Ezio Melottieb053162013-10-06 00:39:18 +0300904"Convert to a string according to format_spec.");
Eric Smith9139cc62009-04-30 00:58:58 +0000905
906static PyObject *
907complex__format__(PyObject* self, PyObject* args)
908{
909 PyObject *format_spec;
910
911 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000912 return NULL;
Eric Smith9139cc62009-04-30 00:58:58 +0000913 if (PyBytes_Check(format_spec))
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000914 return _PyComplex_FormatAdvanced(self,
915 PyBytes_AS_STRING(format_spec),
916 PyBytes_GET_SIZE(format_spec));
Eric Smith9139cc62009-04-30 00:58:58 +0000917 if (PyUnicode_Check(format_spec)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000918 /* Convert format_spec to a str */
919 PyObject *result;
920 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smith9139cc62009-04-30 00:58:58 +0000921
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000922 if (str_spec == NULL)
923 return NULL;
Eric Smith9139cc62009-04-30 00:58:58 +0000924
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000925 result = _PyComplex_FormatAdvanced(self,
926 PyBytes_AS_STRING(str_spec),
927 PyBytes_GET_SIZE(str_spec));
Eric Smith9139cc62009-04-30 00:58:58 +0000928
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000929 Py_DECREF(str_spec);
930 return result;
Eric Smith9139cc62009-04-30 00:58:58 +0000931 }
932 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
933 return NULL;
934}
935
Christian Heimes6f341092008-04-18 23:13:07 +0000936#if 0
937static PyObject *
938complex_is_finite(PyObject *self)
939{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000940 Py_complex c;
941 c = ((PyComplexObject *)self)->cval;
942 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
943 Py_IS_FINITE(c.imag)));
Christian Heimes6f341092008-04-18 23:13:07 +0000944}
945
946PyDoc_STRVAR(complex_is_finite_doc,
947"complex.is_finite() -> bool\n"
948"\n"
949"Returns True if the real and the imaginary part is finite.");
950#endif
951
Guido van Rossumf9fca921996-01-12 00:47:05 +0000952static PyMethodDef complex_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000953 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
954 complex_conjugate_doc},
Christian Heimes6f341092008-04-18 23:13:07 +0000955#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000956 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
957 complex_is_finite_doc},
Christian Heimes6f341092008-04-18 23:13:07 +0000958#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000959 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
960 {"__format__", (PyCFunction)complex__format__,
961 METH_VARARGS, complex__format__doc},
962 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000963};
964
Guido van Rossum6f799372001-09-20 20:46:19 +0000965static PyMemberDef complex_members[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000966 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
967 "the real part of a complex number"},
968 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
969 "the imaginary part of a complex number"},
970 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000972
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000973static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +0000974complex_subtype_from_string(PyTypeObject *type, PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000975{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000976 const char *s, *start;
977 char *end;
978 double x=0.0, y=0.0, z;
979 int got_bracket=0;
Guido van Rossum70e36882001-10-25 18:07:22 +0000980#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000981 char *s_buffer = NULL;
Guido van Rossum70e36882001-10-25 18:07:22 +0000982#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000983 Py_ssize_t len;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000984
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000985 if (PyString_Check(v)) {
986 s = PyString_AS_STRING(v);
987 len = PyString_GET_SIZE(v);
988 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000989#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000990 else if (PyUnicode_Check(v)) {
991 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
992 if (s_buffer == NULL)
993 return PyErr_NoMemory();
994 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
995 PyUnicode_GET_SIZE(v),
996 s_buffer,
997 NULL))
998 goto error;
999 s = s_buffer;
1000 len = strlen(s);
1001 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001002#endif
Serhiy Storchaka61565602015-11-20 21:56:21 +02001003 else {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001004 PyErr_SetString(PyExc_TypeError,
1005 "complex() arg is not a string");
1006 return NULL;
1007 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001008
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001009 /* position on first nonblank */
1010 start = s;
1011 while (Py_ISSPACE(*s))
1012 s++;
1013 if (*s == '(') {
1014 /* Skip over possible bracket from repr(). */
1015 got_bracket = 1;
1016 s++;
1017 while (Py_ISSPACE(*s))
1018 s++;
1019 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001020
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001021 /* a valid complex string usually takes one of the three forms:
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001023 <float> - real part only
1024 <float>j - imaginary part only
1025 <float><signed-float>j - real and imaginary parts
Tim Peters6d6c1a32001-08-02 04:15:00 +00001026
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001027 where <float> represents any numeric string that's accepted by the
1028 float constructor (including 'nan', 'inf', 'infinity', etc.), and
1029 <signed-float> is any string of the form <float> whose first
1030 character is '+' or '-'.
Tim Peters6d6c1a32001-08-02 04:15:00 +00001031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001032 For backwards compatibility, the extra forms
Mark Dickinson95bc9802009-04-24 12:46:53 +00001033
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001034 <float><sign>j
1035 <sign>j
1036 j
Mark Dickinson95bc9802009-04-24 12:46:53 +00001037
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 are also accepted, though support for these forms may be removed from
1039 a future version of Python.
1040 */
Mark Dickinson95bc9802009-04-24 12:46:53 +00001041
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001042 /* first look for forms starting with <float> */
1043 z = PyOS_string_to_double(s, &end, NULL);
1044 if (z == -1.0 && PyErr_Occurred()) {
1045 if (PyErr_ExceptionMatches(PyExc_ValueError))
1046 PyErr_Clear();
1047 else
1048 goto error;
1049 }
1050 if (end != s) {
1051 /* all 4 forms starting with <float> land here */
1052 s = end;
1053 if (*s == '+' || *s == '-') {
1054 /* <float><signed-float>j | <float><sign>j */
1055 x = z;
1056 y = PyOS_string_to_double(s, &end, NULL);
1057 if (y == -1.0 && PyErr_Occurred()) {
1058 if (PyErr_ExceptionMatches(PyExc_ValueError))
1059 PyErr_Clear();
1060 else
1061 goto error;
1062 }
1063 if (end != s)
1064 /* <float><signed-float>j */
1065 s = end;
1066 else {
1067 /* <float><sign>j */
1068 y = *s == '+' ? 1.0 : -1.0;
1069 s++;
1070 }
1071 if (!(*s == 'j' || *s == 'J'))
1072 goto parse_error;
1073 s++;
1074 }
1075 else if (*s == 'j' || *s == 'J') {
1076 /* <float>j */
1077 s++;
1078 y = z;
1079 }
1080 else
1081 /* <float> */
1082 x = z;
1083 }
1084 else {
1085 /* not starting with <float>; must be <sign>j or j */
1086 if (*s == '+' || *s == '-') {
1087 /* <sign>j */
1088 y = *s == '+' ? 1.0 : -1.0;
1089 s++;
1090 }
1091 else
1092 /* j */
1093 y = 1.0;
1094 if (!(*s == 'j' || *s == 'J'))
1095 goto parse_error;
1096 s++;
1097 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001098
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001099 /* trailing whitespace and closing bracket */
1100 while (Py_ISSPACE(*s))
1101 s++;
1102 if (got_bracket) {
1103 /* if there was an opening parenthesis, then the corresponding
1104 closing parenthesis should be right here */
1105 if (*s != ')')
1106 goto parse_error;
1107 s++;
1108 while (Py_ISSPACE(*s))
1109 s++;
1110 }
Mark Dickinson95bc9802009-04-24 12:46:53 +00001111
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001112 /* we should now be at the end of the string */
1113 if (s-start != len)
1114 goto parse_error;
Mark Dickinson95bc9802009-04-24 12:46:53 +00001115
Mark Dickinsonc04c7c52009-10-26 22:28:14 +00001116
1117#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001118 if (s_buffer)
1119 PyMem_FREE(s_buffer);
Mark Dickinsonc04c7c52009-10-26 22:28:14 +00001120#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001121 return complex_subtype_from_doubles(type, x, y);
Mark Dickinson95bc9802009-04-24 12:46:53 +00001122
1123 parse_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001124 PyErr_SetString(PyExc_ValueError,
1125 "complex() arg is a malformed string");
Mark Dickinsonc04c7c52009-10-26 22:28:14 +00001126 error:
1127#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001128 if (s_buffer)
1129 PyMem_FREE(s_buffer);
Mark Dickinsonc04c7c52009-10-26 22:28:14 +00001130#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001131 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +00001132}
1133
Tim Peters6d6c1a32001-08-02 04:15:00 +00001134static PyObject *
1135complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1136{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001137 PyObject *r, *i, *tmp;
1138 PyNumberMethods *nbr, *nbi = NULL;
1139 Py_complex cr, ci;
1140 int own_r = 0;
1141 int cr_is_complex = 0;
1142 int ci_is_complex = 0;
1143 static char *kwlist[] = {"real", "imag", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001144
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001145 r = Py_False;
1146 i = NULL;
1147 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
1148 &r, &i))
1149 return NULL;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +00001150
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001151 /* Special-case for a single argument when type(arg) is complex. */
1152 if (PyComplex_CheckExact(r) && i == NULL &&
1153 type == &PyComplex_Type) {
1154 /* Note that we can't know whether it's safe to return
1155 a complex *subclass* instance as-is, hence the restriction
1156 to exact complexes here. If either the input or the
1157 output is a complex subclass, it will be handled below
1158 as a non-orthogonal vector. */
1159 Py_INCREF(r);
1160 return r;
1161 }
1162 if (PyString_Check(r) || PyUnicode_Check(r)) {
1163 if (i != NULL) {
1164 PyErr_SetString(PyExc_TypeError,
1165 "complex() can't take second arg"
1166 " if first is a string");
1167 return NULL;
1168 }
1169 return complex_subtype_from_string(type, r);
1170 }
1171 if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
1172 PyErr_SetString(PyExc_TypeError,
1173 "complex() second arg can't be a string");
1174 return NULL;
1175 }
Tim Peters2400fa42001-09-12 19:12:49 +00001176
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001177 tmp = try_complex_special_method(r);
1178 if (tmp) {
1179 r = tmp;
1180 own_r = 1;
1181 }
1182 else if (PyErr_Occurred()) {
1183 return NULL;
1184 }
Benjamin Peterson36943662010-01-04 01:00:47 +00001185
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001186 nbr = r->ob_type->tp_as_number;
1187 if (i != NULL)
1188 nbi = i->ob_type->tp_as_number;
1189 if (nbr == NULL || nbr->nb_float == NULL ||
1190 ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
1191 PyErr_SetString(PyExc_TypeError,
1192 "complex() argument must be a string or a number");
1193 if (own_r) {
1194 Py_DECREF(r);
1195 }
1196 return NULL;
1197 }
Georg Brandl8f032cb2007-03-13 07:57:51 +00001198
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001199 /* If we get this far, then the "real" and "imag" parts should
1200 both be treated as numbers, and the constructor should return a
1201 complex number equal to (real + imag*1j).
Georg Brandl8f032cb2007-03-13 07:57:51 +00001202
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001203 Note that we do NOT assume the input to already be in canonical
1204 form; the "real" and "imag" parts might themselves be complex
1205 numbers, which slightly complicates the code below. */
1206 if (PyComplex_Check(r)) {
1207 /* Note that if r is of a complex subtype, we're only
1208 retaining its real & imag parts here, and the return
1209 value is (properly) of the builtin complex type. */
1210 cr = ((PyComplexObject*)r)->cval;
1211 cr_is_complex = 1;
1212 if (own_r) {
1213 Py_DECREF(r);
1214 }
1215 }
1216 else {
1217 /* The "real" part really is entirely real, and contributes
1218 nothing in the imaginary direction.
1219 Just treat it as a double. */
1220 tmp = PyNumber_Float(r);
1221 if (own_r) {
1222 /* r was a newly created complex number, rather
1223 than the original "real" argument. */
1224 Py_DECREF(r);
1225 }
1226 if (tmp == NULL)
1227 return NULL;
1228 if (!PyFloat_Check(tmp)) {
1229 PyErr_SetString(PyExc_TypeError,
1230 "float(r) didn't return a float");
1231 Py_DECREF(tmp);
1232 return NULL;
1233 }
1234 cr.real = PyFloat_AsDouble(tmp);
1235 cr.imag = 0.0; /* Shut up compiler warning */
1236 Py_DECREF(tmp);
1237 }
1238 if (i == NULL) {
1239 ci.real = 0.0;
1240 }
1241 else if (PyComplex_Check(i)) {
1242 ci = ((PyComplexObject*)i)->cval;
1243 ci_is_complex = 1;
1244 } else {
1245 /* The "imag" part really is entirely imaginary, and
1246 contributes nothing in the real direction.
1247 Just treat it as a double. */
1248 tmp = (*nbi->nb_float)(i);
1249 if (tmp == NULL)
1250 return NULL;
1251 ci.real = PyFloat_AsDouble(tmp);
1252 Py_DECREF(tmp);
1253 }
1254 /* If the input was in canonical form, then the "real" and "imag"
1255 parts are real numbers, so that ci.imag and cr.imag are zero.
1256 We need this correction in case they were not real numbers. */
Guido van Rossum715ec182007-11-27 22:38:36 +00001257
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001258 if (ci_is_complex) {
1259 cr.real -= ci.imag;
1260 }
1261 if (cr_is_complex) {
1262 ci.real += cr.imag;
1263 }
1264 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001265}
1266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001267PyDoc_STRVAR(complex_doc,
Tim Peters2400fa42001-09-12 19:12:49 +00001268"complex(real[, imag]) -> complex number\n"
1269"\n"
1270"Create a complex number from a real part and an optional imaginary part.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001271"This is equivalent to (real + imag*1j) where imag defaults to 0.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001272
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001273static PyNumberMethods complex_as_number = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001274 (binaryfunc)complex_add, /* nb_add */
1275 (binaryfunc)complex_sub, /* nb_subtract */
1276 (binaryfunc)complex_mul, /* nb_multiply */
1277 (binaryfunc)complex_classic_div, /* nb_divide */
1278 (binaryfunc)complex_remainder, /* nb_remainder */
1279 (binaryfunc)complex_divmod, /* nb_divmod */
1280 (ternaryfunc)complex_pow, /* nb_power */
1281 (unaryfunc)complex_neg, /* nb_negative */
1282 (unaryfunc)complex_pos, /* nb_positive */
1283 (unaryfunc)complex_abs, /* nb_absolute */
1284 (inquiry)complex_nonzero, /* nb_nonzero */
1285 0, /* nb_invert */
1286 0, /* nb_lshift */
1287 0, /* nb_rshift */
1288 0, /* nb_and */
1289 0, /* nb_xor */
1290 0, /* nb_or */
1291 complex_coerce, /* nb_coerce */
1292 complex_int, /* nb_int */
1293 complex_long, /* nb_long */
1294 complex_float, /* nb_float */
1295 0, /* nb_oct */
1296 0, /* nb_hex */
1297 0, /* nb_inplace_add */
1298 0, /* nb_inplace_subtract */
1299 0, /* nb_inplace_multiply*/
1300 0, /* nb_inplace_divide */
1301 0, /* nb_inplace_remainder */
1302 0, /* nb_inplace_power */
1303 0, /* nb_inplace_lshift */
1304 0, /* nb_inplace_rshift */
1305 0, /* nb_inplace_and */
1306 0, /* nb_inplace_xor */
1307 0, /* nb_inplace_or */
1308 (binaryfunc)complex_int_div, /* nb_floor_divide */
1309 (binaryfunc)complex_div, /* nb_true_divide */
1310 0, /* nb_inplace_floor_divide */
1311 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001312};
1313
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001314PyTypeObject PyComplex_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001315 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1316 "complex",
1317 sizeof(PyComplexObject),
1318 0,
1319 complex_dealloc, /* tp_dealloc */
1320 (printfunc)complex_print, /* tp_print */
1321 0, /* tp_getattr */
1322 0, /* tp_setattr */
1323 0, /* tp_compare */
1324 (reprfunc)complex_repr, /* tp_repr */
1325 &complex_as_number, /* tp_as_number */
1326 0, /* tp_as_sequence */
1327 0, /* tp_as_mapping */
1328 (hashfunc)complex_hash, /* tp_hash */
1329 0, /* tp_call */
1330 (reprfunc)complex_str, /* tp_str */
1331 PyObject_GenericGetAttr, /* tp_getattro */
1332 0, /* tp_setattro */
1333 0, /* tp_as_buffer */
1334 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1335 Py_TPFLAGS_BASETYPE, /* tp_flags */
1336 complex_doc, /* tp_doc */
1337 0, /* tp_traverse */
1338 0, /* tp_clear */
1339 complex_richcompare, /* tp_richcompare */
1340 0, /* tp_weaklistoffset */
1341 0, /* tp_iter */
1342 0, /* tp_iternext */
1343 complex_methods, /* tp_methods */
1344 complex_members, /* tp_members */
1345 0, /* tp_getset */
1346 0, /* tp_base */
1347 0, /* tp_dict */
1348 0, /* tp_descr_get */
1349 0, /* tp_descr_set */
1350 0, /* tp_dictoffset */
1351 0, /* tp_init */
1352 PyType_GenericAlloc, /* tp_alloc */
1353 complex_new, /* tp_new */
1354 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001355};
1356
1357#endif