blob: 05cae32f528c467fb9eed5e6b0d9e233c811f23c [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;
Raymond Hettingera07da092021-04-22 08:34:57 -0700415 hashreal = (Py_uhash_t)_Py_HashDouble((PyObject *) v, v->cval.real);
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000416 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 return -1;
Raymond Hettingera07da092021-04-22 08:34:57 -0700418 hashimag = (Py_uhash_t)_Py_HashDouble((PyObject *)v, v->cval.imag);
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000419 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;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 Py_complex a, b;
518 TO_COMPLEX(v, a);
519 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (z != Py_None) {
522 PyErr_SetString(PyExc_ValueError, "complex modulo");
523 return NULL;
524 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 errno = 0;
Miss Islington (bot)256d97c2021-07-26 12:29:52 -0700526 // Check if w is an integer value that fits inside a C long, so we can
527 // use a faster algorithm. TO_COMPLEX(w, b), above, already handled the
528 // conversion from larger longs, as well as other types.
529 if (PyLong_Check(w)) {
530 int overflow = 0;
531 long int_exponent = PyLong_AsLongAndOverflow(w, &overflow);
532 if (int_exponent == -1 && PyErr_Occurred())
533 return NULL;
534 if (overflow == 0)
535 p = c_powi(a, int_exponent);
536 else
537 p = _Py_c_pow(a, b);
538 } else {
539 p = _Py_c_pow(a, b);
540 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 Py_ADJUST_ERANGE2(p.real, p.imag);
543 if (errno == EDOM) {
544 PyErr_SetString(PyExc_ZeroDivisionError,
545 "0.0 to a negative or complex power");
546 return NULL;
547 }
548 else if (errno == ERANGE) {
549 PyErr_SetString(PyExc_OverflowError,
550 "complex exponentiation");
551 return NULL;
552 }
553 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000554}
555
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000556static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000557complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 Py_complex neg;
560 neg.real = -v->cval.real;
561 neg.imag = -v->cval.imag;
562 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000563}
564
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000566complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 if (PyComplex_CheckExact(v)) {
569 Py_INCREF(v);
570 return (PyObject *)v;
571 }
572 else
573 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000574}
575
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000576static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000577complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000580
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400581 result = _Py_c_abs(v->cval);
Christian Heimes53876d92008-04-19 00:31:39 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (errno == ERANGE) {
584 PyErr_SetString(PyExc_OverflowError,
585 "absolute value too large");
586 return NULL;
587 }
588 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000589}
590
591static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000592complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000595}
596
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000597static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000598complex_richcompare(PyObject *v, PyObject *w, int op)
599{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000601 Py_complex i;
602 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000605 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 }
Guido van Rossum22056422001-09-24 17:52:04 +0000607
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000608 assert(PyComplex_Check(v));
609 TO_COMPLEX(v, i);
610
611 if (PyLong_Check(w)) {
612 /* Check for 0.0 imaginary part first to avoid the rich
613 * comparison when possible.
614 */
615 if (i.imag == 0.0) {
616 PyObject *j, *sub_res;
617 j = PyFloat_FromDouble(i.real);
618 if (j == NULL)
619 return NULL;
620
621 sub_res = PyObject_RichCompare(j, w, op);
622 Py_DECREF(j);
623 return sub_res;
624 }
625 else {
626 equal = 0;
627 }
628 }
629 else if (PyFloat_Check(w)) {
630 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
631 }
632 else if (PyComplex_Check(w)) {
633 Py_complex j;
634
635 TO_COMPLEX(w, j);
636 equal = (i.real == j.real && i.imag == j.imag);
637 }
638 else {
639 goto Unimplemented;
640 }
641
642 if (equal == (op == Py_EQ))
643 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000645 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 Py_INCREF(res);
648 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000649
650Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500651 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000652}
653
Dong-hee Nae1230122020-07-20 21:53:29 +0900654/*[clinic input]
655complex.conjugate
656
657Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
658[clinic start generated code]*/
659
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900661complex_conjugate_impl(PyComplexObject *self)
662/*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
Guido van Rossumf9fca921996-01-12 00:47:05 +0000663{
Dong-hee Nae1230122020-07-20 21:53:29 +0900664 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 c.imag = -c.imag;
666 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000667}
668
Dong-hee Nae1230122020-07-20 21:53:29 +0900669/*[clinic input]
670complex.__getnewargs__
671
672[clinic start generated code]*/
Guido van Rossum46334cd2007-08-01 17:43:15 +0000673
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000674static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900675complex___getnewargs___impl(PyComplexObject *self)
676/*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000677{
Dong-hee Nae1230122020-07-20 21:53:29 +0900678 Py_complex c = self->cval;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000680}
681
Dong-hee Nae1230122020-07-20 21:53:29 +0900682
683/*[clinic input]
684complex.__format__
685
686 format_spec: unicode
687 /
688
689Convert to a string according to format_spec.
690[clinic start generated code]*/
Eric Smith58a42242009-04-30 01:00:33 +0000691
692static PyObject *
Dong-hee Nae1230122020-07-20 21:53:29 +0900693complex___format___impl(PyComplexObject *self, PyObject *format_spec)
694/*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
Eric Smith58a42242009-04-30 01:00:33 +0000695{
Victor Stinnerd3f08822012-05-29 12:57:52 +0200696 _PyUnicodeWriter writer;
697 int ret;
Victor Stinner8f674cc2013-04-17 23:02:17 +0200698 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +0200699 ret = _PyComplex_FormatAdvancedWriter(
700 &writer,
Dong-hee Nae1230122020-07-20 21:53:29 +0900701 (PyObject *)self,
Victor Stinnerd3f08822012-05-29 12:57:52 +0200702 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
703 if (ret == -1) {
704 _PyUnicodeWriter_Dealloc(&writer);
705 return NULL;
706 }
707 return _PyUnicodeWriter_Finish(&writer);
Eric Smith58a42242009-04-30 01:00:33 +0000708}
709
Guido van Rossumf9fca921996-01-12 00:47:05 +0000710static PyMethodDef complex_methods[] = {
Dong-hee Nae1230122020-07-20 21:53:29 +0900711 COMPLEX_CONJUGATE_METHODDEF
712 COMPLEX___GETNEWARGS___METHODDEF
713 COMPLEX___FORMAT___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000715};
716
Guido van Rossum6f799372001-09-20 20:46:19 +0000717static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
719 "the real part of a complex number"},
720 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
721 "the imaginary part of a complex number"},
722 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000723};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000724
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000725static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700726complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 double x=0.0, y=0.0, z;
729 int got_bracket=0;
Brett Cannona721aba2016-09-09 14:57:09 -0700730 const char *start;
731 char *end;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 /* position on first nonblank */
734 start = s;
735 while (Py_ISSPACE(*s))
736 s++;
737 if (*s == '(') {
738 /* Skip over possible bracket from repr(). */
739 got_bracket = 1;
740 s++;
741 while (Py_ISSPACE(*s))
742 s++;
743 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 <float> - real part only
748 <float>j - imaginary part only
749 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 where <float> represents any numeric string that's accepted by the
752 float constructor (including 'nan', 'inf', 'infinity', etc.), and
753 <signed-float> is any string of the form <float> whose first
754 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 <float><sign>j
759 <sign>j
760 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 are also accepted, though support for these forms may be removed from
763 a future version of Python.
764 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 /* first look for forms starting with <float> */
767 z = PyOS_string_to_double(s, &end, NULL);
768 if (z == -1.0 && PyErr_Occurred()) {
769 if (PyErr_ExceptionMatches(PyExc_ValueError))
770 PyErr_Clear();
771 else
Brett Cannona721aba2016-09-09 14:57:09 -0700772 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 }
774 if (end != s) {
775 /* all 4 forms starting with <float> land here */
776 s = end;
777 if (*s == '+' || *s == '-') {
778 /* <float><signed-float>j | <float><sign>j */
779 x = z;
780 y = PyOS_string_to_double(s, &end, NULL);
781 if (y == -1.0 && PyErr_Occurred()) {
782 if (PyErr_ExceptionMatches(PyExc_ValueError))
783 PyErr_Clear();
784 else
Brett Cannona721aba2016-09-09 14:57:09 -0700785 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 }
787 if (end != s)
788 /* <float><signed-float>j */
789 s = end;
790 else {
791 /* <float><sign>j */
792 y = *s == '+' ? 1.0 : -1.0;
793 s++;
794 }
795 if (!(*s == 'j' || *s == 'J'))
796 goto parse_error;
797 s++;
798 }
799 else if (*s == 'j' || *s == 'J') {
800 /* <float>j */
801 s++;
802 y = z;
803 }
804 else
805 /* <float> */
806 x = z;
807 }
808 else {
809 /* not starting with <float>; must be <sign>j or j */
810 if (*s == '+' || *s == '-') {
811 /* <sign>j */
812 y = *s == '+' ? 1.0 : -1.0;
813 s++;
814 }
815 else
816 /* j */
817 y = 1.0;
818 if (!(*s == 'j' || *s == 'J'))
819 goto parse_error;
820 s++;
821 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 /* trailing whitespace and closing bracket */
824 while (Py_ISSPACE(*s))
825 s++;
826 if (got_bracket) {
827 /* if there was an opening parenthesis, then the corresponding
828 closing parenthesis should be right here */
829 if (*s != ')')
830 goto parse_error;
831 s++;
832 while (Py_ISSPACE(*s))
833 s++;
834 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 /* we should now be at the end of the string */
837 if (s-start != len)
838 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000839
Brett Cannona721aba2016-09-09 14:57:09 -0700840 return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000841
Mark Dickinson6649fa42009-04-24 13:25:20 +0000842 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 PyErr_SetString(PyExc_ValueError,
844 "complex() arg is a malformed string");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000846}
847
Tim Peters6d6c1a32001-08-02 04:15:00 +0000848static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700849complex_subtype_from_string(PyTypeObject *type, PyObject *v)
850{
851 const char *s;
852 PyObject *s_buffer = NULL, *result = NULL;
853 Py_ssize_t len;
854
855 if (PyUnicode_Check(v)) {
856 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
857 if (s_buffer == NULL) {
858 return NULL;
859 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200860 assert(PyUnicode_IS_ASCII(s_buffer));
861 /* Simply get a pointer to existing ASCII characters. */
Brett Cannona721aba2016-09-09 14:57:09 -0700862 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200863 assert(s != NULL);
Brett Cannona721aba2016-09-09 14:57:09 -0700864 }
865 else {
866 PyErr_Format(PyExc_TypeError,
867 "complex() argument must be a string or a number, not '%.200s'",
868 Py_TYPE(v)->tp_name);
869 return NULL;
870 }
871
872 result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
873 complex_from_string_inner);
Brett Cannona721aba2016-09-09 14:57:09 -0700874 Py_DECREF(s_buffer);
875 return result;
876}
877
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200878/*[clinic input]
879@classmethod
880complex.__new__ as complex_new
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100881 real as r: object(c_default="NULL") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200882 imag as i: object(c_default="NULL") = 0
883
884Create a complex number from a real part and an optional imaginary part.
885
886This is equivalent to (real + imag*1j) where imag defaults to 0.
887[clinic start generated code]*/
888
Brett Cannona721aba2016-09-09 14:57:09 -0700889static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200890complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100891/*[clinic end generated code: output=b6c7dd577b537dc1 input=f4c667f2596d4fd1]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000892{
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200893 PyObject *tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 PyNumberMethods *nbr, *nbi = NULL;
895 Py_complex cr, ci;
896 int own_r = 0;
897 int cr_is_complex = 0;
898 int ci_is_complex = 0;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000899
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100900 if (r == NULL) {
901 r = _PyLong_GetZero();
902 }
903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 /* Special-case for a single argument when type(arg) is complex. */
905 if (PyComplex_CheckExact(r) && i == NULL &&
906 type == &PyComplex_Type) {
907 /* Note that we can't know whether it's safe to return
908 a complex *subclass* instance as-is, hence the restriction
909 to exact complexes here. If either the input or the
910 output is a complex subclass, it will be handled below
911 as a non-orthogonal vector. */
912 Py_INCREF(r);
913 return r;
914 }
915 if (PyUnicode_Check(r)) {
916 if (i != NULL) {
917 PyErr_SetString(PyExc_TypeError,
918 "complex() can't take second arg"
919 " if first is a string");
920 return NULL;
921 }
922 return complex_subtype_from_string(type, r);
923 }
924 if (i != NULL && PyUnicode_Check(i)) {
925 PyErr_SetString(PyExc_TypeError,
926 "complex() second arg can't be a string");
927 return NULL;
928 }
Tim Peters2400fa42001-09-12 19:12:49 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 tmp = try_complex_special_method(r);
931 if (tmp) {
932 r = tmp;
933 own_r = 1;
934 }
935 else if (PyErr_Occurred()) {
936 return NULL;
937 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000938
Victor Stinner58ac7002020-02-07 03:04:21 +0100939 nbr = Py_TYPE(r)->tp_as_number;
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300940 if (nbr == NULL ||
941 (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
942 {
Ezio Melottia5b95992013-11-07 19:18:34 +0200943 PyErr_Format(PyExc_TypeError,
Mark Dickinson613f8e52016-09-24 15:26:36 +0100944 "complex() first argument must be a string or a number, "
945 "not '%.200s'",
946 Py_TYPE(r)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (own_r) {
948 Py_DECREF(r);
949 }
950 return NULL;
951 }
Mark Dickinson613f8e52016-09-24 15:26:36 +0100952 if (i != NULL) {
Victor Stinner58ac7002020-02-07 03:04:21 +0100953 nbi = Py_TYPE(i)->tp_as_number;
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +0300954 if (nbi == NULL ||
955 (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
956 {
Mark Dickinson613f8e52016-09-24 15:26:36 +0100957 PyErr_Format(PyExc_TypeError,
958 "complex() second argument must be a number, "
959 "not '%.200s'",
960 Py_TYPE(i)->tp_name);
961 if (own_r) {
962 Py_DECREF(r);
963 }
964 return NULL;
965 }
966 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* If we get this far, then the "real" and "imag" parts should
969 both be treated as numbers, and the constructor should return a
970 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 Note that we do NOT assume the input to already be in canonical
973 form; the "real" and "imag" parts might themselves be complex
974 numbers, which slightly complicates the code below. */
975 if (PyComplex_Check(r)) {
976 /* Note that if r is of a complex subtype, we're only
977 retaining its real & imag parts here, and the return
978 value is (properly) of the builtin complex type. */
979 cr = ((PyComplexObject*)r)->cval;
980 cr_is_complex = 1;
981 if (own_r) {
982 Py_DECREF(r);
983 }
984 }
985 else {
986 /* The "real" part really is entirely real, and contributes
987 nothing in the imaginary direction.
988 Just treat it as a double. */
989 tmp = PyNumber_Float(r);
990 if (own_r) {
991 /* r was a newly created complex number, rather
992 than the original "real" argument. */
993 Py_DECREF(r);
994 }
995 if (tmp == NULL)
996 return NULL;
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200997 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 cr.real = PyFloat_AsDouble(tmp);
Mark Dickinson112ec382017-02-20 20:28:15 +0000999 cr.imag = 0.0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 Py_DECREF(tmp);
1001 }
1002 if (i == NULL) {
Mark Dickinson112ec382017-02-20 20:28:15 +00001003 ci.real = cr.imag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 }
1005 else if (PyComplex_Check(i)) {
1006 ci = ((PyComplexObject*)i)->cval;
1007 ci_is_complex = 1;
1008 } else {
1009 /* The "imag" part really is entirely imaginary, and
1010 contributes nothing in the real direction.
1011 Just treat it as a double. */
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001012 tmp = PyNumber_Float(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (tmp == NULL)
1014 return NULL;
1015 ci.real = PyFloat_AsDouble(tmp);
1016 Py_DECREF(tmp);
1017 }
1018 /* If the input was in canonical form, then the "real" and "imag"
1019 parts are real numbers, so that ci.imag and cr.imag are zero.
1020 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (ci_is_complex) {
1023 cr.real -= ci.imag;
1024 }
Mark Dickinson112ec382017-02-20 20:28:15 +00001025 if (cr_is_complex && i != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 ci.real += cr.imag;
1027 }
1028 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001029}
1030
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001031static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 (binaryfunc)complex_add, /* nb_add */
1033 (binaryfunc)complex_sub, /* nb_subtract */
1034 (binaryfunc)complex_mul, /* nb_multiply */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001035 0, /* nb_remainder */
1036 0, /* nb_divmod */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 (ternaryfunc)complex_pow, /* nb_power */
1038 (unaryfunc)complex_neg, /* nb_negative */
1039 (unaryfunc)complex_pos, /* nb_positive */
1040 (unaryfunc)complex_abs, /* nb_absolute */
1041 (inquiry)complex_bool, /* nb_bool */
1042 0, /* nb_invert */
1043 0, /* nb_lshift */
1044 0, /* nb_rshift */
1045 0, /* nb_and */
1046 0, /* nb_xor */
1047 0, /* nb_or */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001048 0, /* nb_int */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 0, /* nb_reserved */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001050 0, /* nb_float */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 0, /* nb_inplace_add */
1052 0, /* nb_inplace_subtract */
1053 0, /* nb_inplace_multiply*/
1054 0, /* nb_inplace_remainder */
1055 0, /* nb_inplace_power */
1056 0, /* nb_inplace_lshift */
1057 0, /* nb_inplace_rshift */
1058 0, /* nb_inplace_and */
1059 0, /* nb_inplace_xor */
1060 0, /* nb_inplace_or */
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001061 0, /* nb_floor_divide */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 (binaryfunc)complex_div, /* nb_true_divide */
1063 0, /* nb_inplace_floor_divide */
1064 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001065};
1066
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001067PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1069 "complex",
1070 sizeof(PyComplexObject),
1071 0,
Inada Naoki7d408692019-05-29 17:23:27 +09001072 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001073 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 0, /* tp_getattr */
1075 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001076 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 (reprfunc)complex_repr, /* tp_repr */
1078 &complex_as_number, /* tp_as_number */
1079 0, /* tp_as_sequence */
1080 0, /* tp_as_mapping */
1081 (hashfunc)complex_hash, /* tp_hash */
1082 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001083 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyObject_GenericGetAttr, /* tp_getattro */
1085 0, /* tp_setattro */
1086 0, /* tp_as_buffer */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001087 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1088 complex_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 0, /* tp_traverse */
1090 0, /* tp_clear */
1091 complex_richcompare, /* tp_richcompare */
1092 0, /* tp_weaklistoffset */
1093 0, /* tp_iter */
1094 0, /* tp_iternext */
1095 complex_methods, /* tp_methods */
1096 complex_members, /* tp_members */
1097 0, /* tp_getset */
1098 0, /* tp_base */
1099 0, /* tp_dict */
1100 0, /* tp_descr_get */
1101 0, /* tp_descr_set */
1102 0, /* tp_dictoffset */
1103 0, /* tp_init */
1104 PyType_GenericAlloc, /* tp_alloc */
1105 complex_new, /* tp_new */
1106 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001107};