blob: f78c0fdf78def42a5f3cc8f8e25977b05c150a7b [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
Serhiy Storchaka18b250f2017-03-19 08:51:07 +020011/*[clinic input]
12class complex "PyComplexObject *" "&PyComplex_Type"
13[clinic start generated code]*/
14/*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
15
16#include "clinic/complexobject.c.h"
17
Guido van Rossumf9fca921996-01-12 00:47:05 +000018/* elementary operations on complex numbers */
19
Guido van Rossum9e720e31996-07-21 02:31:35 +000020static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000021
Tim Peters0f336042001-03-18 08:21:57 +000022Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040023_Py_c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 Py_complex r;
26 r.real = a.real + b.real;
27 r.imag = a.imag + b.imag;
28 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000029}
30
Tim Peters0f336042001-03-18 08:21:57 +000031Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040032_Py_c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Py_complex r;
35 r.real = a.real - b.real;
36 r.imag = a.imag - b.imag;
37 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000038}
39
Tim Peters0f336042001-03-18 08:21:57 +000040Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040041_Py_c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 Py_complex r;
44 r.real = -a.real;
45 r.imag = -a.imag;
46 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000047}
48
Tim Peters0f336042001-03-18 08:21:57 +000049Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040050_Py_c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 Py_complex r;
53 r.real = a.real*b.real - a.imag*b.imag;
54 r.imag = a.real*b.imag + a.imag*b.real;
55 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000056}
57
Tim Peters0f336042001-03-18 08:21:57 +000058Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040059_Py_c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 /******************************************************************
62 This was the original algorithm. It's grossly prone to spurious
63 overflow and underflow errors. It also merrily divides by 0 despite
64 checking for that(!). The code still serves a doc purpose here, as
65 the algorithm following is a simple by-cases transformation of this
66 one:
Tim Peters0f336042001-03-18 08:21:57 +000067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 Py_complex r;
69 double d = b.real*b.real + b.imag*b.imag;
70 if (d == 0.)
71 errno = EDOM;
72 r.real = (a.real*b.real + a.imag*b.imag)/d;
73 r.imag = (a.imag*b.real - a.real*b.imag)/d;
74 return r;
75 ******************************************************************/
Tim Peters0f336042001-03-18 08:21:57 +000076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 /* This algorithm is better, and is pretty obvious: first divide the
78 * numerators and denominator by whichever of {b.real, b.imag} has
79 * larger magnitude. The earliest reference I found was to CACM
80 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
81 * University). As usual, though, we're still ignoring all IEEE
82 * endcases.
83 */
84 Py_complex r; /* the result */
85 const double abs_breal = b.real < 0 ? -b.real : b.real;
86 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
Tim Peters0f336042001-03-18 08:21:57 +000087
Antoine Pitrou9086f922014-10-10 23:49:32 +020088 if (abs_breal >= abs_bimag) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 /* divide tops and bottom by b.real */
90 if (abs_breal == 0.0) {
91 errno = EDOM;
92 r.real = r.imag = 0.0;
93 }
94 else {
95 const double ratio = b.imag / b.real;
96 const double denom = b.real + b.imag * ratio;
97 r.real = (a.real + a.imag * ratio) / denom;
98 r.imag = (a.imag - a.real * ratio) / denom;
99 }
100 }
Antoine Pitrou9086f922014-10-10 23:49:32 +0200101 else if (abs_bimag >= abs_breal) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 /* divide tops and bottom by b.imag */
103 const double ratio = b.real / b.imag;
104 const double denom = b.real * ratio + b.imag;
105 assert(b.imag != 0.0);
106 r.real = (a.real * ratio + a.imag) / denom;
107 r.imag = (a.imag * ratio - a.real) / denom;
108 }
Antoine Pitrou9086f922014-10-10 23:49:32 +0200109 else {
110 /* At least one of b.real or b.imag is a NaN */
111 r.real = r.imag = Py_NAN;
112 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000114}
115
Tim Peters0f336042001-03-18 08:21:57 +0000116Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400117_Py_c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 Py_complex r;
120 double vabs,len,at,phase;
121 if (b.real == 0. && b.imag == 0.) {
122 r.real = 1.;
123 r.imag = 0.;
124 }
125 else if (a.real == 0. && a.imag == 0.) {
126 if (b.imag != 0. || b.real < 0.)
127 errno = EDOM;
128 r.real = 0.;
129 r.imag = 0.;
130 }
131 else {
132 vabs = hypot(a.real,a.imag);
133 len = pow(vabs,b.real);
134 at = atan2(a.imag, a.real);
135 phase = at*b.real;
136 if (b.imag != 0.0) {
137 len /= exp(at*b.imag);
138 phase += b.imag*log(vabs);
139 }
140 r.real = len*cos(phase);
141 r.imag = len*sin(phase);
142 }
143 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000144}
145
Tim Peters0f336042001-03-18 08:21:57 +0000146static Py_complex
147c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 Py_complex r, p;
150 long mask = 1;
151 r = c_1;
152 p = x;
153 while (mask > 0 && n >= mask) {
154 if (n & mask)
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400155 r = _Py_c_prod(r,p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 mask <<= 1;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400157 p = _Py_c_prod(p,p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 }
159 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000160}
161
Tim Peters0f336042001-03-18 08:21:57 +0000162static Py_complex
163c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 if (n > 100 || n < -100) {
168 cn.real = (double) n;
169 cn.imag = 0.;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400170 return _Py_c_pow(x,cn);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 }
172 else if (n > 0)
173 return c_powu(x,n);
174 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400175 return _Py_c_quot(c_1, c_powu(x,-n));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000176
177}
178
Christian Heimes53876d92008-04-19 00:31:39 +0000179double
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400180_Py_c_abs(Py_complex z)
Christian Heimes53876d92008-04-19 00:31:39 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
183 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
186 /* C99 rules: if either the real or the imaginary part is an
187 infinity, return infinity, even if the other part is a
188 NaN. */
189 if (Py_IS_INFINITY(z.real)) {
190 result = fabs(z.real);
191 errno = 0;
192 return result;
193 }
194 if (Py_IS_INFINITY(z.imag)) {
195 result = fabs(z.imag);
196 errno = 0;
197 return result;
198 }
199 /* either the real or imaginary part is a NaN,
200 and neither is infinite. Result should be NaN. */
201 return Py_NAN;
202 }
203 result = hypot(z.real, z.imag);
204 if (!Py_IS_FINITE(result))
205 errno = ERANGE;
206 else
207 errno = 0;
208 return result;
Christian Heimes53876d92008-04-19 00:31:39 +0000209}
210
Tim Peters6d6c1a32001-08-02 04:15:00 +0000211static PyObject *
212complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 PyObject *op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 op = type->tp_alloc(type, 0);
217 if (op != NULL)
218 ((PyComplexObject *)op)->cval = cval;
219 return op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000220}
221
Guido van Rossumf9fca921996-01-12 00:47:05 +0000222PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000223PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000224{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200225 PyComplexObject *op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 /* Inline PyObject_New */
228 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
229 if (op == NULL)
230 return PyErr_NoMemory();
Victor Stinnerb509d522018-11-23 14:27:38 +0100231 (void)PyObject_INIT(op, &PyComplex_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 op->cval = cval;
233 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000234}
235
Tim Peters6d6c1a32001-08-02 04:15:00 +0000236static PyObject *
237complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 Py_complex c;
240 c.real = real;
241 c.imag = imag;
242 return complex_subtype_from_c_complex(type, c);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000243}
244
Guido van Rossumf9fca921996-01-12 00:47:05 +0000245PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000246PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_complex c;
249 c.real = real;
250 c.imag = imag;
251 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000252}
253
254double
Fred Drake4288c802000-07-09 04:36:04 +0000255PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (PyComplex_Check(op)) {
258 return ((PyComplexObject *)op)->cval.real;
259 }
260 else {
261 return PyFloat_AsDouble(op);
262 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000263}
264
265double
Fred Drake4288c802000-07-09 04:36:04 +0000266PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 if (PyComplex_Check(op)) {
269 return ((PyComplexObject *)op)->cval.imag;
270 }
271 else {
272 return 0.0;
273 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000274}
275
Benjamin Petersonaea44282010-01-04 01:10:28 +0000276static PyObject *
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200277try_complex_special_method(PyObject *op)
278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyObject *f;
Benjamin Petersonce798522012-01-22 11:24:29 -0500280 _Py_IDENTIFIER(__complex__);
Benjamin Petersonaea44282010-01-04 01:10:28 +0000281
Benjamin Petersonce798522012-01-22 11:24:29 -0500282 f = _PyObject_LookupSpecial(op, &PyId___complex__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (f) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100284 PyObject *res = _PyObject_CallNoArg(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 Py_DECREF(f);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200286 if (!res || PyComplex_CheckExact(res)) {
287 return res;
288 }
289 if (!PyComplex_Check(res)) {
290 PyErr_Format(PyExc_TypeError,
291 "__complex__ returned non-complex (type %.200s)",
292 res->ob_type->tp_name);
293 Py_DECREF(res);
294 return NULL;
295 }
296 /* Issue #29894: warn if 'res' not of exact type complex. */
297 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
298 "__complex__ returned non-complex (type %.200s). "
299 "The ability to return an instance of a strict subclass of complex "
300 "is deprecated, and may be removed in a future version of Python.",
301 res->ob_type->tp_name)) {
Mark Dickinsond20fb822012-11-14 17:08:31 +0000302 Py_DECREF(res);
303 return NULL;
304 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 return res;
306 }
307 return NULL;
Benjamin Petersonaea44282010-01-04 01:10:28 +0000308}
309
Guido van Rossum9e720e31996-07-21 02:31:35 +0000310Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000311PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 Py_complex cv;
314 PyObject *newop = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 assert(op);
317 /* If op is already of type PyComplex_Type, return its value */
318 if (PyComplex_Check(op)) {
319 return ((PyComplexObject *)op)->cval;
320 }
321 /* If not, use op's __complex__ method, if it exists */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 /* return -1 on failure */
324 cv.real = -1.;
325 cv.imag = 0.;
326
327 newop = try_complex_special_method(op);
328
329 if (newop) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 cv = ((PyComplexObject *)newop)->cval;
331 Py_DECREF(newop);
332 return cv;
333 }
334 else if (PyErr_Occurred()) {
335 return cv;
336 }
337 /* If neither of the above works, interpret op as a float giving the
338 real part of the result, and fill in the imaginary part as 0. */
339 else {
340 /* PyFloat_AsDouble will return -1 on failure */
341 cv.real = PyFloat_AsDouble(op);
342 return cv;
343 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000344}
345
Eric Smith0923d1d2009-04-16 20:16:10 +0000346static PyObject *
Eric Smith70099a12010-12-04 13:27:34 +0000347complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000348{
Eric Smith70099a12010-12-04 13:27:34 +0000349 int precision = 0;
350 char format_code = 'r';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 PyObject *result = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 /* If these are non-NULL, they'll need to be freed. */
354 char *pre = NULL;
355 char *im = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 /* These do not need to be freed. re is either an alias
358 for pre or a pointer to a constant. lead and tail
359 are pointers to constants. */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200360 const char *re = NULL;
361 const char *lead = "";
362 const char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
Eric Smith70099a12010-12-04 13:27:34 +0000365 /* Real part is +0: just output the imaginary part and do not
366 include parens. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 re = "";
368 im = PyOS_double_to_string(v->cval.imag, format_code,
369 precision, 0, NULL);
370 if (!im) {
371 PyErr_NoMemory();
372 goto done;
373 }
374 } else {
Eric Smith70099a12010-12-04 13:27:34 +0000375 /* Format imaginary part with sign, real part without. Include
376 parens in the result. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 pre = PyOS_double_to_string(v->cval.real, format_code,
378 precision, 0, NULL);
379 if (!pre) {
380 PyErr_NoMemory();
381 goto done;
382 }
383 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 im = PyOS_double_to_string(v->cval.imag, format_code,
386 precision, Py_DTSF_SIGN, NULL);
387 if (!im) {
388 PyErr_NoMemory();
389 goto done;
390 }
391 lead = "(";
392 tail = ")";
393 }
Victor Stinner6ced7c42011-03-21 18:15:42 +0100394 result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000395 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 PyMem_Free(im);
397 PyMem_Free(pre);
Eric Smith0923d1d2009-04-16 20:16:10 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000400}
401
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000402static Py_hash_t
Fred Drake4288c802000-07-09 04:36:04 +0000403complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000404{
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000405 Py_uhash_t hashreal, hashimag, combined;
406 hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real);
407 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 return -1;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000409 hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag);
410 if (hashimag == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 return -1;
412 /* Note: if the imaginary part is 0, hashimag is 0 now,
413 * so the following returns hashreal unchanged. This is
414 * important because numbers of different types that
415 * compare equal must have the same hash value, so that
416 * hash(x + 0*j) must equal hash(x).
417 */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000418 combined = hashreal + _PyHASH_IMAG * hashimag;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000419 if (combined == (Py_uhash_t)-1)
420 combined = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000421 return (Py_hash_t)combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000422}
423
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000424/* This macro may return! */
425#define TO_COMPLEX(obj, c) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (PyComplex_Check(obj)) \
427 c = ((PyComplexObject *)(obj))->cval; \
428 else if (to_complex(&(obj), &(c)) < 0) \
429 return (obj)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000430
431static int
432to_complex(PyObject **pobj, Py_complex *pc)
433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 pc->real = pc->imag = 0.0;
437 if (PyLong_Check(obj)) {
438 pc->real = PyLong_AsDouble(obj);
439 if (pc->real == -1.0 && PyErr_Occurred()) {
440 *pobj = NULL;
441 return -1;
442 }
443 return 0;
444 }
445 if (PyFloat_Check(obj)) {
446 pc->real = PyFloat_AsDouble(obj);
447 return 0;
448 }
449 Py_INCREF(Py_NotImplemented);
450 *pobj = Py_NotImplemented;
451 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000452}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000456complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 Py_complex result;
459 Py_complex a, b;
460 TO_COMPLEX(v, a);
461 TO_COMPLEX(w, b);
462 PyFPE_START_PROTECT("complex_add", return 0)
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400463 result = _Py_c_sum(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 PyFPE_END_PROTECT(result)
465 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000466}
467
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000469complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_complex result;
472 Py_complex a, b;
473 TO_COMPLEX(v, a);
474 TO_COMPLEX(w, b);
475 PyFPE_START_PROTECT("complex_sub", return 0)
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400476 result = _Py_c_diff(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyFPE_END_PROTECT(result)
478 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000479}
480
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000482complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 Py_complex result;
485 Py_complex a, b;
486 TO_COMPLEX(v, a);
487 TO_COMPLEX(w, b);
488 PyFPE_START_PROTECT("complex_mul", return 0)
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400489 result = _Py_c_prod(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 PyFPE_END_PROTECT(result)
491 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000492}
493
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000495complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 Py_complex quot;
498 Py_complex a, b;
499 TO_COMPLEX(v, a);
500 TO_COMPLEX(w, b);
501 PyFPE_START_PROTECT("complex_div", return 0)
502 errno = 0;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400503 quot = _Py_c_quot(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyFPE_END_PROTECT(quot)
505 if (errno == EDOM) {
506 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
507 return NULL;
508 }
509 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000510}
511
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000513complex_remainder(PyObject *v, PyObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyErr_SetString(PyExc_TypeError,
516 "can't mod complex numbers.");
517 return NULL;
Guido van Rossumee09fc11996-09-11 13:55:55 +0000518}
519
Guido van Rossumee09fc11996-09-11 13:55:55 +0000520
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000521static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000522complex_divmod(PyObject *v, PyObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 PyErr_SetString(PyExc_TypeError,
525 "can't take floor or mod of complex number.");
526 return NULL;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000527}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000528
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000529static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000530complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 Py_complex p;
533 Py_complex exponent;
534 long int_exponent;
535 Py_complex a, b;
536 TO_COMPLEX(v, a);
537 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (z != Py_None) {
540 PyErr_SetString(PyExc_ValueError, "complex modulo");
541 return NULL;
542 }
543 PyFPE_START_PROTECT("complex_pow", return 0)
544 errno = 0;
545 exponent = b;
546 int_exponent = (long)exponent.real;
547 if (exponent.imag == 0. && exponent.real == int_exponent)
548 p = c_powi(a, int_exponent);
549 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400550 p = _Py_c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyFPE_END_PROTECT(p)
553 Py_ADJUST_ERANGE2(p.real, p.imag);
554 if (errno == EDOM) {
555 PyErr_SetString(PyExc_ZeroDivisionError,
556 "0.0 to a negative or complex power");
557 return NULL;
558 }
559 else if (errno == ERANGE) {
560 PyErr_SetString(PyExc_OverflowError,
561 "complex exponentiation");
562 return NULL;
563 }
564 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000565}
566
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000567static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000568complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 PyErr_SetString(PyExc_TypeError,
571 "can't take floor of complex number.");
572 return NULL;
Guido van Rossum4668b002001-08-08 05:00:18 +0000573}
574
575static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000576complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 Py_complex neg;
579 neg.real = -v->cval.real;
580 neg.imag = -v->cval.imag;
581 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000582}
583
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000584static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000585complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 if (PyComplex_CheckExact(v)) {
588 Py_INCREF(v);
589 return (PyObject *)v;
590 }
591 else
592 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000593}
594
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000595static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000596complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyFPE_START_PROTECT("complex_abs", return 0)
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400601 result = _Py_c_abs(v->cval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 PyFPE_END_PROTECT(result)
Christian Heimes53876d92008-04-19 00:31:39 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (errno == ERANGE) {
605 PyErr_SetString(PyExc_OverflowError,
606 "absolute value too large");
607 return NULL;
608 }
609 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000610}
611
612static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000613complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000616}
617
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000619complex_richcompare(PyObject *v, PyObject *w, int op)
620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000622 Py_complex i;
623 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000626 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 }
Guido van Rossum22056422001-09-24 17:52:04 +0000628
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000629 assert(PyComplex_Check(v));
630 TO_COMPLEX(v, i);
631
632 if (PyLong_Check(w)) {
633 /* Check for 0.0 imaginary part first to avoid the rich
634 * comparison when possible.
635 */
636 if (i.imag == 0.0) {
637 PyObject *j, *sub_res;
638 j = PyFloat_FromDouble(i.real);
639 if (j == NULL)
640 return NULL;
641
642 sub_res = PyObject_RichCompare(j, w, op);
643 Py_DECREF(j);
644 return sub_res;
645 }
646 else {
647 equal = 0;
648 }
649 }
650 else if (PyFloat_Check(w)) {
651 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
652 }
653 else if (PyComplex_Check(w)) {
654 Py_complex j;
655
656 TO_COMPLEX(w, j);
657 equal = (i.real == j.real && i.imag == j.imag);
658 }
659 else {
660 goto Unimplemented;
661 }
662
663 if (equal == (op == Py_EQ))
664 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000666 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 Py_INCREF(res);
669 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000670
671Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500672 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000673}
674
675static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000676complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyErr_SetString(PyExc_TypeError,
679 "can't convert complex to int");
680 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000681}
682
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000683static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000684complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyErr_SetString(PyExc_TypeError,
687 "can't convert complex to float");
688 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000689}
690
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000691static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530692complex_conjugate(PyObject *self, PyObject *Py_UNUSED(ignored))
Guido van Rossumf9fca921996-01-12 00:47:05 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 Py_complex c;
695 c = ((PyComplexObject *)self)->cval;
696 c.imag = -c.imag;
697 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000698}
699
Guido van Rossum46334cd2007-08-01 17:43:15 +0000700PyDoc_STRVAR(complex_conjugate_doc,
701"complex.conjugate() -> complex\n"
702"\n"
Ezio Melotti488d2442013-10-06 00:39:18 +0300703"Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
Guido van Rossum46334cd2007-08-01 17:43:15 +0000704
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000705static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530706complex_getnewargs(PyComplexObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 Py_complex c = v->cval;
709 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000710}
711
Eric Smith58a42242009-04-30 01:00:33 +0000712PyDoc_STRVAR(complex__format__doc,
713"complex.__format__() -> str\n"
714"\n"
Ezio Melotti488d2442013-10-06 00:39:18 +0300715"Convert to a string according to format_spec.");
Eric Smith58a42242009-04-30 01:00:33 +0000716
717static PyObject *
718complex__format__(PyObject* self, PyObject* args)
719{
720 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200721 _PyUnicodeWriter writer;
722 int ret;
Eric Smith58a42242009-04-30 01:00:33 +0000723
724 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
Victor Stinnerd3f08822012-05-29 12:57:52 +0200725 return NULL;
726
Victor Stinner8f674cc2013-04-17 23:02:17 +0200727 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +0200728 ret = _PyComplex_FormatAdvancedWriter(
729 &writer,
730 self,
731 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
732 if (ret == -1) {
733 _PyUnicodeWriter_Dealloc(&writer);
734 return NULL;
735 }
736 return _PyUnicodeWriter_Finish(&writer);
Eric Smith58a42242009-04-30 01:00:33 +0000737}
738
Christian Heimes53876d92008-04-19 00:31:39 +0000739#if 0
740static PyObject *
741complex_is_finite(PyObject *self)
742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 Py_complex c;
744 c = ((PyComplexObject *)self)->cval;
745 return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
746 Py_IS_FINITE(c.imag)));
Christian Heimes53876d92008-04-19 00:31:39 +0000747}
748
749PyDoc_STRVAR(complex_is_finite_doc,
750"complex.is_finite() -> bool\n"
751"\n"
752"Returns True if the real and the imaginary part is finite.");
753#endif
754
Guido van Rossumf9fca921996-01-12 00:47:05 +0000755static PyMethodDef complex_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
757 complex_conjugate_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000758#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
760 complex_is_finite_doc},
Christian Heimes53876d92008-04-19 00:31:39 +0000761#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
763 {"__format__", (PyCFunction)complex__format__,
764 METH_VARARGS, complex__format__doc},
765 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000766};
767
Guido van Rossum6f799372001-09-20 20:46:19 +0000768static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
770 "the real part of a complex number"},
771 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
772 "the imaginary part of a complex number"},
773 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000774};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000775
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000776static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700777complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 double x=0.0, y=0.0, z;
780 int got_bracket=0;
Brett Cannona721aba2016-09-09 14:57:09 -0700781 const char *start;
782 char *end;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* position on first nonblank */
785 start = s;
786 while (Py_ISSPACE(*s))
787 s++;
788 if (*s == '(') {
789 /* Skip over possible bracket from repr(). */
790 got_bracket = 1;
791 s++;
792 while (Py_ISSPACE(*s))
793 s++;
794 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 <float> - real part only
799 <float>j - imaginary part only
800 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 where <float> represents any numeric string that's accepted by the
803 float constructor (including 'nan', 'inf', 'infinity', etc.), and
804 <signed-float> is any string of the form <float> whose first
805 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 <float><sign>j
810 <sign>j
811 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 are also accepted, though support for these forms may be removed from
814 a future version of Python.
815 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 /* first look for forms starting with <float> */
818 z = PyOS_string_to_double(s, &end, NULL);
819 if (z == -1.0 && PyErr_Occurred()) {
820 if (PyErr_ExceptionMatches(PyExc_ValueError))
821 PyErr_Clear();
822 else
Brett Cannona721aba2016-09-09 14:57:09 -0700823 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 }
825 if (end != s) {
826 /* all 4 forms starting with <float> land here */
827 s = end;
828 if (*s == '+' || *s == '-') {
829 /* <float><signed-float>j | <float><sign>j */
830 x = z;
831 y = PyOS_string_to_double(s, &end, NULL);
832 if (y == -1.0 && PyErr_Occurred()) {
833 if (PyErr_ExceptionMatches(PyExc_ValueError))
834 PyErr_Clear();
835 else
Brett Cannona721aba2016-09-09 14:57:09 -0700836 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 }
838 if (end != s)
839 /* <float><signed-float>j */
840 s = end;
841 else {
842 /* <float><sign>j */
843 y = *s == '+' ? 1.0 : -1.0;
844 s++;
845 }
846 if (!(*s == 'j' || *s == 'J'))
847 goto parse_error;
848 s++;
849 }
850 else if (*s == 'j' || *s == 'J') {
851 /* <float>j */
852 s++;
853 y = z;
854 }
855 else
856 /* <float> */
857 x = z;
858 }
859 else {
860 /* not starting with <float>; must be <sign>j or j */
861 if (*s == '+' || *s == '-') {
862 /* <sign>j */
863 y = *s == '+' ? 1.0 : -1.0;
864 s++;
865 }
866 else
867 /* j */
868 y = 1.0;
869 if (!(*s == 'j' || *s == 'J'))
870 goto parse_error;
871 s++;
872 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 /* trailing whitespace and closing bracket */
875 while (Py_ISSPACE(*s))
876 s++;
877 if (got_bracket) {
878 /* if there was an opening parenthesis, then the corresponding
879 closing parenthesis should be right here */
880 if (*s != ')')
881 goto parse_error;
882 s++;
883 while (Py_ISSPACE(*s))
884 s++;
885 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 /* we should now be at the end of the string */
888 if (s-start != len)
889 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000890
Brett Cannona721aba2016-09-09 14:57:09 -0700891 return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000892
Mark Dickinson6649fa42009-04-24 13:25:20 +0000893 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 PyErr_SetString(PyExc_ValueError,
895 "complex() arg is a malformed string");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000897}
898
Tim Peters6d6c1a32001-08-02 04:15:00 +0000899static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700900complex_subtype_from_string(PyTypeObject *type, PyObject *v)
901{
902 const char *s;
903 PyObject *s_buffer = NULL, *result = NULL;
904 Py_ssize_t len;
905
906 if (PyUnicode_Check(v)) {
907 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
908 if (s_buffer == NULL) {
909 return NULL;
910 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200911 assert(PyUnicode_IS_ASCII(s_buffer));
912 /* Simply get a pointer to existing ASCII characters. */
Brett Cannona721aba2016-09-09 14:57:09 -0700913 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200914 assert(s != NULL);
Brett Cannona721aba2016-09-09 14:57:09 -0700915 }
916 else {
917 PyErr_Format(PyExc_TypeError,
918 "complex() argument must be a string or a number, not '%.200s'",
919 Py_TYPE(v)->tp_name);
920 return NULL;
921 }
922
923 result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
924 complex_from_string_inner);
Brett Cannona721aba2016-09-09 14:57:09 -0700925 Py_DECREF(s_buffer);
926 return result;
927}
928
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200929/*[clinic input]
930@classmethod
931complex.__new__ as complex_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300932 real as r: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200933 imag as i: object(c_default="NULL") = 0
934
935Create a complex number from a real part and an optional imaginary part.
936
937This is equivalent to (real + imag*1j) where imag defaults to 0.
938[clinic start generated code]*/
939
Brett Cannona721aba2016-09-09 14:57:09 -0700940static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200941complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
Serhiy Storchakabae68812017-04-05 12:00:42 +0300942/*[clinic end generated code: output=b6c7dd577b537dc1 input=6f6b0bedba29bcb5]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000943{
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200944 PyObject *tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyNumberMethods *nbr, *nbi = NULL;
946 Py_complex cr, ci;
947 int own_r = 0;
948 int cr_is_complex = 0;
949 int ci_is_complex = 0;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* Special-case for a single argument when type(arg) is complex. */
952 if (PyComplex_CheckExact(r) && i == NULL &&
953 type == &PyComplex_Type) {
954 /* Note that we can't know whether it's safe to return
955 a complex *subclass* instance as-is, hence the restriction
956 to exact complexes here. If either the input or the
957 output is a complex subclass, it will be handled below
958 as a non-orthogonal vector. */
959 Py_INCREF(r);
960 return r;
961 }
962 if (PyUnicode_Check(r)) {
963 if (i != NULL) {
964 PyErr_SetString(PyExc_TypeError,
965 "complex() can't take second arg"
966 " if first is a string");
967 return NULL;
968 }
969 return complex_subtype_from_string(type, r);
970 }
971 if (i != NULL && PyUnicode_Check(i)) {
972 PyErr_SetString(PyExc_TypeError,
973 "complex() second arg can't be a string");
974 return NULL;
975 }
Tim Peters2400fa42001-09-12 19:12:49 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 tmp = try_complex_special_method(r);
978 if (tmp) {
979 r = tmp;
980 own_r = 1;
981 }
982 else if (PyErr_Occurred()) {
983 return NULL;
984 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 nbr = r->ob_type->tp_as_number;
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300987 if (nbr == NULL || (nbr->nb_float == NULL && nbr->nb_index == NULL)) {
Ezio Melottia5b95992013-11-07 19:18:34 +0200988 PyErr_Format(PyExc_TypeError,
Mark Dickinson613f8e52016-09-24 15:26:36 +0100989 "complex() first argument must be a string or a number, "
990 "not '%.200s'",
991 Py_TYPE(r)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (own_r) {
993 Py_DECREF(r);
994 }
995 return NULL;
996 }
Mark Dickinson613f8e52016-09-24 15:26:36 +0100997 if (i != NULL) {
998 nbi = i->ob_type->tp_as_number;
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300999 if (nbi == NULL || (nbi->nb_float == NULL && nbi->nb_index == NULL)) {
Mark Dickinson613f8e52016-09-24 15:26:36 +01001000 PyErr_Format(PyExc_TypeError,
1001 "complex() second argument must be a number, "
1002 "not '%.200s'",
1003 Py_TYPE(i)->tp_name);
1004 if (own_r) {
1005 Py_DECREF(r);
1006 }
1007 return NULL;
1008 }
1009 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 /* If we get this far, then the "real" and "imag" parts should
1012 both be treated as numbers, and the constructor should return a
1013 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 Note that we do NOT assume the input to already be in canonical
1016 form; the "real" and "imag" parts might themselves be complex
1017 numbers, which slightly complicates the code below. */
1018 if (PyComplex_Check(r)) {
1019 /* Note that if r is of a complex subtype, we're only
1020 retaining its real & imag parts here, and the return
1021 value is (properly) of the builtin complex type. */
1022 cr = ((PyComplexObject*)r)->cval;
1023 cr_is_complex = 1;
1024 if (own_r) {
1025 Py_DECREF(r);
1026 }
1027 }
1028 else {
1029 /* The "real" part really is entirely real, and contributes
1030 nothing in the imaginary direction.
1031 Just treat it as a double. */
1032 tmp = PyNumber_Float(r);
1033 if (own_r) {
1034 /* r was a newly created complex number, rather
1035 than the original "real" argument. */
1036 Py_DECREF(r);
1037 }
1038 if (tmp == NULL)
1039 return NULL;
Serhiy Storchaka671079e2017-03-24 21:28:43 +02001040 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 cr.real = PyFloat_AsDouble(tmp);
Mark Dickinson112ec382017-02-20 20:28:15 +00001042 cr.imag = 0.0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 Py_DECREF(tmp);
1044 }
1045 if (i == NULL) {
Mark Dickinson112ec382017-02-20 20:28:15 +00001046 ci.real = cr.imag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 }
1048 else if (PyComplex_Check(i)) {
1049 ci = ((PyComplexObject*)i)->cval;
1050 ci_is_complex = 1;
1051 } else {
1052 /* The "imag" part really is entirely imaginary, and
1053 contributes nothing in the real direction.
1054 Just treat it as a double. */
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001055 tmp = PyNumber_Float(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (tmp == NULL)
1057 return NULL;
1058 ci.real = PyFloat_AsDouble(tmp);
1059 Py_DECREF(tmp);
1060 }
1061 /* If the input was in canonical form, then the "real" and "imag"
1062 parts are real numbers, so that ci.imag and cr.imag are zero.
1063 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (ci_is_complex) {
1066 cr.real -= ci.imag;
1067 }
Mark Dickinson112ec382017-02-20 20:28:15 +00001068 if (cr_is_complex && i != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 ci.real += cr.imag;
1070 }
1071 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001072}
1073
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001074static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 (binaryfunc)complex_add, /* nb_add */
1076 (binaryfunc)complex_sub, /* nb_subtract */
1077 (binaryfunc)complex_mul, /* nb_multiply */
1078 (binaryfunc)complex_remainder, /* nb_remainder */
1079 (binaryfunc)complex_divmod, /* nb_divmod */
1080 (ternaryfunc)complex_pow, /* nb_power */
1081 (unaryfunc)complex_neg, /* nb_negative */
1082 (unaryfunc)complex_pos, /* nb_positive */
1083 (unaryfunc)complex_abs, /* nb_absolute */
1084 (inquiry)complex_bool, /* nb_bool */
1085 0, /* nb_invert */
1086 0, /* nb_lshift */
1087 0, /* nb_rshift */
1088 0, /* nb_and */
1089 0, /* nb_xor */
1090 0, /* nb_or */
1091 complex_int, /* nb_int */
1092 0, /* nb_reserved */
1093 complex_float, /* nb_float */
1094 0, /* nb_inplace_add */
1095 0, /* nb_inplace_subtract */
1096 0, /* nb_inplace_multiply*/
1097 0, /* nb_inplace_remainder */
1098 0, /* nb_inplace_power */
1099 0, /* nb_inplace_lshift */
1100 0, /* nb_inplace_rshift */
1101 0, /* nb_inplace_and */
1102 0, /* nb_inplace_xor */
1103 0, /* nb_inplace_or */
1104 (binaryfunc)complex_int_div, /* nb_floor_divide */
1105 (binaryfunc)complex_div, /* nb_true_divide */
1106 0, /* nb_inplace_floor_divide */
1107 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001108};
1109
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001110PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1112 "complex",
1113 sizeof(PyComplexObject),
1114 0,
Inada Naoki7d408692019-05-29 17:23:27 +09001115 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001116 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 0, /* tp_getattr */
1118 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001119 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 (reprfunc)complex_repr, /* tp_repr */
1121 &complex_as_number, /* tp_as_number */
1122 0, /* tp_as_sequence */
1123 0, /* tp_as_mapping */
1124 (hashfunc)complex_hash, /* tp_hash */
1125 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001126 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyObject_GenericGetAttr, /* tp_getattro */
1128 0, /* tp_setattro */
1129 0, /* tp_as_buffer */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001130 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1131 complex_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 0, /* tp_traverse */
1133 0, /* tp_clear */
1134 complex_richcompare, /* tp_richcompare */
1135 0, /* tp_weaklistoffset */
1136 0, /* tp_iter */
1137 0, /* tp_iternext */
1138 complex_methods, /* tp_methods */
1139 complex_members, /* tp_members */
1140 0, /* tp_getset */
1141 0, /* tp_base */
1142 0, /* tp_dict */
1143 0, /* tp_descr_get */
1144 0, /* tp_descr_set */
1145 0, /* tp_dictoffset */
1146 0, /* tp_init */
1147 PyType_GenericAlloc, /* tp_alloc */
1148 complex_new, /* tp_new */
1149 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001150};