blob: 5ab839a9e9423a2a39dcf7fb30dec45d74142acf [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_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 Py_complex p;
516 Py_complex exponent;
517 long int_exponent;
518 Py_complex a, b;
519 TO_COMPLEX(v, a);
520 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (z != Py_None) {
523 PyErr_SetString(PyExc_ValueError, "complex modulo");
524 return NULL;
525 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 errno = 0;
527 exponent = b;
528 int_exponent = (long)exponent.real;
529 if (exponent.imag == 0. && exponent.real == int_exponent)
530 p = c_powi(a, int_exponent);
531 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400532 p = _Py_c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 Py_ADJUST_ERANGE2(p.real, p.imag);
535 if (errno == EDOM) {
536 PyErr_SetString(PyExc_ZeroDivisionError,
537 "0.0 to a negative or complex power");
538 return NULL;
539 }
540 else if (errno == ERANGE) {
541 PyErr_SetString(PyExc_OverflowError,
542 "complex exponentiation");
543 return NULL;
544 }
545 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000546}
547
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000549complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 Py_complex neg;
552 neg.real = -v->cval.real;
553 neg.imag = -v->cval.imag;
554 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000555}
556
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000557static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000558complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (PyComplex_CheckExact(v)) {
561 Py_INCREF(v);
562 return (PyObject *)v;
563 }
564 else
565 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000566}
567
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000568static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000569complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000572
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400573 result = _Py_c_abs(v->cval);
Christian Heimes53876d92008-04-19 00:31:39 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 if (errno == ERANGE) {
576 PyErr_SetString(PyExc_OverflowError,
577 "absolute value too large");
578 return NULL;
579 }
580 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000581}
582
583static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000584complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000587}
588
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000589static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000590complex_richcompare(PyObject *v, PyObject *w, int op)
591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000593 Py_complex i;
594 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000597 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 }
Guido van Rossum22056422001-09-24 17:52:04 +0000599
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000600 assert(PyComplex_Check(v));
601 TO_COMPLEX(v, i);
602
603 if (PyLong_Check(w)) {
604 /* Check for 0.0 imaginary part first to avoid the rich
605 * comparison when possible.
606 */
607 if (i.imag == 0.0) {
608 PyObject *j, *sub_res;
609 j = PyFloat_FromDouble(i.real);
610 if (j == NULL)
611 return NULL;
612
613 sub_res = PyObject_RichCompare(j, w, op);
614 Py_DECREF(j);
615 return sub_res;
616 }
617 else {
618 equal = 0;
619 }
620 }
621 else if (PyFloat_Check(w)) {
622 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
623 }
624 else if (PyComplex_Check(w)) {
625 Py_complex j;
626
627 TO_COMPLEX(w, j);
628 equal = (i.real == j.real && i.imag == j.imag);
629 }
630 else {
631 goto Unimplemented;
632 }
633
634 if (equal == (op == Py_EQ))
635 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000637 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 Py_INCREF(res);
640 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000641
642Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500643 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000644}
645
Dong-hee Nae1230122020-07-20 21:53:29 +0900646/*[clinic input]
647complex.conjugate
648
649Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
650[clinic start generated code]*/
651
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000652static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900653complex_conjugate_impl(PyComplexObject *self)
654/*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
Guido van Rossumf9fca921996-01-12 00:47:05 +0000655{
Dong-hee Nae1230122020-07-20 21:53:29 +0900656 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 c.imag = -c.imag;
658 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000659}
660
Dong-hee Nae1230122020-07-20 21:53:29 +0900661/*[clinic input]
662complex.__getnewargs__
663
664[clinic start generated code]*/
Guido van Rossum46334cd2007-08-01 17:43:15 +0000665
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000666static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900667complex___getnewargs___impl(PyComplexObject *self)
668/*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000669{
Dong-hee Nae1230122020-07-20 21:53:29 +0900670 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000672}
673
Dong-hee Nae1230122020-07-20 21:53:29 +0900674
675/*[clinic input]
676complex.__format__
677
678 format_spec: unicode
679 /
680
681Convert to a string according to format_spec.
682[clinic start generated code]*/
Eric Smith58a42242009-04-30 01:00:33 +0000683
684static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900685complex___format___impl(PyComplexObject *self, PyObject *format_spec)
686/*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
Eric Smith58a42242009-04-30 01:00:33 +0000687{
Victor Stinnerd3f08822012-05-29 12:57:52 +0200688 _PyUnicodeWriter writer;
689 int ret;
Victor Stinner8f674cc2013-04-17 23:02:17 +0200690 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +0200691 ret = _PyComplex_FormatAdvancedWriter(
692 &writer,
Dong-hee Nae1230122020-07-20 21:53:29 +0900693 (PyObject *)self,
Victor Stinnerd3f08822012-05-29 12:57:52 +0200694 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
695 if (ret == -1) {
696 _PyUnicodeWriter_Dealloc(&writer);
697 return NULL;
698 }
699 return _PyUnicodeWriter_Finish(&writer);
Eric Smith58a42242009-04-30 01:00:33 +0000700}
701
Guido van Rossumf9fca921996-01-12 00:47:05 +0000702static PyMethodDef complex_methods[] = {
Dong-hee Nae1230122020-07-20 21:53:29 +0900703 COMPLEX_CONJUGATE_METHODDEF
704 COMPLEX___GETNEWARGS___METHODDEF
705 COMPLEX___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000707};
708
Guido van Rossum6f799372001-09-20 20:46:19 +0000709static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
711 "the real part of a complex number"},
712 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
713 "the imaginary part of a complex number"},
714 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000715};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000716
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000717static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700718complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 double x=0.0, y=0.0, z;
721 int got_bracket=0;
Brett Cannona721aba2016-09-09 14:57:09 -0700722 const char *start;
723 char *end;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 /* position on first nonblank */
726 start = s;
727 while (Py_ISSPACE(*s))
728 s++;
729 if (*s == '(') {
730 /* Skip over possible bracket from repr(). */
731 got_bracket = 1;
732 s++;
733 while (Py_ISSPACE(*s))
734 s++;
735 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 <float> - real part only
740 <float>j - imaginary part only
741 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 where <float> represents any numeric string that's accepted by the
744 float constructor (including 'nan', 'inf', 'infinity', etc.), and
745 <signed-float> is any string of the form <float> whose first
746 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 <float><sign>j
751 <sign>j
752 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 are also accepted, though support for these forms may be removed from
755 a future version of Python.
756 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* first look for forms starting with <float> */
759 z = PyOS_string_to_double(s, &end, NULL);
760 if (z == -1.0 && PyErr_Occurred()) {
761 if (PyErr_ExceptionMatches(PyExc_ValueError))
762 PyErr_Clear();
763 else
Brett Cannona721aba2016-09-09 14:57:09 -0700764 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 }
766 if (end != s) {
767 /* all 4 forms starting with <float> land here */
768 s = end;
769 if (*s == '+' || *s == '-') {
770 /* <float><signed-float>j | <float><sign>j */
771 x = z;
772 y = PyOS_string_to_double(s, &end, NULL);
773 if (y == -1.0 && PyErr_Occurred()) {
774 if (PyErr_ExceptionMatches(PyExc_ValueError))
775 PyErr_Clear();
776 else
Brett Cannona721aba2016-09-09 14:57:09 -0700777 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 }
779 if (end != s)
780 /* <float><signed-float>j */
781 s = end;
782 else {
783 /* <float><sign>j */
784 y = *s == '+' ? 1.0 : -1.0;
785 s++;
786 }
787 if (!(*s == 'j' || *s == 'J'))
788 goto parse_error;
789 s++;
790 }
791 else if (*s == 'j' || *s == 'J') {
792 /* <float>j */
793 s++;
794 y = z;
795 }
796 else
797 /* <float> */
798 x = z;
799 }
800 else {
801 /* not starting with <float>; must be <sign>j or j */
802 if (*s == '+' || *s == '-') {
803 /* <sign>j */
804 y = *s == '+' ? 1.0 : -1.0;
805 s++;
806 }
807 else
808 /* j */
809 y = 1.0;
810 if (!(*s == 'j' || *s == 'J'))
811 goto parse_error;
812 s++;
813 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 /* trailing whitespace and closing bracket */
816 while (Py_ISSPACE(*s))
817 s++;
818 if (got_bracket) {
819 /* if there was an opening parenthesis, then the corresponding
820 closing parenthesis should be right here */
821 if (*s != ')')
822 goto parse_error;
823 s++;
824 while (Py_ISSPACE(*s))
825 s++;
826 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 /* we should now be at the end of the string */
829 if (s-start != len)
830 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000831
Brett Cannona721aba2016-09-09 14:57:09 -0700832 return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000833
Mark Dickinson6649fa42009-04-24 13:25:20 +0000834 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyErr_SetString(PyExc_ValueError,
836 "complex() arg is a malformed string");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000838}
839
Tim Peters6d6c1a32001-08-02 04:15:00 +0000840static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700841complex_subtype_from_string(PyTypeObject *type, PyObject *v)
842{
843 const char *s;
844 PyObject *s_buffer = NULL, *result = NULL;
845 Py_ssize_t len;
846
847 if (PyUnicode_Check(v)) {
848 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
849 if (s_buffer == NULL) {
850 return NULL;
851 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200852 assert(PyUnicode_IS_ASCII(s_buffer));
853 /* Simply get a pointer to existing ASCII characters. */
Brett Cannona721aba2016-09-09 14:57:09 -0700854 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200855 assert(s != NULL);
Brett Cannona721aba2016-09-09 14:57:09 -0700856 }
857 else {
858 PyErr_Format(PyExc_TypeError,
859 "complex() argument must be a string or a number, not '%.200s'",
860 Py_TYPE(v)->tp_name);
861 return NULL;
862 }
863
864 result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
865 complex_from_string_inner);
Brett Cannona721aba2016-09-09 14:57:09 -0700866 Py_DECREF(s_buffer);
867 return result;
868}
869
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200870/*[clinic input]
871@classmethod
872complex.__new__ as complex_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300873 real as r: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200874 imag as i: object(c_default="NULL") = 0
875
876Create a complex number from a real part and an optional imaginary part.
877
878This is equivalent to (real + imag*1j) where imag defaults to 0.
879[clinic start generated code]*/
880
Brett Cannona721aba2016-09-09 14:57:09 -0700881static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200882complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
Serhiy Storchakabae68812017-04-05 12:00:42 +0300883/*[clinic end generated code: output=b6c7dd577b537dc1 input=6f6b0bedba29bcb5]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000884{
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200885 PyObject *tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyNumberMethods *nbr, *nbi = NULL;
887 Py_complex cr, ci;
888 int own_r = 0;
889 int cr_is_complex = 0;
890 int ci_is_complex = 0;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* Special-case for a single argument when type(arg) is complex. */
893 if (PyComplex_CheckExact(r) && i == NULL &&
894 type == &PyComplex_Type) {
895 /* Note that we can't know whether it's safe to return
896 a complex *subclass* instance as-is, hence the restriction
897 to exact complexes here. If either the input or the
898 output is a complex subclass, it will be handled below
899 as a non-orthogonal vector. */
900 Py_INCREF(r);
901 return r;
902 }
903 if (PyUnicode_Check(r)) {
904 if (i != NULL) {
905 PyErr_SetString(PyExc_TypeError,
906 "complex() can't take second arg"
907 " if first is a string");
908 return NULL;
909 }
910 return complex_subtype_from_string(type, r);
911 }
912 if (i != NULL && PyUnicode_Check(i)) {
913 PyErr_SetString(PyExc_TypeError,
914 "complex() second arg can't be a string");
915 return NULL;
916 }
Tim Peters2400fa42001-09-12 19:12:49 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 tmp = try_complex_special_method(r);
919 if (tmp) {
920 r = tmp;
921 own_r = 1;
922 }
923 else if (PyErr_Occurred()) {
924 return NULL;
925 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000926
Victor Stinner58ac7002020-02-07 03:04:21 +0100927 nbr = Py_TYPE(r)->tp_as_number;
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300928 if (nbr == NULL ||
929 (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
930 {
Ezio Melottia5b95992013-11-07 19:18:34 +0200931 PyErr_Format(PyExc_TypeError,
Mark Dickinson613f8e52016-09-24 15:26:36 +0100932 "complex() first argument must be a string or a number, "
933 "not '%.200s'",
934 Py_TYPE(r)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (own_r) {
936 Py_DECREF(r);
937 }
938 return NULL;
939 }
Mark Dickinson613f8e52016-09-24 15:26:36 +0100940 if (i != NULL) {
Victor Stinner58ac7002020-02-07 03:04:21 +0100941 nbi = Py_TYPE(i)->tp_as_number;
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300942 if (nbi == NULL ||
943 (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
944 {
Mark Dickinson613f8e52016-09-24 15:26:36 +0100945 PyErr_Format(PyExc_TypeError,
946 "complex() second argument must be a number, "
947 "not '%.200s'",
948 Py_TYPE(i)->tp_name);
949 if (own_r) {
950 Py_DECREF(r);
951 }
952 return NULL;
953 }
954 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* If we get this far, then the "real" and "imag" parts should
957 both be treated as numbers, and the constructor should return a
958 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 Note that we do NOT assume the input to already be in canonical
961 form; the "real" and "imag" parts might themselves be complex
962 numbers, which slightly complicates the code below. */
963 if (PyComplex_Check(r)) {
964 /* Note that if r is of a complex subtype, we're only
965 retaining its real & imag parts here, and the return
966 value is (properly) of the builtin complex type. */
967 cr = ((PyComplexObject*)r)->cval;
968 cr_is_complex = 1;
969 if (own_r) {
970 Py_DECREF(r);
971 }
972 }
973 else {
974 /* The "real" part really is entirely real, and contributes
975 nothing in the imaginary direction.
976 Just treat it as a double. */
977 tmp = PyNumber_Float(r);
978 if (own_r) {
979 /* r was a newly created complex number, rather
980 than the original "real" argument. */
981 Py_DECREF(r);
982 }
983 if (tmp == NULL)
984 return NULL;
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200985 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 cr.real = PyFloat_AsDouble(tmp);
Mark Dickinson112ec382017-02-20 20:28:15 +0000987 cr.imag = 0.0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 Py_DECREF(tmp);
989 }
990 if (i == NULL) {
Mark Dickinson112ec382017-02-20 20:28:15 +0000991 ci.real = cr.imag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 }
993 else if (PyComplex_Check(i)) {
994 ci = ((PyComplexObject*)i)->cval;
995 ci_is_complex = 1;
996 } else {
997 /* The "imag" part really is entirely imaginary, and
998 contributes nothing in the real direction.
999 Just treat it as a double. */
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001000 tmp = PyNumber_Float(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (tmp == NULL)
1002 return NULL;
1003 ci.real = PyFloat_AsDouble(tmp);
1004 Py_DECREF(tmp);
1005 }
1006 /* If the input was in canonical form, then the "real" and "imag"
1007 parts are real numbers, so that ci.imag and cr.imag are zero.
1008 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (ci_is_complex) {
1011 cr.real -= ci.imag;
1012 }
Mark Dickinson112ec382017-02-20 20:28:15 +00001013 if (cr_is_complex && i != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 ci.real += cr.imag;
1015 }
1016 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001017}
1018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001019static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 (binaryfunc)complex_add, /* nb_add */
1021 (binaryfunc)complex_sub, /* nb_subtract */
1022 (binaryfunc)complex_mul, /* nb_multiply */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001023 0, /* nb_remainder */
1024 0, /* nb_divmod */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 (ternaryfunc)complex_pow, /* nb_power */
1026 (unaryfunc)complex_neg, /* nb_negative */
1027 (unaryfunc)complex_pos, /* nb_positive */
1028 (unaryfunc)complex_abs, /* nb_absolute */
1029 (inquiry)complex_bool, /* nb_bool */
1030 0, /* nb_invert */
1031 0, /* nb_lshift */
1032 0, /* nb_rshift */
1033 0, /* nb_and */
1034 0, /* nb_xor */
1035 0, /* nb_or */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001036 0, /* nb_int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 0, /* nb_reserved */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001038 0, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 0, /* nb_inplace_add */
1040 0, /* nb_inplace_subtract */
1041 0, /* nb_inplace_multiply*/
1042 0, /* nb_inplace_remainder */
1043 0, /* nb_inplace_power */
1044 0, /* nb_inplace_lshift */
1045 0, /* nb_inplace_rshift */
1046 0, /* nb_inplace_and */
1047 0, /* nb_inplace_xor */
1048 0, /* nb_inplace_or */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001049 0, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 (binaryfunc)complex_div, /* nb_true_divide */
1051 0, /* nb_inplace_floor_divide */
1052 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001053};
1054
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001055PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1057 "complex",
1058 sizeof(PyComplexObject),
1059 0,
Inada Naoki7d408692019-05-29 17:23:27 +09001060 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001061 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 0, /* tp_getattr */
1063 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001064 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 (reprfunc)complex_repr, /* tp_repr */
1066 &complex_as_number, /* tp_as_number */
1067 0, /* tp_as_sequence */
1068 0, /* tp_as_mapping */
1069 (hashfunc)complex_hash, /* tp_hash */
1070 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001071 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 PyObject_GenericGetAttr, /* tp_getattro */
1073 0, /* tp_setattro */
1074 0, /* tp_as_buffer */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001075 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1076 complex_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 0, /* tp_traverse */
1078 0, /* tp_clear */
1079 complex_richcompare, /* tp_richcompare */
1080 0, /* tp_weaklistoffset */
1081 0, /* tp_iter */
1082 0, /* tp_iternext */
1083 complex_methods, /* tp_methods */
1084 complex_members, /* tp_members */
1085 0, /* tp_getset */
1086 0, /* tp_base */
1087 0, /* tp_dict */
1088 0, /* tp_descr_get */
1089 0, /* tp_descr_set */
1090 0, /* tp_dictoffset */
1091 0, /* tp_init */
1092 PyType_GenericAlloc, /* tp_alloc */
1093 complex_new, /* tp_new */
1094 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001095};