blob: 69f6c17b4a49cd08e0806e183012cbaec393fa6e [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"
Victor Stinner04fc4f22020-06-16 01:28:07 +02009#include "pycore_object.h" // _PyObject_Init()
Victor Stinner4a21e572020-04-15 02:35:41 +020010#include "structmember.h" // PyMemberDef
Guido van Rossumf9fca921996-01-12 00:47:05 +000011
Victor Stinner04fc4f22020-06-16 01:28:07 +020012
Serhiy Storchaka18b250f2017-03-19 08:51:07 +020013/*[clinic input]
14class complex "PyComplexObject *" "&PyComplex_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
17
18#include "clinic/complexobject.c.h"
19
Guido van Rossumf9fca921996-01-12 00:47:05 +000020/* elementary operations on complex numbers */
21
Guido van Rossum9e720e31996-07-21 02:31:35 +000022static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000023
Tim Peters0f336042001-03-18 08:21:57 +000024Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040025_Py_c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 Py_complex r;
28 r.real = a.real + b.real;
29 r.imag = a.imag + b.imag;
30 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000031}
32
Tim Peters0f336042001-03-18 08:21:57 +000033Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040034_Py_c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040043_Py_c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 Py_complex r;
46 r.real = -a.real;
47 r.imag = -a.imag;
48 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000049}
50
Tim Peters0f336042001-03-18 08:21:57 +000051Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040052_Py_c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 Py_complex r;
55 r.real = a.real*b.real - a.imag*b.imag;
56 r.imag = a.real*b.imag + a.imag*b.real;
57 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000058}
59
Paul Monsonff6bb0a2019-06-12 11:08:40 -070060/* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
61#ifdef _M_ARM64
62#pragma optimize("", off)
63#endif
Tim Peters0f336042001-03-18 08:21:57 +000064Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040065_Py_c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 /******************************************************************
68 This was the original algorithm. It's grossly prone to spurious
69 overflow and underflow errors. It also merrily divides by 0 despite
70 checking for that(!). The code still serves a doc purpose here, as
71 the algorithm following is a simple by-cases transformation of this
72 one:
Tim Peters0f336042001-03-18 08:21:57 +000073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 Py_complex r;
75 double d = b.real*b.real + b.imag*b.imag;
76 if (d == 0.)
77 errno = EDOM;
78 r.real = (a.real*b.real + a.imag*b.imag)/d;
79 r.imag = (a.imag*b.real - a.real*b.imag)/d;
80 return r;
81 ******************************************************************/
Tim Peters0f336042001-03-18 08:21:57 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 /* This algorithm is better, and is pretty obvious: first divide the
84 * numerators and denominator by whichever of {b.real, b.imag} has
85 * larger magnitude. The earliest reference I found was to CACM
86 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
87 * University). As usual, though, we're still ignoring all IEEE
88 * endcases.
89 */
90 Py_complex r; /* the result */
91 const double abs_breal = b.real < 0 ? -b.real : b.real;
92 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
Tim Peters0f336042001-03-18 08:21:57 +000093
Antoine Pitrou9086f922014-10-10 23:49:32 +020094 if (abs_breal >= abs_bimag) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 /* divide tops and bottom by b.real */
96 if (abs_breal == 0.0) {
97 errno = EDOM;
98 r.real = r.imag = 0.0;
99 }
100 else {
101 const double ratio = b.imag / b.real;
102 const double denom = b.real + b.imag * ratio;
103 r.real = (a.real + a.imag * ratio) / denom;
104 r.imag = (a.imag - a.real * ratio) / denom;
105 }
106 }
Antoine Pitrou9086f922014-10-10 23:49:32 +0200107 else if (abs_bimag >= abs_breal) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 /* divide tops and bottom by b.imag */
109 const double ratio = b.real / b.imag;
110 const double denom = b.real * ratio + b.imag;
111 assert(b.imag != 0.0);
112 r.real = (a.real * ratio + a.imag) / denom;
113 r.imag = (a.imag * ratio - a.real) / denom;
114 }
Antoine Pitrou9086f922014-10-10 23:49:32 +0200115 else {
116 /* At least one of b.real or b.imag is a NaN */
117 r.real = r.imag = Py_NAN;
118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000120}
Paul Monsonff6bb0a2019-06-12 11:08:40 -0700121#ifdef _M_ARM64
122#pragma optimize("", on)
123#endif
Guido van Rossumf9fca921996-01-12 00:47:05 +0000124
Tim Peters0f336042001-03-18 08:21:57 +0000125Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400126_Py_c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 Py_complex r;
129 double vabs,len,at,phase;
130 if (b.real == 0. && b.imag == 0.) {
131 r.real = 1.;
132 r.imag = 0.;
133 }
134 else if (a.real == 0. && a.imag == 0.) {
135 if (b.imag != 0. || b.real < 0.)
136 errno = EDOM;
137 r.real = 0.;
138 r.imag = 0.;
139 }
140 else {
141 vabs = hypot(a.real,a.imag);
142 len = pow(vabs,b.real);
143 at = atan2(a.imag, a.real);
144 phase = at*b.real;
145 if (b.imag != 0.0) {
146 len /= exp(at*b.imag);
147 phase += b.imag*log(vabs);
148 }
149 r.real = len*cos(phase);
150 r.imag = len*sin(phase);
151 }
152 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000153}
154
Tim Peters0f336042001-03-18 08:21:57 +0000155static Py_complex
156c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 Py_complex r, p;
159 long mask = 1;
160 r = c_1;
161 p = x;
162 while (mask > 0 && n >= mask) {
163 if (n & mask)
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400164 r = _Py_c_prod(r,p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 mask <<= 1;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400166 p = _Py_c_prod(p,p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 }
168 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000169}
170
Tim Peters0f336042001-03-18 08:21:57 +0000171static Py_complex
172c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (n > 100 || n < -100) {
177 cn.real = (double) n;
178 cn.imag = 0.;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400179 return _Py_c_pow(x,cn);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 }
181 else if (n > 0)
182 return c_powu(x,n);
183 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400184 return _Py_c_quot(c_1, c_powu(x,-n));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000185
186}
187
Christian Heimes53876d92008-04-19 00:31:39 +0000188double
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400189_Py_c_abs(Py_complex z)
Christian Heimes53876d92008-04-19 00:31:39 +0000190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
192 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
195 /* C99 rules: if either the real or the imaginary part is an
196 infinity, return infinity, even if the other part is a
197 NaN. */
198 if (Py_IS_INFINITY(z.real)) {
199 result = fabs(z.real);
200 errno = 0;
201 return result;
202 }
203 if (Py_IS_INFINITY(z.imag)) {
204 result = fabs(z.imag);
205 errno = 0;
206 return result;
207 }
208 /* either the real or imaginary part is a NaN,
209 and neither is infinite. Result should be NaN. */
210 return Py_NAN;
211 }
212 result = hypot(z.real, z.imag);
213 if (!Py_IS_FINITE(result))
214 errno = ERANGE;
215 else
216 errno = 0;
217 return result;
Christian Heimes53876d92008-04-19 00:31:39 +0000218}
219
Tim Peters6d6c1a32001-08-02 04:15:00 +0000220static PyObject *
221complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyObject *op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 op = type->tp_alloc(type, 0);
226 if (op != NULL)
227 ((PyComplexObject *)op)->cval = cval;
228 return op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000229}
230
Guido van Rossumf9fca921996-01-12 00:47:05 +0000231PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000232PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 /* Inline PyObject_New */
Victor Stinner04fc4f22020-06-16 01:28:07 +0200235 PyComplexObject *op = PyObject_MALLOC(sizeof(PyComplexObject));
236 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 return PyErr_NoMemory();
Victor Stinner04fc4f22020-06-16 01:28:07 +0200238 }
239 _PyObject_Init((PyObject*)op, &PyComplex_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 op->cval = cval;
241 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000242}
243
Tim Peters6d6c1a32001-08-02 04:15:00 +0000244static PyObject *
245complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 Py_complex c;
248 c.real = real;
249 c.imag = imag;
250 return complex_subtype_from_c_complex(type, c);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000251}
252
Guido van Rossumf9fca921996-01-12 00:47:05 +0000253PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000254PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 Py_complex c;
257 c.real = real;
258 c.imag = imag;
259 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000260}
261
262double
Fred Drake4288c802000-07-09 04:36:04 +0000263PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if (PyComplex_Check(op)) {
266 return ((PyComplexObject *)op)->cval.real;
267 }
268 else {
269 return PyFloat_AsDouble(op);
270 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000271}
272
273double
Fred Drake4288c802000-07-09 04:36:04 +0000274PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 if (PyComplex_Check(op)) {
277 return ((PyComplexObject *)op)->cval.imag;
278 }
279 else {
280 return 0.0;
281 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000282}
283
Benjamin Petersonaea44282010-01-04 01:10:28 +0000284static PyObject *
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200285try_complex_special_method(PyObject *op)
286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 PyObject *f;
Benjamin Petersonce798522012-01-22 11:24:29 -0500288 _Py_IDENTIFIER(__complex__);
Benjamin Petersonaea44282010-01-04 01:10:28 +0000289
Benjamin Petersonce798522012-01-22 11:24:29 -0500290 f = _PyObject_LookupSpecial(op, &PyId___complex__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (f) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100292 PyObject *res = _PyObject_CallNoArg(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 Py_DECREF(f);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200294 if (!res || PyComplex_CheckExact(res)) {
295 return res;
296 }
297 if (!PyComplex_Check(res)) {
298 PyErr_Format(PyExc_TypeError,
299 "__complex__ returned non-complex (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100300 Py_TYPE(res)->tp_name);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200301 Py_DECREF(res);
302 return NULL;
303 }
304 /* Issue #29894: warn if 'res' not of exact type complex. */
305 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
306 "__complex__ returned non-complex (type %.200s). "
307 "The ability to return an instance of a strict subclass of complex "
308 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100309 Py_TYPE(res)->tp_name)) {
Mark Dickinsond20fb822012-11-14 17:08:31 +0000310 Py_DECREF(res);
311 return NULL;
312 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return res;
314 }
315 return NULL;
Benjamin Petersonaea44282010-01-04 01:10:28 +0000316}
317
Guido van Rossum9e720e31996-07-21 02:31:35 +0000318Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000319PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 Py_complex cv;
322 PyObject *newop = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 assert(op);
325 /* If op is already of type PyComplex_Type, return its value */
326 if (PyComplex_Check(op)) {
327 return ((PyComplexObject *)op)->cval;
328 }
329 /* If not, use op's __complex__ method, if it exists */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 /* return -1 on failure */
332 cv.real = -1.;
333 cv.imag = 0.;
334
335 newop = try_complex_special_method(op);
336
337 if (newop) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 cv = ((PyComplexObject *)newop)->cval;
339 Py_DECREF(newop);
340 return cv;
341 }
342 else if (PyErr_Occurred()) {
343 return cv;
344 }
345 /* If neither of the above works, interpret op as a float giving the
346 real part of the result, and fill in the imaginary part as 0. */
347 else {
348 /* PyFloat_AsDouble will return -1 on failure */
349 cv.real = PyFloat_AsDouble(op);
350 return cv;
351 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000352}
353
Eric Smith0923d1d2009-04-16 20:16:10 +0000354static PyObject *
Eric Smith70099a12010-12-04 13:27:34 +0000355complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000356{
Eric Smith70099a12010-12-04 13:27:34 +0000357 int precision = 0;
358 char format_code = 'r';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PyObject *result = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 /* If these are non-NULL, they'll need to be freed. */
362 char *pre = NULL;
363 char *im = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 /* These do not need to be freed. re is either an alias
366 for pre or a pointer to a constant. lead and tail
367 are pointers to constants. */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200368 const char *re = NULL;
369 const char *lead = "";
370 const char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
Eric Smith70099a12010-12-04 13:27:34 +0000373 /* Real part is +0: just output the imaginary part and do not
374 include parens. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 re = "";
376 im = PyOS_double_to_string(v->cval.imag, format_code,
377 precision, 0, NULL);
378 if (!im) {
379 PyErr_NoMemory();
380 goto done;
381 }
382 } else {
Eric Smith70099a12010-12-04 13:27:34 +0000383 /* Format imaginary part with sign, real part without. Include
384 parens in the result. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 pre = PyOS_double_to_string(v->cval.real, format_code,
386 precision, 0, NULL);
387 if (!pre) {
388 PyErr_NoMemory();
389 goto done;
390 }
391 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 im = PyOS_double_to_string(v->cval.imag, format_code,
394 precision, Py_DTSF_SIGN, NULL);
395 if (!im) {
396 PyErr_NoMemory();
397 goto done;
398 }
399 lead = "(";
400 tail = ")";
401 }
Victor Stinner6ced7c42011-03-21 18:15:42 +0100402 result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000403 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 PyMem_Free(im);
405 PyMem_Free(pre);
Eric Smith0923d1d2009-04-16 20:16:10 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000408}
409
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000410static Py_hash_t
Fred Drake4288c802000-07-09 04:36:04 +0000411complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000412{
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000413 Py_uhash_t hashreal, hashimag, combined;
414 hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real);
415 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 return -1;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000417 hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag);
418 if (hashimag == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 return -1;
420 /* Note: if the imaginary part is 0, hashimag is 0 now,
421 * so the following returns hashreal unchanged. This is
422 * important because numbers of different types that
423 * compare equal must have the same hash value, so that
424 * hash(x + 0*j) must equal hash(x).
425 */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000426 combined = hashreal + _PyHASH_IMAG * hashimag;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000427 if (combined == (Py_uhash_t)-1)
428 combined = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000429 return (Py_hash_t)combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000430}
431
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000432/* This macro may return! */
433#define TO_COMPLEX(obj, c) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (PyComplex_Check(obj)) \
435 c = ((PyComplexObject *)(obj))->cval; \
436 else if (to_complex(&(obj), &(c)) < 0) \
437 return (obj)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000438
439static int
440to_complex(PyObject **pobj, Py_complex *pc)
441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 pc->real = pc->imag = 0.0;
445 if (PyLong_Check(obj)) {
446 pc->real = PyLong_AsDouble(obj);
447 if (pc->real == -1.0 && PyErr_Occurred()) {
448 *pobj = NULL;
449 return -1;
450 }
451 return 0;
452 }
453 if (PyFloat_Check(obj)) {
454 pc->real = PyFloat_AsDouble(obj);
455 return 0;
456 }
457 Py_INCREF(Py_NotImplemented);
458 *pobj = Py_NotImplemented;
459 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000460}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000462
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000463static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000464complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 Py_complex result;
467 Py_complex a, b;
468 TO_COMPLEX(v, a);
469 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400470 result = _Py_c_sum(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000472}
473
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000475complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 Py_complex result;
478 Py_complex a, b;
479 TO_COMPLEX(v, a);
480 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400481 result = _Py_c_diff(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000483}
484
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000486complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 Py_complex result;
489 Py_complex a, b;
490 TO_COMPLEX(v, a);
491 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400492 result = _Py_c_prod(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000494}
495
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000497complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 Py_complex quot;
500 Py_complex a, b;
501 TO_COMPLEX(v, a);
502 TO_COMPLEX(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 errno = 0;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400504 quot = _Py_c_quot(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 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 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 errno = 0;
544 exponent = b;
545 int_exponent = (long)exponent.real;
546 if (exponent.imag == 0. && exponent.real == int_exponent)
547 p = c_powi(a, int_exponent);
548 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400549 p = _Py_c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 Py_ADJUST_ERANGE2(p.real, p.imag);
552 if (errno == EDOM) {
553 PyErr_SetString(PyExc_ZeroDivisionError,
554 "0.0 to a negative or complex power");
555 return NULL;
556 }
557 else if (errno == ERANGE) {
558 PyErr_SetString(PyExc_OverflowError,
559 "complex exponentiation");
560 return NULL;
561 }
562 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000563}
564
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000566complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 PyErr_SetString(PyExc_TypeError,
569 "can't take floor of complex number.");
570 return NULL;
Guido van Rossum4668b002001-08-08 05:00:18 +0000571}
572
573static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000574complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 Py_complex neg;
577 neg.real = -v->cval.real;
578 neg.imag = -v->cval.imag;
579 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000580}
581
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000583complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (PyComplex_CheckExact(v)) {
586 Py_INCREF(v);
587 return (PyObject *)v;
588 }
589 else
590 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000591}
592
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000593static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000594complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000597
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400598 result = _Py_c_abs(v->cval);
Christian Heimes53876d92008-04-19 00:31:39 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (errno == ERANGE) {
601 PyErr_SetString(PyExc_OverflowError,
602 "absolute value too large");
603 return NULL;
604 }
605 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000606}
607
608static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000609complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000612}
613
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000614static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000615complex_richcompare(PyObject *v, PyObject *w, int op)
616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000618 Py_complex i;
619 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000622 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 }
Guido van Rossum22056422001-09-24 17:52:04 +0000624
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000625 assert(PyComplex_Check(v));
626 TO_COMPLEX(v, i);
627
628 if (PyLong_Check(w)) {
629 /* Check for 0.0 imaginary part first to avoid the rich
630 * comparison when possible.
631 */
632 if (i.imag == 0.0) {
633 PyObject *j, *sub_res;
634 j = PyFloat_FromDouble(i.real);
635 if (j == NULL)
636 return NULL;
637
638 sub_res = PyObject_RichCompare(j, w, op);
639 Py_DECREF(j);
640 return sub_res;
641 }
642 else {
643 equal = 0;
644 }
645 }
646 else if (PyFloat_Check(w)) {
647 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
648 }
649 else if (PyComplex_Check(w)) {
650 Py_complex j;
651
652 TO_COMPLEX(w, j);
653 equal = (i.real == j.real && i.imag == j.imag);
654 }
655 else {
656 goto Unimplemented;
657 }
658
659 if (equal == (op == Py_EQ))
660 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000662 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 Py_INCREF(res);
665 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000666
667Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500668 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000669}
670
671static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000672complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyErr_SetString(PyExc_TypeError,
675 "can't convert complex to int");
676 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000677}
678
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000680complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 PyErr_SetString(PyExc_TypeError,
683 "can't convert complex to float");
684 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000685}
686
Dong-hee Nae1230122020-07-20 21:53:29 +0900687/*[clinic input]
688complex.conjugate
689
690Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
691[clinic start generated code]*/
692
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000693static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900694complex_conjugate_impl(PyComplexObject *self)
695/*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
Guido van Rossumf9fca921996-01-12 00:47:05 +0000696{
Dong-hee Nae1230122020-07-20 21:53:29 +0900697 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 c.imag = -c.imag;
699 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000700}
701
Dong-hee Nae1230122020-07-20 21:53:29 +0900702/*[clinic input]
703complex.__getnewargs__
704
705[clinic start generated code]*/
Guido van Rossum46334cd2007-08-01 17:43:15 +0000706
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000707static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900708complex___getnewargs___impl(PyComplexObject *self)
709/*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000710{
Dong-hee Nae1230122020-07-20 21:53:29 +0900711 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000713}
714
Dong-hee Nae1230122020-07-20 21:53:29 +0900715
716/*[clinic input]
717complex.__format__
718
719 format_spec: unicode
720 /
721
722Convert to a string according to format_spec.
723[clinic start generated code]*/
Eric Smith58a42242009-04-30 01:00:33 +0000724
725static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900726complex___format___impl(PyComplexObject *self, PyObject *format_spec)
727/*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
Eric Smith58a42242009-04-30 01:00:33 +0000728{
Victor Stinnerd3f08822012-05-29 12:57:52 +0200729 _PyUnicodeWriter writer;
730 int ret;
Victor Stinner8f674cc2013-04-17 23:02:17 +0200731 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +0200732 ret = _PyComplex_FormatAdvancedWriter(
733 &writer,
Dong-hee Nae1230122020-07-20 21:53:29 +0900734 (PyObject *)self,
Victor Stinnerd3f08822012-05-29 12:57:52 +0200735 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
736 if (ret == -1) {
737 _PyUnicodeWriter_Dealloc(&writer);
738 return NULL;
739 }
740 return _PyUnicodeWriter_Finish(&writer);
Eric Smith58a42242009-04-30 01:00:33 +0000741}
742
Guido van Rossumf9fca921996-01-12 00:47:05 +0000743static PyMethodDef complex_methods[] = {
Dong-hee Nae1230122020-07-20 21:53:29 +0900744 COMPLEX_CONJUGATE_METHODDEF
745 COMPLEX___GETNEWARGS___METHODDEF
746 COMPLEX___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000748};
749
Guido van Rossum6f799372001-09-20 20:46:19 +0000750static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
752 "the real part of a complex number"},
753 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
754 "the imaginary part of a complex number"},
755 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000756};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000757
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000758static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700759complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 double x=0.0, y=0.0, z;
762 int got_bracket=0;
Brett Cannona721aba2016-09-09 14:57:09 -0700763 const char *start;
764 char *end;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 /* position on first nonblank */
767 start = s;
768 while (Py_ISSPACE(*s))
769 s++;
770 if (*s == '(') {
771 /* Skip over possible bracket from repr(). */
772 got_bracket = 1;
773 s++;
774 while (Py_ISSPACE(*s))
775 s++;
776 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 <float> - real part only
781 <float>j - imaginary part only
782 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 where <float> represents any numeric string that's accepted by the
785 float constructor (including 'nan', 'inf', 'infinity', etc.), and
786 <signed-float> is any string of the form <float> whose first
787 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 <float><sign>j
792 <sign>j
793 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 are also accepted, though support for these forms may be removed from
796 a future version of Python.
797 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 /* first look for forms starting with <float> */
800 z = PyOS_string_to_double(s, &end, NULL);
801 if (z == -1.0 && PyErr_Occurred()) {
802 if (PyErr_ExceptionMatches(PyExc_ValueError))
803 PyErr_Clear();
804 else
Brett Cannona721aba2016-09-09 14:57:09 -0700805 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 }
807 if (end != s) {
808 /* all 4 forms starting with <float> land here */
809 s = end;
810 if (*s == '+' || *s == '-') {
811 /* <float><signed-float>j | <float><sign>j */
812 x = z;
813 y = PyOS_string_to_double(s, &end, NULL);
814 if (y == -1.0 && PyErr_Occurred()) {
815 if (PyErr_ExceptionMatches(PyExc_ValueError))
816 PyErr_Clear();
817 else
Brett Cannona721aba2016-09-09 14:57:09 -0700818 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 }
820 if (end != s)
821 /* <float><signed-float>j */
822 s = end;
823 else {
824 /* <float><sign>j */
825 y = *s == '+' ? 1.0 : -1.0;
826 s++;
827 }
828 if (!(*s == 'j' || *s == 'J'))
829 goto parse_error;
830 s++;
831 }
832 else if (*s == 'j' || *s == 'J') {
833 /* <float>j */
834 s++;
835 y = z;
836 }
837 else
838 /* <float> */
839 x = z;
840 }
841 else {
842 /* not starting with <float>; must be <sign>j or j */
843 if (*s == '+' || *s == '-') {
844 /* <sign>j */
845 y = *s == '+' ? 1.0 : -1.0;
846 s++;
847 }
848 else
849 /* j */
850 y = 1.0;
851 if (!(*s == 'j' || *s == 'J'))
852 goto parse_error;
853 s++;
854 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 /* trailing whitespace and closing bracket */
857 while (Py_ISSPACE(*s))
858 s++;
859 if (got_bracket) {
860 /* if there was an opening parenthesis, then the corresponding
861 closing parenthesis should be right here */
862 if (*s != ')')
863 goto parse_error;
864 s++;
865 while (Py_ISSPACE(*s))
866 s++;
867 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 /* we should now be at the end of the string */
870 if (s-start != len)
871 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000872
Brett Cannona721aba2016-09-09 14:57:09 -0700873 return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000874
Mark Dickinson6649fa42009-04-24 13:25:20 +0000875 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 PyErr_SetString(PyExc_ValueError,
877 "complex() arg is a malformed string");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000879}
880
Tim Peters6d6c1a32001-08-02 04:15:00 +0000881static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700882complex_subtype_from_string(PyTypeObject *type, PyObject *v)
883{
884 const char *s;
885 PyObject *s_buffer = NULL, *result = NULL;
886 Py_ssize_t len;
887
888 if (PyUnicode_Check(v)) {
889 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
890 if (s_buffer == NULL) {
891 return NULL;
892 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200893 assert(PyUnicode_IS_ASCII(s_buffer));
894 /* Simply get a pointer to existing ASCII characters. */
Brett Cannona721aba2016-09-09 14:57:09 -0700895 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200896 assert(s != NULL);
Brett Cannona721aba2016-09-09 14:57:09 -0700897 }
898 else {
899 PyErr_Format(PyExc_TypeError,
900 "complex() argument must be a string or a number, not '%.200s'",
901 Py_TYPE(v)->tp_name);
902 return NULL;
903 }
904
905 result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
906 complex_from_string_inner);
Brett Cannona721aba2016-09-09 14:57:09 -0700907 Py_DECREF(s_buffer);
908 return result;
909}
910
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200911/*[clinic input]
912@classmethod
913complex.__new__ as complex_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300914 real as r: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200915 imag as i: object(c_default="NULL") = 0
916
917Create a complex number from a real part and an optional imaginary part.
918
919This is equivalent to (real + imag*1j) where imag defaults to 0.
920[clinic start generated code]*/
921
Brett Cannona721aba2016-09-09 14:57:09 -0700922static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200923complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
Serhiy Storchakabae68812017-04-05 12:00:42 +0300924/*[clinic end generated code: output=b6c7dd577b537dc1 input=6f6b0bedba29bcb5]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000925{
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200926 PyObject *tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 PyNumberMethods *nbr, *nbi = NULL;
928 Py_complex cr, ci;
929 int own_r = 0;
930 int cr_is_complex = 0;
931 int ci_is_complex = 0;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Special-case for a single argument when type(arg) is complex. */
934 if (PyComplex_CheckExact(r) && i == NULL &&
935 type == &PyComplex_Type) {
936 /* Note that we can't know whether it's safe to return
937 a complex *subclass* instance as-is, hence the restriction
938 to exact complexes here. If either the input or the
939 output is a complex subclass, it will be handled below
940 as a non-orthogonal vector. */
941 Py_INCREF(r);
942 return r;
943 }
944 if (PyUnicode_Check(r)) {
945 if (i != NULL) {
946 PyErr_SetString(PyExc_TypeError,
947 "complex() can't take second arg"
948 " if first is a string");
949 return NULL;
950 }
951 return complex_subtype_from_string(type, r);
952 }
953 if (i != NULL && PyUnicode_Check(i)) {
954 PyErr_SetString(PyExc_TypeError,
955 "complex() second arg can't be a string");
956 return NULL;
957 }
Tim Peters2400fa42001-09-12 19:12:49 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 tmp = try_complex_special_method(r);
960 if (tmp) {
961 r = tmp;
962 own_r = 1;
963 }
964 else if (PyErr_Occurred()) {
965 return NULL;
966 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000967
Victor Stinner58ac7002020-02-07 03:04:21 +0100968 nbr = Py_TYPE(r)->tp_as_number;
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300969 if (nbr == NULL || (nbr->nb_float == NULL && nbr->nb_index == NULL)) {
Ezio Melottia5b95992013-11-07 19:18:34 +0200970 PyErr_Format(PyExc_TypeError,
Mark Dickinson613f8e52016-09-24 15:26:36 +0100971 "complex() first argument must be a string or a number, "
972 "not '%.200s'",
973 Py_TYPE(r)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (own_r) {
975 Py_DECREF(r);
976 }
977 return NULL;
978 }
Mark Dickinson613f8e52016-09-24 15:26:36 +0100979 if (i != NULL) {
Victor Stinner58ac7002020-02-07 03:04:21 +0100980 nbi = Py_TYPE(i)->tp_as_number;
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300981 if (nbi == NULL || (nbi->nb_float == NULL && nbi->nb_index == NULL)) {
Mark Dickinson613f8e52016-09-24 15:26:36 +0100982 PyErr_Format(PyExc_TypeError,
983 "complex() second argument must be a number, "
984 "not '%.200s'",
985 Py_TYPE(i)->tp_name);
986 if (own_r) {
987 Py_DECREF(r);
988 }
989 return NULL;
990 }
991 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 /* If we get this far, then the "real" and "imag" parts should
994 both be treated as numbers, and the constructor should return a
995 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 Note that we do NOT assume the input to already be in canonical
998 form; the "real" and "imag" parts might themselves be complex
999 numbers, which slightly complicates the code below. */
1000 if (PyComplex_Check(r)) {
1001 /* Note that if r is of a complex subtype, we're only
1002 retaining its real & imag parts here, and the return
1003 value is (properly) of the builtin complex type. */
1004 cr = ((PyComplexObject*)r)->cval;
1005 cr_is_complex = 1;
1006 if (own_r) {
1007 Py_DECREF(r);
1008 }
1009 }
1010 else {
1011 /* The "real" part really is entirely real, and contributes
1012 nothing in the imaginary direction.
1013 Just treat it as a double. */
1014 tmp = PyNumber_Float(r);
1015 if (own_r) {
1016 /* r was a newly created complex number, rather
1017 than the original "real" argument. */
1018 Py_DECREF(r);
1019 }
1020 if (tmp == NULL)
1021 return NULL;
Serhiy Storchaka671079e2017-03-24 21:28:43 +02001022 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 cr.real = PyFloat_AsDouble(tmp);
Mark Dickinson112ec382017-02-20 20:28:15 +00001024 cr.imag = 0.0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 Py_DECREF(tmp);
1026 }
1027 if (i == NULL) {
Mark Dickinson112ec382017-02-20 20:28:15 +00001028 ci.real = cr.imag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 }
1030 else if (PyComplex_Check(i)) {
1031 ci = ((PyComplexObject*)i)->cval;
1032 ci_is_complex = 1;
1033 } else {
1034 /* The "imag" part really is entirely imaginary, and
1035 contributes nothing in the real direction.
1036 Just treat it as a double. */
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001037 tmp = PyNumber_Float(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 if (tmp == NULL)
1039 return NULL;
1040 ci.real = PyFloat_AsDouble(tmp);
1041 Py_DECREF(tmp);
1042 }
1043 /* If the input was in canonical form, then the "real" and "imag"
1044 parts are real numbers, so that ci.imag and cr.imag are zero.
1045 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 if (ci_is_complex) {
1048 cr.real -= ci.imag;
1049 }
Mark Dickinson112ec382017-02-20 20:28:15 +00001050 if (cr_is_complex && i != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 ci.real += cr.imag;
1052 }
1053 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054}
1055
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001056static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 (binaryfunc)complex_add, /* nb_add */
1058 (binaryfunc)complex_sub, /* nb_subtract */
1059 (binaryfunc)complex_mul, /* nb_multiply */
1060 (binaryfunc)complex_remainder, /* nb_remainder */
1061 (binaryfunc)complex_divmod, /* nb_divmod */
1062 (ternaryfunc)complex_pow, /* nb_power */
1063 (unaryfunc)complex_neg, /* nb_negative */
1064 (unaryfunc)complex_pos, /* nb_positive */
1065 (unaryfunc)complex_abs, /* nb_absolute */
1066 (inquiry)complex_bool, /* nb_bool */
1067 0, /* nb_invert */
1068 0, /* nb_lshift */
1069 0, /* nb_rshift */
1070 0, /* nb_and */
1071 0, /* nb_xor */
1072 0, /* nb_or */
1073 complex_int, /* nb_int */
1074 0, /* nb_reserved */
1075 complex_float, /* nb_float */
1076 0, /* nb_inplace_add */
1077 0, /* nb_inplace_subtract */
1078 0, /* nb_inplace_multiply*/
1079 0, /* nb_inplace_remainder */
1080 0, /* nb_inplace_power */
1081 0, /* nb_inplace_lshift */
1082 0, /* nb_inplace_rshift */
1083 0, /* nb_inplace_and */
1084 0, /* nb_inplace_xor */
1085 0, /* nb_inplace_or */
1086 (binaryfunc)complex_int_div, /* nb_floor_divide */
1087 (binaryfunc)complex_div, /* nb_true_divide */
1088 0, /* nb_inplace_floor_divide */
1089 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001090};
1091
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001092PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1094 "complex",
1095 sizeof(PyComplexObject),
1096 0,
Inada Naoki7d408692019-05-29 17:23:27 +09001097 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001098 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 0, /* tp_getattr */
1100 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001101 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 (reprfunc)complex_repr, /* tp_repr */
1103 &complex_as_number, /* tp_as_number */
1104 0, /* tp_as_sequence */
1105 0, /* tp_as_mapping */
1106 (hashfunc)complex_hash, /* tp_hash */
1107 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001108 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyObject_GenericGetAttr, /* tp_getattro */
1110 0, /* tp_setattro */
1111 0, /* tp_as_buffer */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1113 complex_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 0, /* tp_traverse */
1115 0, /* tp_clear */
1116 complex_richcompare, /* tp_richcompare */
1117 0, /* tp_weaklistoffset */
1118 0, /* tp_iter */
1119 0, /* tp_iternext */
1120 complex_methods, /* tp_methods */
1121 complex_members, /* tp_members */
1122 0, /* tp_getset */
1123 0, /* tp_base */
1124 0, /* tp_dict */
1125 0, /* tp_descr_get */
1126 0, /* tp_descr_set */
1127 0, /* tp_dictoffset */
1128 0, /* tp_init */
1129 PyType_GenericAlloc, /* tp_alloc */
1130 complex_new, /* tp_new */
1131 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001132};