blob: 3e479497cfcc31f8c4cf47c5eebd0b3d9bfb21f7 [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{
Miss Islington (bot)3f81e962021-08-17 10:38:03 -0700175 if (n > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 return c_powu(x,n);
177 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400178 return _Py_c_quot(c_1, c_powu(x,-n));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000179
180}
181
Christian Heimes53876d92008-04-19 00:31:39 +0000182double
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400183_Py_c_abs(Py_complex z)
Christian Heimes53876d92008-04-19 00:31:39 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
186 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
189 /* C99 rules: if either the real or the imaginary part is an
190 infinity, return infinity, even if the other part is a
191 NaN. */
192 if (Py_IS_INFINITY(z.real)) {
193 result = fabs(z.real);
194 errno = 0;
195 return result;
196 }
197 if (Py_IS_INFINITY(z.imag)) {
198 result = fabs(z.imag);
199 errno = 0;
200 return result;
201 }
202 /* either the real or imaginary part is a NaN,
203 and neither is infinite. Result should be NaN. */
204 return Py_NAN;
205 }
206 result = hypot(z.real, z.imag);
207 if (!Py_IS_FINITE(result))
208 errno = ERANGE;
209 else
210 errno = 0;
211 return result;
Christian Heimes53876d92008-04-19 00:31:39 +0000212}
213
Tim Peters6d6c1a32001-08-02 04:15:00 +0000214static PyObject *
215complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyObject *op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 op = type->tp_alloc(type, 0);
220 if (op != NULL)
221 ((PyComplexObject *)op)->cval = cval;
222 return op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000223}
224
Guido van Rossumf9fca921996-01-12 00:47:05 +0000225PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000226PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 /* Inline PyObject_New */
Victor Stinner32bd68c2020-12-01 10:37:39 +0100229 PyComplexObject *op = PyObject_Malloc(sizeof(PyComplexObject));
Victor Stinner04fc4f22020-06-16 01:28:07 +0200230 if (op == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 return PyErr_NoMemory();
Victor Stinner04fc4f22020-06-16 01:28:07 +0200232 }
233 _PyObject_Init((PyObject*)op, &PyComplex_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 op->cval = cval;
235 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000236}
237
Tim Peters6d6c1a32001-08-02 04:15:00 +0000238static PyObject *
239complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 Py_complex c;
242 c.real = real;
243 c.imag = imag;
244 return complex_subtype_from_c_complex(type, c);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000245}
246
Guido van Rossumf9fca921996-01-12 00:47:05 +0000247PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000248PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 Py_complex c;
251 c.real = real;
252 c.imag = imag;
253 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000254}
255
256double
Fred Drake4288c802000-07-09 04:36:04 +0000257PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (PyComplex_Check(op)) {
260 return ((PyComplexObject *)op)->cval.real;
261 }
262 else {
263 return PyFloat_AsDouble(op);
264 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000265}
266
267double
Fred Drake4288c802000-07-09 04:36:04 +0000268PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 if (PyComplex_Check(op)) {
271 return ((PyComplexObject *)op)->cval.imag;
272 }
273 else {
274 return 0.0;
275 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000276}
277
Benjamin Petersonaea44282010-01-04 01:10:28 +0000278static PyObject *
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200279try_complex_special_method(PyObject *op)
280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 PyObject *f;
Benjamin Petersonce798522012-01-22 11:24:29 -0500282 _Py_IDENTIFIER(__complex__);
Benjamin Petersonaea44282010-01-04 01:10:28 +0000283
Benjamin Petersonce798522012-01-22 11:24:29 -0500284 f = _PyObject_LookupSpecial(op, &PyId___complex__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (f) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100286 PyObject *res = _PyObject_CallNoArg(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Py_DECREF(f);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200288 if (!res || PyComplex_CheckExact(res)) {
289 return res;
290 }
291 if (!PyComplex_Check(res)) {
292 PyErr_Format(PyExc_TypeError,
293 "__complex__ returned non-complex (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100294 Py_TYPE(res)->tp_name);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200295 Py_DECREF(res);
296 return NULL;
297 }
298 /* Issue #29894: warn if 'res' not of exact type complex. */
299 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
300 "__complex__ returned non-complex (type %.200s). "
301 "The ability to return an instance of a strict subclass of complex "
302 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100303 Py_TYPE(res)->tp_name)) {
Mark Dickinsond20fb822012-11-14 17:08:31 +0000304 Py_DECREF(res);
305 return NULL;
306 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return res;
308 }
309 return NULL;
Benjamin Petersonaea44282010-01-04 01:10:28 +0000310}
311
Guido van Rossum9e720e31996-07-21 02:31:35 +0000312Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000313PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 Py_complex cv;
316 PyObject *newop = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 assert(op);
319 /* If op is already of type PyComplex_Type, return its value */
320 if (PyComplex_Check(op)) {
321 return ((PyComplexObject *)op)->cval;
322 }
323 /* If not, use op's __complex__ method, if it exists */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 /* return -1 on failure */
326 cv.real = -1.;
327 cv.imag = 0.;
328
329 newop = try_complex_special_method(op);
330
331 if (newop) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 cv = ((PyComplexObject *)newop)->cval;
333 Py_DECREF(newop);
334 return cv;
335 }
336 else if (PyErr_Occurred()) {
337 return cv;
338 }
339 /* If neither of the above works, interpret op as a float giving the
340 real part of the result, and fill in the imaginary part as 0. */
341 else {
342 /* PyFloat_AsDouble will return -1 on failure */
343 cv.real = PyFloat_AsDouble(op);
344 return cv;
345 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000346}
347
Eric Smith0923d1d2009-04-16 20:16:10 +0000348static PyObject *
Eric Smith70099a12010-12-04 13:27:34 +0000349complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000350{
Eric Smith70099a12010-12-04 13:27:34 +0000351 int precision = 0;
352 char format_code = 'r';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyObject *result = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* If these are non-NULL, they'll need to be freed. */
356 char *pre = NULL;
357 char *im = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 /* These do not need to be freed. re is either an alias
360 for pre or a pointer to a constant. lead and tail
361 are pointers to constants. */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200362 const char *re = NULL;
363 const char *lead = "";
364 const char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
Eric Smith70099a12010-12-04 13:27:34 +0000367 /* Real part is +0: just output the imaginary part and do not
368 include parens. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 re = "";
370 im = PyOS_double_to_string(v->cval.imag, format_code,
371 precision, 0, NULL);
372 if (!im) {
373 PyErr_NoMemory();
374 goto done;
375 }
376 } else {
Eric Smith70099a12010-12-04 13:27:34 +0000377 /* Format imaginary part with sign, real part without. Include
378 parens in the result. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 pre = PyOS_double_to_string(v->cval.real, format_code,
380 precision, 0, NULL);
381 if (!pre) {
382 PyErr_NoMemory();
383 goto done;
384 }
385 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 im = PyOS_double_to_string(v->cval.imag, format_code,
388 precision, Py_DTSF_SIGN, NULL);
389 if (!im) {
390 PyErr_NoMemory();
391 goto done;
392 }
393 lead = "(";
394 tail = ")";
395 }
Victor Stinner6ced7c42011-03-21 18:15:42 +0100396 result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000397 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 PyMem_Free(im);
399 PyMem_Free(pre);
Eric Smith0923d1d2009-04-16 20:16:10 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000402}
403
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000404static Py_hash_t
Fred Drake4288c802000-07-09 04:36:04 +0000405complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000406{
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000407 Py_uhash_t hashreal, hashimag, combined;
Raymond Hettingera07da092021-04-22 08:34:57 -0700408 hashreal = (Py_uhash_t)_Py_HashDouble((PyObject *) v, v->cval.real);
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000409 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 return -1;
Raymond Hettingera07da092021-04-22 08:34:57 -0700411 hashimag = (Py_uhash_t)_Py_HashDouble((PyObject *)v, v->cval.imag);
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000412 if (hashimag == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 return -1;
414 /* Note: if the imaginary part is 0, hashimag is 0 now,
415 * so the following returns hashreal unchanged. This is
416 * important because numbers of different types that
417 * compare equal must have the same hash value, so that
418 * hash(x + 0*j) must equal hash(x).
419 */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000420 combined = hashreal + _PyHASH_IMAG * hashimag;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000421 if (combined == (Py_uhash_t)-1)
422 combined = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000423 return (Py_hash_t)combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000424}
425
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000426/* This macro may return! */
427#define TO_COMPLEX(obj, c) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (PyComplex_Check(obj)) \
429 c = ((PyComplexObject *)(obj))->cval; \
430 else if (to_complex(&(obj), &(c)) < 0) \
431 return (obj)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000432
433static int
434to_complex(PyObject **pobj, Py_complex *pc)
435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 pc->real = pc->imag = 0.0;
439 if (PyLong_Check(obj)) {
440 pc->real = PyLong_AsDouble(obj);
441 if (pc->real == -1.0 && PyErr_Occurred()) {
442 *pobj = NULL;
443 return -1;
444 }
445 return 0;
446 }
447 if (PyFloat_Check(obj)) {
448 pc->real = PyFloat_AsDouble(obj);
449 return 0;
450 }
451 Py_INCREF(Py_NotImplemented);
452 *pobj = Py_NotImplemented;
453 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000454}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000456
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000458complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_complex result;
461 Py_complex a, b;
462 TO_COMPLEX(v, a);
463 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400464 result = _Py_c_sum(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000466}
467
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000469complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_complex result;
472 Py_complex a, b;
473 TO_COMPLEX(v, a);
474 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400475 result = _Py_c_diff(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000477}
478
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000480complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 Py_complex result;
483 Py_complex a, b;
484 TO_COMPLEX(v, a);
485 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400486 result = _Py_c_prod(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000488}
489
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000491complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 Py_complex quot;
494 Py_complex a, b;
495 TO_COMPLEX(v, a);
496 TO_COMPLEX(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 errno = 0;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400498 quot = _Py_c_quot(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 if (errno == EDOM) {
500 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
501 return NULL;
502 }
503 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000504}
505
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000507complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 Py_complex p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 Py_complex a, b;
511 TO_COMPLEX(v, a);
512 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (z != Py_None) {
515 PyErr_SetString(PyExc_ValueError, "complex modulo");
516 return NULL;
517 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 errno = 0;
Miss Islington (bot)3f81e962021-08-17 10:38:03 -0700519 // Check whether the exponent has a small integer value, and if so use
520 // a faster and more accurate algorithm.
521 if (b.imag == 0.0 && b.real == floor(b.real) && fabs(b.real) <= 100.0) {
522 p = c_powi(a, (long)b.real);
523 }
524 else {
Miss Islington (bot)256d97c2021-07-26 12:29:52 -0700525 p = _Py_c_pow(a, b);
526 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 Py_ADJUST_ERANGE2(p.real, p.imag);
529 if (errno == EDOM) {
530 PyErr_SetString(PyExc_ZeroDivisionError,
531 "0.0 to a negative or complex power");
532 return NULL;
533 }
534 else if (errno == ERANGE) {
535 PyErr_SetString(PyExc_OverflowError,
536 "complex exponentiation");
537 return NULL;
538 }
539 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000540}
541
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000543complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 Py_complex neg;
546 neg.real = -v->cval.real;
547 neg.imag = -v->cval.imag;
548 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000549}
550
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000551static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000552complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (PyComplex_CheckExact(v)) {
555 Py_INCREF(v);
556 return (PyObject *)v;
557 }
558 else
559 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000560}
561
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000562static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000563complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000566
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400567 result = _Py_c_abs(v->cval);
Christian Heimes53876d92008-04-19 00:31:39 +0000568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (errno == ERANGE) {
570 PyErr_SetString(PyExc_OverflowError,
571 "absolute value too large");
572 return NULL;
573 }
574 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000575}
576
577static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000578complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000581}
582
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000584complex_richcompare(PyObject *v, PyObject *w, int op)
585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000587 Py_complex i;
588 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000591 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 }
Guido van Rossum22056422001-09-24 17:52:04 +0000593
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000594 assert(PyComplex_Check(v));
595 TO_COMPLEX(v, i);
596
597 if (PyLong_Check(w)) {
598 /* Check for 0.0 imaginary part first to avoid the rich
599 * comparison when possible.
600 */
601 if (i.imag == 0.0) {
602 PyObject *j, *sub_res;
603 j = PyFloat_FromDouble(i.real);
604 if (j == NULL)
605 return NULL;
606
607 sub_res = PyObject_RichCompare(j, w, op);
608 Py_DECREF(j);
609 return sub_res;
610 }
611 else {
612 equal = 0;
613 }
614 }
615 else if (PyFloat_Check(w)) {
616 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
617 }
618 else if (PyComplex_Check(w)) {
619 Py_complex j;
620
621 TO_COMPLEX(w, j);
622 equal = (i.real == j.real && i.imag == j.imag);
623 }
624 else {
625 goto Unimplemented;
626 }
627
628 if (equal == (op == Py_EQ))
629 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000631 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 Py_INCREF(res);
634 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000635
636Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500637 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000638}
639
Dong-hee Nae1230122020-07-20 21:53:29 +0900640/*[clinic input]
641complex.conjugate
642
643Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
644[clinic start generated code]*/
645
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000646static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900647complex_conjugate_impl(PyComplexObject *self)
648/*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
Guido van Rossumf9fca921996-01-12 00:47:05 +0000649{
Dong-hee Nae1230122020-07-20 21:53:29 +0900650 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 c.imag = -c.imag;
652 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000653}
654
Dong-hee Nae1230122020-07-20 21:53:29 +0900655/*[clinic input]
656complex.__getnewargs__
657
658[clinic start generated code]*/
Guido van Rossum46334cd2007-08-01 17:43:15 +0000659
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000660static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900661complex___getnewargs___impl(PyComplexObject *self)
662/*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000663{
Dong-hee Nae1230122020-07-20 21:53:29 +0900664 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000666}
667
Dong-hee Nae1230122020-07-20 21:53:29 +0900668
669/*[clinic input]
670complex.__format__
671
672 format_spec: unicode
673 /
674
675Convert to a string according to format_spec.
676[clinic start generated code]*/
Eric Smith58a42242009-04-30 01:00:33 +0000677
678static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900679complex___format___impl(PyComplexObject *self, PyObject *format_spec)
680/*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
Eric Smith58a42242009-04-30 01:00:33 +0000681{
Victor Stinnerd3f08822012-05-29 12:57:52 +0200682 _PyUnicodeWriter writer;
683 int ret;
Victor Stinner8f674cc2013-04-17 23:02:17 +0200684 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +0200685 ret = _PyComplex_FormatAdvancedWriter(
686 &writer,
Dong-hee Nae1230122020-07-20 21:53:29 +0900687 (PyObject *)self,
Victor Stinnerd3f08822012-05-29 12:57:52 +0200688 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
689 if (ret == -1) {
690 _PyUnicodeWriter_Dealloc(&writer);
691 return NULL;
692 }
693 return _PyUnicodeWriter_Finish(&writer);
Eric Smith58a42242009-04-30 01:00:33 +0000694}
695
Guido van Rossumf9fca921996-01-12 00:47:05 +0000696static PyMethodDef complex_methods[] = {
Dong-hee Nae1230122020-07-20 21:53:29 +0900697 COMPLEX_CONJUGATE_METHODDEF
698 COMPLEX___GETNEWARGS___METHODDEF
699 COMPLEX___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000701};
702
Guido van Rossum6f799372001-09-20 20:46:19 +0000703static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
705 "the real part of a complex number"},
706 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
707 "the imaginary part of a complex number"},
708 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000709};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000710
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000711static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700712complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 double x=0.0, y=0.0, z;
715 int got_bracket=0;
Brett Cannona721aba2016-09-09 14:57:09 -0700716 const char *start;
717 char *end;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 /* position on first nonblank */
720 start = s;
721 while (Py_ISSPACE(*s))
722 s++;
723 if (*s == '(') {
724 /* Skip over possible bracket from repr(). */
725 got_bracket = 1;
726 s++;
727 while (Py_ISSPACE(*s))
728 s++;
729 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 <float> - real part only
734 <float>j - imaginary part only
735 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 where <float> represents any numeric string that's accepted by the
738 float constructor (including 'nan', 'inf', 'infinity', etc.), and
739 <signed-float> is any string of the form <float> whose first
740 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 <float><sign>j
745 <sign>j
746 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 are also accepted, though support for these forms may be removed from
749 a future version of Python.
750 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 /* first look for forms starting with <float> */
753 z = PyOS_string_to_double(s, &end, NULL);
754 if (z == -1.0 && PyErr_Occurred()) {
755 if (PyErr_ExceptionMatches(PyExc_ValueError))
756 PyErr_Clear();
757 else
Brett Cannona721aba2016-09-09 14:57:09 -0700758 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
760 if (end != s) {
761 /* all 4 forms starting with <float> land here */
762 s = end;
763 if (*s == '+' || *s == '-') {
764 /* <float><signed-float>j | <float><sign>j */
765 x = z;
766 y = PyOS_string_to_double(s, &end, NULL);
767 if (y == -1.0 && PyErr_Occurred()) {
768 if (PyErr_ExceptionMatches(PyExc_ValueError))
769 PyErr_Clear();
770 else
Brett Cannona721aba2016-09-09 14:57:09 -0700771 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 }
773 if (end != s)
774 /* <float><signed-float>j */
775 s = end;
776 else {
777 /* <float><sign>j */
778 y = *s == '+' ? 1.0 : -1.0;
779 s++;
780 }
781 if (!(*s == 'j' || *s == 'J'))
782 goto parse_error;
783 s++;
784 }
785 else if (*s == 'j' || *s == 'J') {
786 /* <float>j */
787 s++;
788 y = z;
789 }
790 else
791 /* <float> */
792 x = z;
793 }
794 else {
795 /* not starting with <float>; must be <sign>j or j */
796 if (*s == '+' || *s == '-') {
797 /* <sign>j */
798 y = *s == '+' ? 1.0 : -1.0;
799 s++;
800 }
801 else
802 /* j */
803 y = 1.0;
804 if (!(*s == 'j' || *s == 'J'))
805 goto parse_error;
806 s++;
807 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 /* trailing whitespace and closing bracket */
810 while (Py_ISSPACE(*s))
811 s++;
812 if (got_bracket) {
813 /* if there was an opening parenthesis, then the corresponding
814 closing parenthesis should be right here */
815 if (*s != ')')
816 goto parse_error;
817 s++;
818 while (Py_ISSPACE(*s))
819 s++;
820 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 /* we should now be at the end of the string */
823 if (s-start != len)
824 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825
Brett Cannona721aba2016-09-09 14:57:09 -0700826 return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000827
Mark Dickinson6649fa42009-04-24 13:25:20 +0000828 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 PyErr_SetString(PyExc_ValueError,
830 "complex() arg is a malformed string");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000832}
833
Tim Peters6d6c1a32001-08-02 04:15:00 +0000834static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700835complex_subtype_from_string(PyTypeObject *type, PyObject *v)
836{
837 const char *s;
838 PyObject *s_buffer = NULL, *result = NULL;
839 Py_ssize_t len;
840
841 if (PyUnicode_Check(v)) {
842 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
843 if (s_buffer == NULL) {
844 return NULL;
845 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200846 assert(PyUnicode_IS_ASCII(s_buffer));
847 /* Simply get a pointer to existing ASCII characters. */
Brett Cannona721aba2016-09-09 14:57:09 -0700848 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200849 assert(s != NULL);
Brett Cannona721aba2016-09-09 14:57:09 -0700850 }
851 else {
852 PyErr_Format(PyExc_TypeError,
853 "complex() argument must be a string or a number, not '%.200s'",
854 Py_TYPE(v)->tp_name);
855 return NULL;
856 }
857
858 result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
859 complex_from_string_inner);
Brett Cannona721aba2016-09-09 14:57:09 -0700860 Py_DECREF(s_buffer);
861 return result;
862}
863
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200864/*[clinic input]
865@classmethod
866complex.__new__ as complex_new
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100867 real as r: object(c_default="NULL") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200868 imag as i: object(c_default="NULL") = 0
869
870Create a complex number from a real part and an optional imaginary part.
871
872This is equivalent to (real + imag*1j) where imag defaults to 0.
873[clinic start generated code]*/
874
Brett Cannona721aba2016-09-09 14:57:09 -0700875static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200876complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100877/*[clinic end generated code: output=b6c7dd577b537dc1 input=f4c667f2596d4fd1]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000878{
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200879 PyObject *tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyNumberMethods *nbr, *nbi = NULL;
881 Py_complex cr, ci;
882 int own_r = 0;
883 int cr_is_complex = 0;
884 int ci_is_complex = 0;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000885
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100886 if (r == NULL) {
887 r = _PyLong_GetZero();
888 }
889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 /* Special-case for a single argument when type(arg) is complex. */
891 if (PyComplex_CheckExact(r) && i == NULL &&
892 type == &PyComplex_Type) {
893 /* Note that we can't know whether it's safe to return
894 a complex *subclass* instance as-is, hence the restriction
895 to exact complexes here. If either the input or the
896 output is a complex subclass, it will be handled below
897 as a non-orthogonal vector. */
898 Py_INCREF(r);
899 return r;
900 }
901 if (PyUnicode_Check(r)) {
902 if (i != NULL) {
903 PyErr_SetString(PyExc_TypeError,
904 "complex() can't take second arg"
905 " if first is a string");
906 return NULL;
907 }
908 return complex_subtype_from_string(type, r);
909 }
910 if (i != NULL && PyUnicode_Check(i)) {
911 PyErr_SetString(PyExc_TypeError,
912 "complex() second arg can't be a string");
913 return NULL;
914 }
Tim Peters2400fa42001-09-12 19:12:49 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 tmp = try_complex_special_method(r);
917 if (tmp) {
918 r = tmp;
919 own_r = 1;
920 }
921 else if (PyErr_Occurred()) {
922 return NULL;
923 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000924
Victor Stinner58ac7002020-02-07 03:04:21 +0100925 nbr = Py_TYPE(r)->tp_as_number;
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300926 if (nbr == NULL ||
927 (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
928 {
Ezio Melottia5b95992013-11-07 19:18:34 +0200929 PyErr_Format(PyExc_TypeError,
Mark Dickinson613f8e52016-09-24 15:26:36 +0100930 "complex() first argument must be a string or a number, "
931 "not '%.200s'",
932 Py_TYPE(r)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (own_r) {
934 Py_DECREF(r);
935 }
936 return NULL;
937 }
Mark Dickinson613f8e52016-09-24 15:26:36 +0100938 if (i != NULL) {
Victor Stinner58ac7002020-02-07 03:04:21 +0100939 nbi = Py_TYPE(i)->tp_as_number;
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300940 if (nbi == NULL ||
941 (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
942 {
Mark Dickinson613f8e52016-09-24 15:26:36 +0100943 PyErr_Format(PyExc_TypeError,
944 "complex() second argument must be a number, "
945 "not '%.200s'",
946 Py_TYPE(i)->tp_name);
947 if (own_r) {
948 Py_DECREF(r);
949 }
950 return NULL;
951 }
952 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* If we get this far, then the "real" and "imag" parts should
955 both be treated as numbers, and the constructor should return a
956 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 Note that we do NOT assume the input to already be in canonical
959 form; the "real" and "imag" parts might themselves be complex
960 numbers, which slightly complicates the code below. */
961 if (PyComplex_Check(r)) {
962 /* Note that if r is of a complex subtype, we're only
963 retaining its real & imag parts here, and the return
964 value is (properly) of the builtin complex type. */
965 cr = ((PyComplexObject*)r)->cval;
966 cr_is_complex = 1;
967 if (own_r) {
968 Py_DECREF(r);
969 }
970 }
971 else {
972 /* The "real" part really is entirely real, and contributes
973 nothing in the imaginary direction.
974 Just treat it as a double. */
975 tmp = PyNumber_Float(r);
976 if (own_r) {
977 /* r was a newly created complex number, rather
978 than the original "real" argument. */
979 Py_DECREF(r);
980 }
981 if (tmp == NULL)
982 return NULL;
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200983 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 cr.real = PyFloat_AsDouble(tmp);
Mark Dickinson112ec382017-02-20 20:28:15 +0000985 cr.imag = 0.0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 Py_DECREF(tmp);
987 }
988 if (i == NULL) {
Mark Dickinson112ec382017-02-20 20:28:15 +0000989 ci.real = cr.imag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 }
991 else if (PyComplex_Check(i)) {
992 ci = ((PyComplexObject*)i)->cval;
993 ci_is_complex = 1;
994 } else {
995 /* The "imag" part really is entirely imaginary, and
996 contributes nothing in the real direction.
997 Just treat it as a double. */
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300998 tmp = PyNumber_Float(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (tmp == NULL)
1000 return NULL;
1001 ci.real = PyFloat_AsDouble(tmp);
1002 Py_DECREF(tmp);
1003 }
1004 /* If the input was in canonical form, then the "real" and "imag"
1005 parts are real numbers, so that ci.imag and cr.imag are zero.
1006 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (ci_is_complex) {
1009 cr.real -= ci.imag;
1010 }
Mark Dickinson112ec382017-02-20 20:28:15 +00001011 if (cr_is_complex && i != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 ci.real += cr.imag;
1013 }
1014 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001015}
1016
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001017static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 (binaryfunc)complex_add, /* nb_add */
1019 (binaryfunc)complex_sub, /* nb_subtract */
1020 (binaryfunc)complex_mul, /* nb_multiply */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001021 0, /* nb_remainder */
1022 0, /* nb_divmod */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 (ternaryfunc)complex_pow, /* nb_power */
1024 (unaryfunc)complex_neg, /* nb_negative */
1025 (unaryfunc)complex_pos, /* nb_positive */
1026 (unaryfunc)complex_abs, /* nb_absolute */
1027 (inquiry)complex_bool, /* nb_bool */
1028 0, /* nb_invert */
1029 0, /* nb_lshift */
1030 0, /* nb_rshift */
1031 0, /* nb_and */
1032 0, /* nb_xor */
1033 0, /* nb_or */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001034 0, /* nb_int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 0, /* nb_reserved */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001036 0, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 0, /* nb_inplace_add */
1038 0, /* nb_inplace_subtract */
1039 0, /* nb_inplace_multiply*/
1040 0, /* nb_inplace_remainder */
1041 0, /* nb_inplace_power */
1042 0, /* nb_inplace_lshift */
1043 0, /* nb_inplace_rshift */
1044 0, /* nb_inplace_and */
1045 0, /* nb_inplace_xor */
1046 0, /* nb_inplace_or */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001047 0, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 (binaryfunc)complex_div, /* nb_true_divide */
1049 0, /* nb_inplace_floor_divide */
1050 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001051};
1052
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001053PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1055 "complex",
1056 sizeof(PyComplexObject),
1057 0,
Inada Naoki7d408692019-05-29 17:23:27 +09001058 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001059 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 0, /* tp_getattr */
1061 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001062 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 (reprfunc)complex_repr, /* tp_repr */
1064 &complex_as_number, /* tp_as_number */
1065 0, /* tp_as_sequence */
1066 0, /* tp_as_mapping */
1067 (hashfunc)complex_hash, /* tp_hash */
1068 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001069 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyObject_GenericGetAttr, /* tp_getattro */
1071 0, /* tp_setattro */
1072 0, /* tp_as_buffer */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001073 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1074 complex_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 0, /* tp_traverse */
1076 0, /* tp_clear */
1077 complex_richcompare, /* tp_richcompare */
1078 0, /* tp_weaklistoffset */
1079 0, /* tp_iter */
1080 0, /* tp_iternext */
1081 complex_methods, /* tp_methods */
1082 complex_members, /* tp_members */
1083 0, /* tp_getset */
1084 0, /* tp_base */
1085 0, /* tp_dict */
1086 0, /* tp_descr_get */
1087 0, /* tp_descr_set */
1088 0, /* tp_dictoffset */
1089 0, /* tp_init */
1090 PyType_GenericAlloc, /* tp_alloc */
1091 complex_new, /* tp_new */
1092 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001093};