blob: a65ebdfa6cdf934256d8ce2d42869363cc83edfd [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 Stinnerc9bc2902020-10-27 02:24:34 +01009#include "pycore_long.h" // _PyLong_GetZero()
Victor Stinner04fc4f22020-06-16 01:28:07 +020010#include "pycore_object.h" // _PyObject_Init()
Victor Stinner4a21e572020-04-15 02:35:41 +020011#include "structmember.h" // PyMemberDef
Guido van Rossumf9fca921996-01-12 00:47:05 +000012
Victor Stinner04fc4f22020-06-16 01:28:07 +020013
Serhiy Storchaka18b250f2017-03-19 08:51:07 +020014/*[clinic input]
15class complex "PyComplexObject *" "&PyComplex_Type"
16[clinic start generated code]*/
17/*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
18
19#include "clinic/complexobject.c.h"
20
Guido van Rossumf9fca921996-01-12 00:47:05 +000021/* elementary operations on complex numbers */
22
Guido van Rossum9e720e31996-07-21 02:31:35 +000023static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000024
Tim Peters0f336042001-03-18 08:21:57 +000025Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040026_Py_c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 Py_complex r;
29 r.real = a.real + b.real;
30 r.imag = a.imag + b.imag;
31 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000032}
33
Tim Peters0f336042001-03-18 08:21:57 +000034Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040035_Py_c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 Py_complex r;
38 r.real = a.real - b.real;
39 r.imag = a.imag - b.imag;
40 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000041}
42
Tim Peters0f336042001-03-18 08:21:57 +000043Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040044_Py_c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 Py_complex r;
47 r.real = -a.real;
48 r.imag = -a.imag;
49 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000050}
51
Tim Peters0f336042001-03-18 08:21:57 +000052Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040053_Py_c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 Py_complex r;
56 r.real = a.real*b.real - a.imag*b.imag;
57 r.imag = a.real*b.imag + a.imag*b.real;
58 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000059}
60
Paul Monsonff6bb0a2019-06-12 11:08:40 -070061/* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
62#ifdef _M_ARM64
63#pragma optimize("", off)
64#endif
Tim Peters0f336042001-03-18 08:21:57 +000065Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040066_Py_c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 /******************************************************************
69 This was the original algorithm. It's grossly prone to spurious
70 overflow and underflow errors. It also merrily divides by 0 despite
71 checking for that(!). The code still serves a doc purpose here, as
72 the algorithm following is a simple by-cases transformation of this
73 one:
Tim Peters0f336042001-03-18 08:21:57 +000074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 Py_complex r;
76 double d = b.real*b.real + b.imag*b.imag;
77 if (d == 0.)
78 errno = EDOM;
79 r.real = (a.real*b.real + a.imag*b.imag)/d;
80 r.imag = (a.imag*b.real - a.real*b.imag)/d;
81 return r;
82 ******************************************************************/
Tim Peters0f336042001-03-18 08:21:57 +000083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 /* This algorithm is better, and is pretty obvious: first divide the
85 * numerators and denominator by whichever of {b.real, b.imag} has
86 * larger magnitude. The earliest reference I found was to CACM
87 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
88 * University). As usual, though, we're still ignoring all IEEE
89 * endcases.
90 */
91 Py_complex r; /* the result */
92 const double abs_breal = b.real < 0 ? -b.real : b.real;
93 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
Tim Peters0f336042001-03-18 08:21:57 +000094
Antoine Pitrou9086f922014-10-10 23:49:32 +020095 if (abs_breal >= abs_bimag) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 /* divide tops and bottom by b.real */
97 if (abs_breal == 0.0) {
98 errno = EDOM;
99 r.real = r.imag = 0.0;
100 }
101 else {
102 const double ratio = b.imag / b.real;
103 const double denom = b.real + b.imag * ratio;
104 r.real = (a.real + a.imag * ratio) / denom;
105 r.imag = (a.imag - a.real * ratio) / denom;
106 }
107 }
Antoine Pitrou9086f922014-10-10 23:49:32 +0200108 else if (abs_bimag >= abs_breal) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 /* divide tops and bottom by b.imag */
110 const double ratio = b.real / b.imag;
111 const double denom = b.real * ratio + b.imag;
112 assert(b.imag != 0.0);
113 r.real = (a.real * ratio + a.imag) / denom;
114 r.imag = (a.imag * ratio - a.real) / denom;
115 }
Antoine Pitrou9086f922014-10-10 23:49:32 +0200116 else {
117 /* At least one of b.real or b.imag is a NaN */
118 r.real = r.imag = Py_NAN;
119 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000121}
Paul Monsonff6bb0a2019-06-12 11:08:40 -0700122#ifdef _M_ARM64
123#pragma optimize("", on)
124#endif
Guido van Rossumf9fca921996-01-12 00:47:05 +0000125
Tim Peters0f336042001-03-18 08:21:57 +0000126Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400127_Py_c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 Py_complex r;
130 double vabs,len,at,phase;
131 if (b.real == 0. && b.imag == 0.) {
132 r.real = 1.;
133 r.imag = 0.;
134 }
135 else if (a.real == 0. && a.imag == 0.) {
136 if (b.imag != 0. || b.real < 0.)
137 errno = EDOM;
138 r.real = 0.;
139 r.imag = 0.;
140 }
141 else {
142 vabs = hypot(a.real,a.imag);
143 len = pow(vabs,b.real);
144 at = atan2(a.imag, a.real);
145 phase = at*b.real;
146 if (b.imag != 0.0) {
147 len /= exp(at*b.imag);
148 phase += b.imag*log(vabs);
149 }
150 r.real = len*cos(phase);
151 r.imag = len*sin(phase);
152 }
153 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000154}
155
Tim Peters0f336042001-03-18 08:21:57 +0000156static Py_complex
157c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 Py_complex r, p;
160 long mask = 1;
161 r = c_1;
162 p = x;
163 while (mask > 0 && n >= mask) {
164 if (n & mask)
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400165 r = _Py_c_prod(r,p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 mask <<= 1;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400167 p = _Py_c_prod(p,p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 }
169 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000170}
171
Tim Peters0f336042001-03-18 08:21:57 +0000172static Py_complex
173c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (n > 100 || n < -100) {
178 cn.real = (double) n;
179 cn.imag = 0.;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400180 return _Py_c_pow(x,cn);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 }
182 else if (n > 0)
183 return c_powu(x,n);
184 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400185 return _Py_c_quot(c_1, c_powu(x,-n));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000186
187}
188
Christian Heimes53876d92008-04-19 00:31:39 +0000189double
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400190_Py_c_abs(Py_complex z)
Christian Heimes53876d92008-04-19 00:31:39 +0000191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
193 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
196 /* C99 rules: if either the real or the imaginary part is an
197 infinity, return infinity, even if the other part is a
198 NaN. */
199 if (Py_IS_INFINITY(z.real)) {
200 result = fabs(z.real);
201 errno = 0;
202 return result;
203 }
204 if (Py_IS_INFINITY(z.imag)) {
205 result = fabs(z.imag);
206 errno = 0;
207 return result;
208 }
209 /* either the real or imaginary part is a NaN,
210 and neither is infinite. Result should be NaN. */
211 return Py_NAN;
212 }
213 result = hypot(z.real, z.imag);
214 if (!Py_IS_FINITE(result))
215 errno = ERANGE;
216 else
217 errno = 0;
218 return result;
Christian Heimes53876d92008-04-19 00:31:39 +0000219}
220
Tim Peters6d6c1a32001-08-02 04:15:00 +0000221static PyObject *
222complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 PyObject *op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 op = type->tp_alloc(type, 0);
227 if (op != NULL)
228 ((PyComplexObject *)op)->cval = cval;
229 return op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000230}
231
Guido van Rossumf9fca921996-01-12 00:47:05 +0000232PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000233PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 /* Inline PyObject_New */
Victor Stinner32bd68c2020-12-01 10:37:39 +0100236 PyComplexObject *op = PyObject_Malloc(sizeof(PyComplexObject));
Victor Stinner04fc4f22020-06-16 01:28:07 +0200237 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 return PyErr_NoMemory();
Victor Stinner04fc4f22020-06-16 01:28:07 +0200239 }
240 _PyObject_Init((PyObject*)op, &PyComplex_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 op->cval = cval;
242 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000243}
244
Tim Peters6d6c1a32001-08-02 04:15:00 +0000245static PyObject *
246complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 Py_complex c;
249 c.real = real;
250 c.imag = imag;
251 return complex_subtype_from_c_complex(type, c);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000252}
253
Guido van Rossumf9fca921996-01-12 00:47:05 +0000254PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000255PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 Py_complex c;
258 c.real = real;
259 c.imag = imag;
260 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000261}
262
263double
Fred Drake4288c802000-07-09 04:36:04 +0000264PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (PyComplex_Check(op)) {
267 return ((PyComplexObject *)op)->cval.real;
268 }
269 else {
270 return PyFloat_AsDouble(op);
271 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000272}
273
274double
Fred Drake4288c802000-07-09 04:36:04 +0000275PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (PyComplex_Check(op)) {
278 return ((PyComplexObject *)op)->cval.imag;
279 }
280 else {
281 return 0.0;
282 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000283}
284
Benjamin Petersonaea44282010-01-04 01:10:28 +0000285static PyObject *
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200286try_complex_special_method(PyObject *op)
287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 PyObject *f;
Benjamin Petersonce798522012-01-22 11:24:29 -0500289 _Py_IDENTIFIER(__complex__);
Benjamin Petersonaea44282010-01-04 01:10:28 +0000290
Benjamin Petersonce798522012-01-22 11:24:29 -0500291 f = _PyObject_LookupSpecial(op, &PyId___complex__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 if (f) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100293 PyObject *res = _PyObject_CallNoArg(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_DECREF(f);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200295 if (!res || PyComplex_CheckExact(res)) {
296 return res;
297 }
298 if (!PyComplex_Check(res)) {
299 PyErr_Format(PyExc_TypeError,
300 "__complex__ returned non-complex (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100301 Py_TYPE(res)->tp_name);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200302 Py_DECREF(res);
303 return NULL;
304 }
305 /* Issue #29894: warn if 'res' not of exact type complex. */
306 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
307 "__complex__ returned non-complex (type %.200s). "
308 "The ability to return an instance of a strict subclass of complex "
309 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100310 Py_TYPE(res)->tp_name)) {
Mark Dickinsond20fb822012-11-14 17:08:31 +0000311 Py_DECREF(res);
312 return NULL;
313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return res;
315 }
316 return NULL;
Benjamin Petersonaea44282010-01-04 01:10:28 +0000317}
318
Guido van Rossum9e720e31996-07-21 02:31:35 +0000319Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000320PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 Py_complex cv;
323 PyObject *newop = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 assert(op);
326 /* If op is already of type PyComplex_Type, return its value */
327 if (PyComplex_Check(op)) {
328 return ((PyComplexObject *)op)->cval;
329 }
330 /* If not, use op's __complex__ method, if it exists */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* return -1 on failure */
333 cv.real = -1.;
334 cv.imag = 0.;
335
336 newop = try_complex_special_method(op);
337
338 if (newop) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 cv = ((PyComplexObject *)newop)->cval;
340 Py_DECREF(newop);
341 return cv;
342 }
343 else if (PyErr_Occurred()) {
344 return cv;
345 }
346 /* If neither of the above works, interpret op as a float giving the
347 real part of the result, and fill in the imaginary part as 0. */
348 else {
349 /* PyFloat_AsDouble will return -1 on failure */
350 cv.real = PyFloat_AsDouble(op);
351 return cv;
352 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000353}
354
Eric Smith0923d1d2009-04-16 20:16:10 +0000355static PyObject *
Eric Smith70099a12010-12-04 13:27:34 +0000356complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000357{
Eric Smith70099a12010-12-04 13:27:34 +0000358 int precision = 0;
359 char format_code = 'r';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyObject *result = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 /* If these are non-NULL, they'll need to be freed. */
363 char *pre = NULL;
364 char *im = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 /* These do not need to be freed. re is either an alias
367 for pre or a pointer to a constant. lead and tail
368 are pointers to constants. */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200369 const char *re = NULL;
370 const char *lead = "";
371 const char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
Eric Smith70099a12010-12-04 13:27:34 +0000374 /* Real part is +0: just output the imaginary part and do not
375 include parens. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 re = "";
377 im = PyOS_double_to_string(v->cval.imag, format_code,
378 precision, 0, NULL);
379 if (!im) {
380 PyErr_NoMemory();
381 goto done;
382 }
383 } else {
Eric Smith70099a12010-12-04 13:27:34 +0000384 /* Format imaginary part with sign, real part without. Include
385 parens in the result. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 pre = PyOS_double_to_string(v->cval.real, format_code,
387 precision, 0, NULL);
388 if (!pre) {
389 PyErr_NoMemory();
390 goto done;
391 }
392 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 im = PyOS_double_to_string(v->cval.imag, format_code,
395 precision, Py_DTSF_SIGN, NULL);
396 if (!im) {
397 PyErr_NoMemory();
398 goto done;
399 }
400 lead = "(";
401 tail = ")";
402 }
Victor Stinner6ced7c42011-03-21 18:15:42 +0100403 result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000404 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 PyMem_Free(im);
406 PyMem_Free(pre);
Eric Smith0923d1d2009-04-16 20:16:10 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000409}
410
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000411static Py_hash_t
Fred Drake4288c802000-07-09 04:36:04 +0000412complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000413{
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000414 Py_uhash_t hashreal, hashimag, combined;
415 hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real);
416 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 return -1;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000418 hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag);
419 if (hashimag == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 return -1;
421 /* Note: if the imaginary part is 0, hashimag is 0 now,
422 * so the following returns hashreal unchanged. This is
423 * important because numbers of different types that
424 * compare equal must have the same hash value, so that
425 * hash(x + 0*j) must equal hash(x).
426 */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000427 combined = hashreal + _PyHASH_IMAG * hashimag;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000428 if (combined == (Py_uhash_t)-1)
429 combined = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000430 return (Py_hash_t)combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000431}
432
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000433/* This macro may return! */
434#define TO_COMPLEX(obj, c) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (PyComplex_Check(obj)) \
436 c = ((PyComplexObject *)(obj))->cval; \
437 else if (to_complex(&(obj), &(c)) < 0) \
438 return (obj)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000439
440static int
441to_complex(PyObject **pobj, Py_complex *pc)
442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 pc->real = pc->imag = 0.0;
446 if (PyLong_Check(obj)) {
447 pc->real = PyLong_AsDouble(obj);
448 if (pc->real == -1.0 && PyErr_Occurred()) {
449 *pobj = NULL;
450 return -1;
451 }
452 return 0;
453 }
454 if (PyFloat_Check(obj)) {
455 pc->real = PyFloat_AsDouble(obj);
456 return 0;
457 }
458 Py_INCREF(Py_NotImplemented);
459 *pobj = Py_NotImplemented;
460 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000461}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000463
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000465complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 Py_complex result;
468 Py_complex a, b;
469 TO_COMPLEX(v, a);
470 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400471 result = _Py_c_sum(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000473}
474
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000475static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000476complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 Py_complex result;
479 Py_complex a, b;
480 TO_COMPLEX(v, a);
481 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400482 result = _Py_c_diff(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000484}
485
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000487complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_complex result;
490 Py_complex a, b;
491 TO_COMPLEX(v, a);
492 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400493 result = _Py_c_prod(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000495}
496
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000497static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000498complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 Py_complex quot;
501 Py_complex a, b;
502 TO_COMPLEX(v, a);
503 TO_COMPLEX(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 errno = 0;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400505 quot = _Py_c_quot(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (errno == EDOM) {
507 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
508 return NULL;
509 }
510 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000511}
512
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000513static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000514complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 Py_complex p;
517 Py_complex exponent;
518 long int_exponent;
519 Py_complex a, b;
520 TO_COMPLEX(v, a);
521 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (z != Py_None) {
524 PyErr_SetString(PyExc_ValueError, "complex modulo");
525 return NULL;
526 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 errno = 0;
528 exponent = b;
529 int_exponent = (long)exponent.real;
530 if (exponent.imag == 0. && exponent.real == int_exponent)
531 p = c_powi(a, int_exponent);
532 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400533 p = _Py_c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 Py_ADJUST_ERANGE2(p.real, p.imag);
536 if (errno == EDOM) {
537 PyErr_SetString(PyExc_ZeroDivisionError,
538 "0.0 to a negative or complex power");
539 return NULL;
540 }
541 else if (errno == ERANGE) {
542 PyErr_SetString(PyExc_OverflowError,
543 "complex exponentiation");
544 return NULL;
545 }
546 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000547}
548
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000549static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000550complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 Py_complex neg;
553 neg.real = -v->cval.real;
554 neg.imag = -v->cval.imag;
555 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000556}
557
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000559complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (PyComplex_CheckExact(v)) {
562 Py_INCREF(v);
563 return (PyObject *)v;
564 }
565 else
566 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000567}
568
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000570complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000573
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400574 result = _Py_c_abs(v->cval);
Christian Heimes53876d92008-04-19 00:31:39 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (errno == ERANGE) {
577 PyErr_SetString(PyExc_OverflowError,
578 "absolute value too large");
579 return NULL;
580 }
581 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000582}
583
584static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000585complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000588}
589
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000590static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000591complex_richcompare(PyObject *v, PyObject *w, int op)
592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000594 Py_complex i;
595 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000598 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 }
Guido van Rossum22056422001-09-24 17:52:04 +0000600
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000601 assert(PyComplex_Check(v));
602 TO_COMPLEX(v, i);
603
604 if (PyLong_Check(w)) {
605 /* Check for 0.0 imaginary part first to avoid the rich
606 * comparison when possible.
607 */
608 if (i.imag == 0.0) {
609 PyObject *j, *sub_res;
610 j = PyFloat_FromDouble(i.real);
611 if (j == NULL)
612 return NULL;
613
614 sub_res = PyObject_RichCompare(j, w, op);
615 Py_DECREF(j);
616 return sub_res;
617 }
618 else {
619 equal = 0;
620 }
621 }
622 else if (PyFloat_Check(w)) {
623 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
624 }
625 else if (PyComplex_Check(w)) {
626 Py_complex j;
627
628 TO_COMPLEX(w, j);
629 equal = (i.real == j.real && i.imag == j.imag);
630 }
631 else {
632 goto Unimplemented;
633 }
634
635 if (equal == (op == Py_EQ))
636 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000638 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 Py_INCREF(res);
641 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000642
643Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500644 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000645}
646
Dong-hee Nae1230122020-07-20 21:53:29 +0900647/*[clinic input]
648complex.conjugate
649
650Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
651[clinic start generated code]*/
652
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000653static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900654complex_conjugate_impl(PyComplexObject *self)
655/*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
Guido van Rossumf9fca921996-01-12 00:47:05 +0000656{
Dong-hee Nae1230122020-07-20 21:53:29 +0900657 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 c.imag = -c.imag;
659 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000660}
661
Dong-hee Nae1230122020-07-20 21:53:29 +0900662/*[clinic input]
663complex.__getnewargs__
664
665[clinic start generated code]*/
Guido van Rossum46334cd2007-08-01 17:43:15 +0000666
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000667static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900668complex___getnewargs___impl(PyComplexObject *self)
669/*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000670{
Dong-hee Nae1230122020-07-20 21:53:29 +0900671 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000673}
674
Dong-hee Nae1230122020-07-20 21:53:29 +0900675
676/*[clinic input]
677complex.__format__
678
679 format_spec: unicode
680 /
681
682Convert to a string according to format_spec.
683[clinic start generated code]*/
Eric Smith58a42242009-04-30 01:00:33 +0000684
685static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900686complex___format___impl(PyComplexObject *self, PyObject *format_spec)
687/*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
Eric Smith58a42242009-04-30 01:00:33 +0000688{
Victor Stinnerd3f08822012-05-29 12:57:52 +0200689 _PyUnicodeWriter writer;
690 int ret;
Victor Stinner8f674cc2013-04-17 23:02:17 +0200691 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +0200692 ret = _PyComplex_FormatAdvancedWriter(
693 &writer,
Dong-hee Nae1230122020-07-20 21:53:29 +0900694 (PyObject *)self,
Victor Stinnerd3f08822012-05-29 12:57:52 +0200695 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
696 if (ret == -1) {
697 _PyUnicodeWriter_Dealloc(&writer);
698 return NULL;
699 }
700 return _PyUnicodeWriter_Finish(&writer);
Eric Smith58a42242009-04-30 01:00:33 +0000701}
702
Guido van Rossumf9fca921996-01-12 00:47:05 +0000703static PyMethodDef complex_methods[] = {
Dong-hee Nae1230122020-07-20 21:53:29 +0900704 COMPLEX_CONJUGATE_METHODDEF
705 COMPLEX___GETNEWARGS___METHODDEF
706 COMPLEX___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000708};
709
Guido van Rossum6f799372001-09-20 20:46:19 +0000710static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
712 "the real part of a complex number"},
713 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
714 "the imaginary part of a complex number"},
715 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000716};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000717
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700719complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 double x=0.0, y=0.0, z;
722 int got_bracket=0;
Brett Cannona721aba2016-09-09 14:57:09 -0700723 const char *start;
724 char *end;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 /* position on first nonblank */
727 start = s;
728 while (Py_ISSPACE(*s))
729 s++;
730 if (*s == '(') {
731 /* Skip over possible bracket from repr(). */
732 got_bracket = 1;
733 s++;
734 while (Py_ISSPACE(*s))
735 s++;
736 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 <float> - real part only
741 <float>j - imaginary part only
742 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 where <float> represents any numeric string that's accepted by the
745 float constructor (including 'nan', 'inf', 'infinity', etc.), and
746 <signed-float> is any string of the form <float> whose first
747 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 <float><sign>j
752 <sign>j
753 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 are also accepted, though support for these forms may be removed from
756 a future version of Python.
757 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* first look for forms starting with <float> */
760 z = PyOS_string_to_double(s, &end, NULL);
761 if (z == -1.0 && PyErr_Occurred()) {
762 if (PyErr_ExceptionMatches(PyExc_ValueError))
763 PyErr_Clear();
764 else
Brett Cannona721aba2016-09-09 14:57:09 -0700765 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 }
767 if (end != s) {
768 /* all 4 forms starting with <float> land here */
769 s = end;
770 if (*s == '+' || *s == '-') {
771 /* <float><signed-float>j | <float><sign>j */
772 x = z;
773 y = PyOS_string_to_double(s, &end, NULL);
774 if (y == -1.0 && PyErr_Occurred()) {
775 if (PyErr_ExceptionMatches(PyExc_ValueError))
776 PyErr_Clear();
777 else
Brett Cannona721aba2016-09-09 14:57:09 -0700778 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 }
780 if (end != s)
781 /* <float><signed-float>j */
782 s = end;
783 else {
784 /* <float><sign>j */
785 y = *s == '+' ? 1.0 : -1.0;
786 s++;
787 }
788 if (!(*s == 'j' || *s == 'J'))
789 goto parse_error;
790 s++;
791 }
792 else if (*s == 'j' || *s == 'J') {
793 /* <float>j */
794 s++;
795 y = z;
796 }
797 else
798 /* <float> */
799 x = z;
800 }
801 else {
802 /* not starting with <float>; must be <sign>j or j */
803 if (*s == '+' || *s == '-') {
804 /* <sign>j */
805 y = *s == '+' ? 1.0 : -1.0;
806 s++;
807 }
808 else
809 /* j */
810 y = 1.0;
811 if (!(*s == 'j' || *s == 'J'))
812 goto parse_error;
813 s++;
814 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 /* trailing whitespace and closing bracket */
817 while (Py_ISSPACE(*s))
818 s++;
819 if (got_bracket) {
820 /* if there was an opening parenthesis, then the corresponding
821 closing parenthesis should be right here */
822 if (*s != ')')
823 goto parse_error;
824 s++;
825 while (Py_ISSPACE(*s))
826 s++;
827 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 /* we should now be at the end of the string */
830 if (s-start != len)
831 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000832
Brett Cannona721aba2016-09-09 14:57:09 -0700833 return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000834
Mark Dickinson6649fa42009-04-24 13:25:20 +0000835 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyErr_SetString(PyExc_ValueError,
837 "complex() arg is a malformed string");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000839}
840
Tim Peters6d6c1a32001-08-02 04:15:00 +0000841static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700842complex_subtype_from_string(PyTypeObject *type, PyObject *v)
843{
844 const char *s;
845 PyObject *s_buffer = NULL, *result = NULL;
846 Py_ssize_t len;
847
848 if (PyUnicode_Check(v)) {
849 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
850 if (s_buffer == NULL) {
851 return NULL;
852 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200853 assert(PyUnicode_IS_ASCII(s_buffer));
854 /* Simply get a pointer to existing ASCII characters. */
Brett Cannona721aba2016-09-09 14:57:09 -0700855 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200856 assert(s != NULL);
Brett Cannona721aba2016-09-09 14:57:09 -0700857 }
858 else {
859 PyErr_Format(PyExc_TypeError,
860 "complex() argument must be a string or a number, not '%.200s'",
861 Py_TYPE(v)->tp_name);
862 return NULL;
863 }
864
865 result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
866 complex_from_string_inner);
Brett Cannona721aba2016-09-09 14:57:09 -0700867 Py_DECREF(s_buffer);
868 return result;
869}
870
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200871/*[clinic input]
872@classmethod
873complex.__new__ as complex_new
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100874 real as r: object(c_default="NULL") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200875 imag as i: object(c_default="NULL") = 0
876
877Create a complex number from a real part and an optional imaginary part.
878
879This is equivalent to (real + imag*1j) where imag defaults to 0.
880[clinic start generated code]*/
881
Brett Cannona721aba2016-09-09 14:57:09 -0700882static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200883complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100884/*[clinic end generated code: output=b6c7dd577b537dc1 input=f4c667f2596d4fd1]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000885{
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200886 PyObject *tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 PyNumberMethods *nbr, *nbi = NULL;
888 Py_complex cr, ci;
889 int own_r = 0;
890 int cr_is_complex = 0;
891 int ci_is_complex = 0;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000892
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100893 if (r == NULL) {
894 r = _PyLong_GetZero();
895 }
896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* Special-case for a single argument when type(arg) is complex. */
898 if (PyComplex_CheckExact(r) && i == NULL &&
899 type == &PyComplex_Type) {
900 /* Note that we can't know whether it's safe to return
901 a complex *subclass* instance as-is, hence the restriction
902 to exact complexes here. If either the input or the
903 output is a complex subclass, it will be handled below
904 as a non-orthogonal vector. */
905 Py_INCREF(r);
906 return r;
907 }
908 if (PyUnicode_Check(r)) {
909 if (i != NULL) {
910 PyErr_SetString(PyExc_TypeError,
911 "complex() can't take second arg"
912 " if first is a string");
913 return NULL;
914 }
915 return complex_subtype_from_string(type, r);
916 }
917 if (i != NULL && PyUnicode_Check(i)) {
918 PyErr_SetString(PyExc_TypeError,
919 "complex() second arg can't be a string");
920 return NULL;
921 }
Tim Peters2400fa42001-09-12 19:12:49 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 tmp = try_complex_special_method(r);
924 if (tmp) {
925 r = tmp;
926 own_r = 1;
927 }
928 else if (PyErr_Occurred()) {
929 return NULL;
930 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000931
Victor Stinner58ac7002020-02-07 03:04:21 +0100932 nbr = Py_TYPE(r)->tp_as_number;
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300933 if (nbr == NULL ||
934 (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
935 {
Ezio Melottia5b95992013-11-07 19:18:34 +0200936 PyErr_Format(PyExc_TypeError,
Mark Dickinson613f8e52016-09-24 15:26:36 +0100937 "complex() first argument must be a string or a number, "
938 "not '%.200s'",
939 Py_TYPE(r)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 if (own_r) {
941 Py_DECREF(r);
942 }
943 return NULL;
944 }
Mark Dickinson613f8e52016-09-24 15:26:36 +0100945 if (i != NULL) {
Victor Stinner58ac7002020-02-07 03:04:21 +0100946 nbi = Py_TYPE(i)->tp_as_number;
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300947 if (nbi == NULL ||
948 (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
949 {
Mark Dickinson613f8e52016-09-24 15:26:36 +0100950 PyErr_Format(PyExc_TypeError,
951 "complex() second argument must be a number, "
952 "not '%.200s'",
953 Py_TYPE(i)->tp_name);
954 if (own_r) {
955 Py_DECREF(r);
956 }
957 return NULL;
958 }
959 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* If we get this far, then the "real" and "imag" parts should
962 both be treated as numbers, and the constructor should return a
963 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 Note that we do NOT assume the input to already be in canonical
966 form; the "real" and "imag" parts might themselves be complex
967 numbers, which slightly complicates the code below. */
968 if (PyComplex_Check(r)) {
969 /* Note that if r is of a complex subtype, we're only
970 retaining its real & imag parts here, and the return
971 value is (properly) of the builtin complex type. */
972 cr = ((PyComplexObject*)r)->cval;
973 cr_is_complex = 1;
974 if (own_r) {
975 Py_DECREF(r);
976 }
977 }
978 else {
979 /* The "real" part really is entirely real, and contributes
980 nothing in the imaginary direction.
981 Just treat it as a double. */
982 tmp = PyNumber_Float(r);
983 if (own_r) {
984 /* r was a newly created complex number, rather
985 than the original "real" argument. */
986 Py_DECREF(r);
987 }
988 if (tmp == NULL)
989 return NULL;
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200990 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 cr.real = PyFloat_AsDouble(tmp);
Mark Dickinson112ec382017-02-20 20:28:15 +0000992 cr.imag = 0.0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 Py_DECREF(tmp);
994 }
995 if (i == NULL) {
Mark Dickinson112ec382017-02-20 20:28:15 +0000996 ci.real = cr.imag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 }
998 else if (PyComplex_Check(i)) {
999 ci = ((PyComplexObject*)i)->cval;
1000 ci_is_complex = 1;
1001 } else {
1002 /* The "imag" part really is entirely imaginary, and
1003 contributes nothing in the real direction.
1004 Just treat it as a double. */
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001005 tmp = PyNumber_Float(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (tmp == NULL)
1007 return NULL;
1008 ci.real = PyFloat_AsDouble(tmp);
1009 Py_DECREF(tmp);
1010 }
1011 /* If the input was in canonical form, then the "real" and "imag"
1012 parts are real numbers, so that ci.imag and cr.imag are zero.
1013 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (ci_is_complex) {
1016 cr.real -= ci.imag;
1017 }
Mark Dickinson112ec382017-02-20 20:28:15 +00001018 if (cr_is_complex && i != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 ci.real += cr.imag;
1020 }
1021 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001022}
1023
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001024static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 (binaryfunc)complex_add, /* nb_add */
1026 (binaryfunc)complex_sub, /* nb_subtract */
1027 (binaryfunc)complex_mul, /* nb_multiply */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001028 0, /* nb_remainder */
1029 0, /* nb_divmod */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 (ternaryfunc)complex_pow, /* nb_power */
1031 (unaryfunc)complex_neg, /* nb_negative */
1032 (unaryfunc)complex_pos, /* nb_positive */
1033 (unaryfunc)complex_abs, /* nb_absolute */
1034 (inquiry)complex_bool, /* nb_bool */
1035 0, /* nb_invert */
1036 0, /* nb_lshift */
1037 0, /* nb_rshift */
1038 0, /* nb_and */
1039 0, /* nb_xor */
1040 0, /* nb_or */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001041 0, /* nb_int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 0, /* nb_reserved */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001043 0, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 0, /* nb_inplace_add */
1045 0, /* nb_inplace_subtract */
1046 0, /* nb_inplace_multiply*/
1047 0, /* nb_inplace_remainder */
1048 0, /* nb_inplace_power */
1049 0, /* nb_inplace_lshift */
1050 0, /* nb_inplace_rshift */
1051 0, /* nb_inplace_and */
1052 0, /* nb_inplace_xor */
1053 0, /* nb_inplace_or */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001054 0, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 (binaryfunc)complex_div, /* nb_true_divide */
1056 0, /* nb_inplace_floor_divide */
1057 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001058};
1059
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001060PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1062 "complex",
1063 sizeof(PyComplexObject),
1064 0,
Inada Naoki7d408692019-05-29 17:23:27 +09001065 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001066 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 0, /* tp_getattr */
1068 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001069 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 (reprfunc)complex_repr, /* tp_repr */
1071 &complex_as_number, /* tp_as_number */
1072 0, /* tp_as_sequence */
1073 0, /* tp_as_mapping */
1074 (hashfunc)complex_hash, /* tp_hash */
1075 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001076 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyObject_GenericGetAttr, /* tp_getattro */
1078 0, /* tp_setattro */
1079 0, /* tp_as_buffer */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001080 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1081 complex_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 0, /* tp_traverse */
1083 0, /* tp_clear */
1084 complex_richcompare, /* tp_richcompare */
1085 0, /* tp_weaklistoffset */
1086 0, /* tp_iter */
1087 0, /* tp_iternext */
1088 complex_methods, /* tp_methods */
1089 complex_members, /* tp_members */
1090 0, /* tp_getset */
1091 0, /* tp_base */
1092 0, /* tp_dict */
1093 0, /* tp_descr_get */
1094 0, /* tp_descr_set */
1095 0, /* tp_dictoffset */
1096 0, /* tp_init */
1097 PyType_GenericAlloc, /* tp_alloc */
1098 complex_new, /* tp_new */
1099 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001100};