blob: a49037783be777561b013b2898f0965677f55d61 [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 Stinner4a21e572020-04-15 02:35:41 +02009#include "structmember.h" // PyMemberDef
Guido van Rossumf9fca921996-01-12 00:47:05 +000010
Serhiy Storchaka18b250f2017-03-19 08:51:07 +020011/*[clinic input]
12class complex "PyComplexObject *" "&PyComplex_Type"
13[clinic start generated code]*/
14/*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
15
16#include "clinic/complexobject.c.h"
17
Guido van Rossumf9fca921996-01-12 00:47:05 +000018/* elementary operations on complex numbers */
19
Guido van Rossum9e720e31996-07-21 02:31:35 +000020static Py_complex c_1 = {1., 0.};
Guido van Rossumf9fca921996-01-12 00:47:05 +000021
Tim Peters0f336042001-03-18 08:21:57 +000022Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040023_Py_c_sum(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 Py_complex r;
26 r.real = a.real + b.real;
27 r.imag = a.imag + b.imag;
28 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000029}
30
Tim Peters0f336042001-03-18 08:21:57 +000031Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040032_Py_c_diff(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 Py_complex r;
35 r.real = a.real - b.real;
36 r.imag = a.imag - b.imag;
37 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000038}
39
Tim Peters0f336042001-03-18 08:21:57 +000040Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040041_Py_c_neg(Py_complex a)
Guido van Rossumf9fca921996-01-12 00:47:05 +000042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 Py_complex r;
44 r.real = -a.real;
45 r.imag = -a.imag;
46 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000047}
48
Tim Peters0f336042001-03-18 08:21:57 +000049Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040050_Py_c_prod(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 Py_complex r;
53 r.real = a.real*b.real - a.imag*b.imag;
54 r.imag = a.real*b.imag + a.imag*b.real;
55 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +000056}
57
Paul Monsonff6bb0a2019-06-12 11:08:40 -070058/* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
59#ifdef _M_ARM64
60#pragma optimize("", off)
61#endif
Tim Peters0f336042001-03-18 08:21:57 +000062Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -040063_Py_c_quot(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +000064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 /******************************************************************
66 This was the original algorithm. It's grossly prone to spurious
67 overflow and underflow errors. It also merrily divides by 0 despite
68 checking for that(!). The code still serves a doc purpose here, as
69 the algorithm following is a simple by-cases transformation of this
70 one:
Tim Peters0f336042001-03-18 08:21:57 +000071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 Py_complex r;
73 double d = b.real*b.real + b.imag*b.imag;
74 if (d == 0.)
75 errno = EDOM;
76 r.real = (a.real*b.real + a.imag*b.imag)/d;
77 r.imag = (a.imag*b.real - a.real*b.imag)/d;
78 return r;
79 ******************************************************************/
Tim Peters0f336042001-03-18 08:21:57 +000080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 /* This algorithm is better, and is pretty obvious: first divide the
82 * numerators and denominator by whichever of {b.real, b.imag} has
83 * larger magnitude. The earliest reference I found was to CACM
84 * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
85 * University). As usual, though, we're still ignoring all IEEE
86 * endcases.
87 */
88 Py_complex r; /* the result */
89 const double abs_breal = b.real < 0 ? -b.real : b.real;
90 const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
Tim Peters0f336042001-03-18 08:21:57 +000091
Antoine Pitrou9086f922014-10-10 23:49:32 +020092 if (abs_breal >= abs_bimag) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 /* divide tops and bottom by b.real */
94 if (abs_breal == 0.0) {
95 errno = EDOM;
96 r.real = r.imag = 0.0;
97 }
98 else {
99 const double ratio = b.imag / b.real;
100 const double denom = b.real + b.imag * ratio;
101 r.real = (a.real + a.imag * ratio) / denom;
102 r.imag = (a.imag - a.real * ratio) / denom;
103 }
104 }
Antoine Pitrou9086f922014-10-10 23:49:32 +0200105 else if (abs_bimag >= abs_breal) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 /* divide tops and bottom by b.imag */
107 const double ratio = b.real / b.imag;
108 const double denom = b.real * ratio + b.imag;
109 assert(b.imag != 0.0);
110 r.real = (a.real * ratio + a.imag) / denom;
111 r.imag = (a.imag * ratio - a.real) / denom;
112 }
Antoine Pitrou9086f922014-10-10 23:49:32 +0200113 else {
114 /* At least one of b.real or b.imag is a NaN */
115 r.real = r.imag = Py_NAN;
116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000118}
Paul Monsonff6bb0a2019-06-12 11:08:40 -0700119#ifdef _M_ARM64
120#pragma optimize("", on)
121#endif
Guido van Rossumf9fca921996-01-12 00:47:05 +0000122
Tim Peters0f336042001-03-18 08:21:57 +0000123Py_complex
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400124_Py_c_pow(Py_complex a, Py_complex b)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 Py_complex r;
127 double vabs,len,at,phase;
128 if (b.real == 0. && b.imag == 0.) {
129 r.real = 1.;
130 r.imag = 0.;
131 }
132 else if (a.real == 0. && a.imag == 0.) {
133 if (b.imag != 0. || b.real < 0.)
134 errno = EDOM;
135 r.real = 0.;
136 r.imag = 0.;
137 }
138 else {
139 vabs = hypot(a.real,a.imag);
140 len = pow(vabs,b.real);
141 at = atan2(a.imag, a.real);
142 phase = at*b.real;
143 if (b.imag != 0.0) {
144 len /= exp(at*b.imag);
145 phase += b.imag*log(vabs);
146 }
147 r.real = len*cos(phase);
148 r.imag = len*sin(phase);
149 }
150 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000151}
152
Tim Peters0f336042001-03-18 08:21:57 +0000153static Py_complex
154c_powu(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 Py_complex r, p;
157 long mask = 1;
158 r = c_1;
159 p = x;
160 while (mask > 0 && n >= mask) {
161 if (n & mask)
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400162 r = _Py_c_prod(r,p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 mask <<= 1;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400164 p = _Py_c_prod(p,p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 }
166 return r;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000167}
168
Tim Peters0f336042001-03-18 08:21:57 +0000169static Py_complex
170c_powi(Py_complex x, long n)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 Py_complex cn;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (n > 100 || n < -100) {
175 cn.real = (double) n;
176 cn.imag = 0.;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400177 return _Py_c_pow(x,cn);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
179 else if (n > 0)
180 return c_powu(x,n);
181 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400182 return _Py_c_quot(c_1, c_powu(x,-n));
Guido van Rossumf9fca921996-01-12 00:47:05 +0000183
184}
185
Christian Heimes53876d92008-04-19 00:31:39 +0000186double
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400187_Py_c_abs(Py_complex z)
Christian Heimes53876d92008-04-19 00:31:39 +0000188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 /* sets errno = ERANGE on overflow; otherwise errno = 0 */
190 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
193 /* C99 rules: if either the real or the imaginary part is an
194 infinity, return infinity, even if the other part is a
195 NaN. */
196 if (Py_IS_INFINITY(z.real)) {
197 result = fabs(z.real);
198 errno = 0;
199 return result;
200 }
201 if (Py_IS_INFINITY(z.imag)) {
202 result = fabs(z.imag);
203 errno = 0;
204 return result;
205 }
206 /* either the real or imaginary part is a NaN,
207 and neither is infinite. Result should be NaN. */
208 return Py_NAN;
209 }
210 result = hypot(z.real, z.imag);
211 if (!Py_IS_FINITE(result))
212 errno = ERANGE;
213 else
214 errno = 0;
215 return result;
Christian Heimes53876d92008-04-19 00:31:39 +0000216}
217
Tim Peters6d6c1a32001-08-02 04:15:00 +0000218static PyObject *
219complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 PyObject *op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 op = type->tp_alloc(type, 0);
224 if (op != NULL)
225 ((PyComplexObject *)op)->cval = cval;
226 return op;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000227}
228
Guido van Rossumf9fca921996-01-12 00:47:05 +0000229PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000230PyComplex_FromCComplex(Py_complex cval)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000231{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200232 PyComplexObject *op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 /* Inline PyObject_New */
235 op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
236 if (op == NULL)
237 return PyErr_NoMemory();
Victor Stinnerb509d522018-11-23 14:27:38 +0100238 (void)PyObject_INIT(op, &PyComplex_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 op->cval = cval;
240 return (PyObject *) op;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000241}
242
Tim Peters6d6c1a32001-08-02 04:15:00 +0000243static PyObject *
244complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_complex c;
247 c.real = real;
248 c.imag = imag;
249 return complex_subtype_from_c_complex(type, c);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000250}
251
Guido van Rossumf9fca921996-01-12 00:47:05 +0000252PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000253PyComplex_FromDoubles(double real, double imag)
Guido van Rossum926518b1996-08-19 19:30:45 +0000254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 Py_complex c;
256 c.real = real;
257 c.imag = imag;
258 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000259}
260
261double
Fred Drake4288c802000-07-09 04:36:04 +0000262PyComplex_RealAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (PyComplex_Check(op)) {
265 return ((PyComplexObject *)op)->cval.real;
266 }
267 else {
268 return PyFloat_AsDouble(op);
269 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000270}
271
272double
Fred Drake4288c802000-07-09 04:36:04 +0000273PyComplex_ImagAsDouble(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (PyComplex_Check(op)) {
276 return ((PyComplexObject *)op)->cval.imag;
277 }
278 else {
279 return 0.0;
280 }
Guido van Rossumf9fca921996-01-12 00:47:05 +0000281}
282
Benjamin Petersonaea44282010-01-04 01:10:28 +0000283static PyObject *
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200284try_complex_special_method(PyObject *op)
285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 PyObject *f;
Benjamin Petersonce798522012-01-22 11:24:29 -0500287 _Py_IDENTIFIER(__complex__);
Benjamin Petersonaea44282010-01-04 01:10:28 +0000288
Benjamin Petersonce798522012-01-22 11:24:29 -0500289 f = _PyObject_LookupSpecial(op, &PyId___complex__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 if (f) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100291 PyObject *res = _PyObject_CallNoArg(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 Py_DECREF(f);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200293 if (!res || PyComplex_CheckExact(res)) {
294 return res;
295 }
296 if (!PyComplex_Check(res)) {
297 PyErr_Format(PyExc_TypeError,
298 "__complex__ returned non-complex (type %.200s)",
Victor Stinner58ac7002020-02-07 03:04:21 +0100299 Py_TYPE(res)->tp_name);
Serhiy Storchaka671079e2017-03-24 21:28:43 +0200300 Py_DECREF(res);
301 return NULL;
302 }
303 /* Issue #29894: warn if 'res' not of exact type complex. */
304 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
305 "__complex__ returned non-complex (type %.200s). "
306 "The ability to return an instance of a strict subclass of complex "
307 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner58ac7002020-02-07 03:04:21 +0100308 Py_TYPE(res)->tp_name)) {
Mark Dickinsond20fb822012-11-14 17:08:31 +0000309 Py_DECREF(res);
310 return NULL;
311 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return res;
313 }
314 return NULL;
Benjamin Petersonaea44282010-01-04 01:10:28 +0000315}
316
Guido van Rossum9e720e31996-07-21 02:31:35 +0000317Py_complex
Fred Drake4288c802000-07-09 04:36:04 +0000318PyComplex_AsCComplex(PyObject *op)
Guido van Rossum926518b1996-08-19 19:30:45 +0000319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 Py_complex cv;
321 PyObject *newop = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 assert(op);
324 /* If op is already of type PyComplex_Type, return its value */
325 if (PyComplex_Check(op)) {
326 return ((PyComplexObject *)op)->cval;
327 }
328 /* If not, use op's __complex__ method, if it exists */
Guido van Rossumd8faa362007-04-27 19:54:29 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 /* return -1 on failure */
331 cv.real = -1.;
332 cv.imag = 0.;
333
334 newop = try_complex_special_method(op);
335
336 if (newop) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 cv = ((PyComplexObject *)newop)->cval;
338 Py_DECREF(newop);
339 return cv;
340 }
341 else if (PyErr_Occurred()) {
342 return cv;
343 }
344 /* If neither of the above works, interpret op as a float giving the
345 real part of the result, and fill in the imaginary part as 0. */
346 else {
347 /* PyFloat_AsDouble will return -1 on failure */
348 cv.real = PyFloat_AsDouble(op);
349 return cv;
350 }
Guido van Rossumcf3d1081996-01-12 01:21:14 +0000351}
352
Eric Smith0923d1d2009-04-16 20:16:10 +0000353static PyObject *
Eric Smith70099a12010-12-04 13:27:34 +0000354complex_repr(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000355{
Eric Smith70099a12010-12-04 13:27:34 +0000356 int precision = 0;
357 char format_code = 'r';
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 PyObject *result = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 /* If these are non-NULL, they'll need to be freed. */
361 char *pre = NULL;
362 char *im = NULL;
Eric Smith0923d1d2009-04-16 20:16:10 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 /* These do not need to be freed. re is either an alias
365 for pre or a pointer to a constant. lead and tail
366 are pointers to constants. */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +0200367 const char *re = NULL;
368 const char *lead = "";
369 const char *tail = "";
Eric Smith0923d1d2009-04-16 20:16:10 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
Eric Smith70099a12010-12-04 13:27:34 +0000372 /* Real part is +0: just output the imaginary part and do not
373 include parens. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 re = "";
375 im = PyOS_double_to_string(v->cval.imag, format_code,
376 precision, 0, NULL);
377 if (!im) {
378 PyErr_NoMemory();
379 goto done;
380 }
381 } else {
Eric Smith70099a12010-12-04 13:27:34 +0000382 /* Format imaginary part with sign, real part without. Include
383 parens in the result. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 pre = PyOS_double_to_string(v->cval.real, format_code,
385 precision, 0, NULL);
386 if (!pre) {
387 PyErr_NoMemory();
388 goto done;
389 }
390 re = pre;
Eric Smith0923d1d2009-04-16 20:16:10 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 im = PyOS_double_to_string(v->cval.imag, format_code,
393 precision, Py_DTSF_SIGN, NULL);
394 if (!im) {
395 PyErr_NoMemory();
396 goto done;
397 }
398 lead = "(";
399 tail = ")";
400 }
Victor Stinner6ced7c42011-03-21 18:15:42 +0100401 result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000402 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 PyMem_Free(im);
404 PyMem_Free(pre);
Eric Smith0923d1d2009-04-16 20:16:10 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return result;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000407}
408
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000409static Py_hash_t
Fred Drake4288c802000-07-09 04:36:04 +0000410complex_hash(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000411{
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000412 Py_uhash_t hashreal, hashimag, combined;
413 hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real);
414 if (hashreal == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 return -1;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000416 hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag);
417 if (hashimag == (Py_uhash_t)-1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 return -1;
419 /* Note: if the imaginary part is 0, hashimag is 0 now,
420 * so the following returns hashreal unchanged. This is
421 * important because numbers of different types that
422 * compare equal must have the same hash value, so that
423 * hash(x + 0*j) must equal hash(x).
424 */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000425 combined = hashreal + _PyHASH_IMAG * hashimag;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000426 if (combined == (Py_uhash_t)-1)
427 combined = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000428 return (Py_hash_t)combined;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000429}
430
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000431/* This macro may return! */
432#define TO_COMPLEX(obj, c) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 if (PyComplex_Check(obj)) \
434 c = ((PyComplexObject *)(obj))->cval; \
435 else if (to_complex(&(obj), &(c)) < 0) \
436 return (obj)
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000437
438static int
439to_complex(PyObject **pobj, Py_complex *pc)
440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PyObject *obj = *pobj;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 pc->real = pc->imag = 0.0;
444 if (PyLong_Check(obj)) {
445 pc->real = PyLong_AsDouble(obj);
446 if (pc->real == -1.0 && PyErr_Occurred()) {
447 *pobj = NULL;
448 return -1;
449 }
450 return 0;
451 }
452 if (PyFloat_Check(obj)) {
453 pc->real = PyFloat_AsDouble(obj);
454 return 0;
455 }
456 Py_INCREF(Py_NotImplemented);
457 *pobj = Py_NotImplemented;
458 return -1;
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000459}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000461
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000463complex_add(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 Py_complex result;
466 Py_complex a, b;
467 TO_COMPLEX(v, a);
468 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400469 result = _Py_c_sum(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000471}
472
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000474complex_sub(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_complex result;
477 Py_complex a, b;
478 TO_COMPLEX(v, a);
479 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400480 result = _Py_c_diff(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000482}
483
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000485complex_mul(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 Py_complex result;
488 Py_complex a, b;
489 TO_COMPLEX(v, a);
490 TO_COMPLEX(w, b);
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400491 result = _Py_c_prod(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return PyComplex_FromCComplex(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000493}
494
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000495static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000496complex_div(PyObject *v, PyObject *w)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 Py_complex quot;
499 Py_complex a, b;
500 TO_COMPLEX(v, a);
501 TO_COMPLEX(w, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 errno = 0;
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400503 quot = _Py_c_quot(a, b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (errno == EDOM) {
505 PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
506 return NULL;
507 }
508 return PyComplex_FromCComplex(quot);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000509}
510
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000512complex_remainder(PyObject *v, PyObject *w)
Guido van Rossumee09fc11996-09-11 13:55:55 +0000513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 PyErr_SetString(PyExc_TypeError,
515 "can't mod complex numbers.");
516 return NULL;
Guido van Rossumee09fc11996-09-11 13:55:55 +0000517}
518
Guido van Rossumee09fc11996-09-11 13:55:55 +0000519
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000520static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000521complex_divmod(PyObject *v, PyObject *w)
Guido van Rossum3be12e91996-09-12 20:56:18 +0000522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 PyErr_SetString(PyExc_TypeError,
524 "can't take floor or mod of complex number.");
525 return NULL;
Guido van Rossum3be12e91996-09-12 20:56:18 +0000526}
Guido van Rossumf9fca921996-01-12 00:47:05 +0000527
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000529complex_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 Py_complex p;
532 Py_complex exponent;
533 long int_exponent;
534 Py_complex a, b;
535 TO_COMPLEX(v, a);
536 TO_COMPLEX(w, b);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (z != Py_None) {
539 PyErr_SetString(PyExc_ValueError, "complex modulo");
540 return NULL;
541 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 errno = 0;
543 exponent = b;
544 int_exponent = (long)exponent.real;
545 if (exponent.imag == 0. && exponent.real == int_exponent)
546 p = c_powi(a, int_exponent);
547 else
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400548 p = _Py_c_pow(a, exponent);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 Py_ADJUST_ERANGE2(p.real, p.imag);
551 if (errno == EDOM) {
552 PyErr_SetString(PyExc_ZeroDivisionError,
553 "0.0 to a negative or complex power");
554 return NULL;
555 }
556 else if (errno == ERANGE) {
557 PyErr_SetString(PyExc_OverflowError,
558 "complex exponentiation");
559 return NULL;
560 }
561 return PyComplex_FromCComplex(p);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000562}
563
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564static PyObject *
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +0000565complex_int_div(PyObject *v, PyObject *w)
Guido van Rossum4668b002001-08-08 05:00:18 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyErr_SetString(PyExc_TypeError,
568 "can't take floor of complex number.");
569 return NULL;
Guido van Rossum4668b002001-08-08 05:00:18 +0000570}
571
572static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000573complex_neg(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 Py_complex neg;
576 neg.real = -v->cval.real;
577 neg.imag = -v->cval.imag;
578 return PyComplex_FromCComplex(neg);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000579}
580
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000581static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000582complex_pos(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (PyComplex_CheckExact(v)) {
585 Py_INCREF(v);
586 return (PyObject *)v;
587 }
588 else
589 return PyComplex_FromCComplex(v->cval);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000590}
591
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000592static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000593complex_abs(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 double result;
Christian Heimes53876d92008-04-19 00:31:39 +0000596
Antoine Pitrou1eee8e52014-07-07 18:49:30 -0400597 result = _Py_c_abs(v->cval);
Christian Heimes53876d92008-04-19 00:31:39 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (errno == ERANGE) {
600 PyErr_SetString(PyExc_OverflowError,
601 "absolute value too large");
602 return NULL;
603 }
604 return PyFloat_FromDouble(result);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000605}
606
607static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000608complex_bool(PyComplexObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return v->cval.real != 0.0 || v->cval.imag != 0.0;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000611}
612
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613static PyObject *
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000614complex_richcompare(PyObject *v, PyObject *w, int op)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 PyObject *res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000617 Py_complex i;
618 int equal;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (op != Py_EQ && op != Py_NE) {
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000621 goto Unimplemented;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 }
Guido van Rossum22056422001-09-24 17:52:04 +0000623
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000624 assert(PyComplex_Check(v));
625 TO_COMPLEX(v, i);
626
627 if (PyLong_Check(w)) {
628 /* Check for 0.0 imaginary part first to avoid the rich
629 * comparison when possible.
630 */
631 if (i.imag == 0.0) {
632 PyObject *j, *sub_res;
633 j = PyFloat_FromDouble(i.real);
634 if (j == NULL)
635 return NULL;
636
637 sub_res = PyObject_RichCompare(j, w, op);
638 Py_DECREF(j);
639 return sub_res;
640 }
641 else {
642 equal = 0;
643 }
644 }
645 else if (PyFloat_Check(w)) {
646 equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
647 }
648 else if (PyComplex_Check(w)) {
649 Py_complex j;
650
651 TO_COMPLEX(w, j);
652 equal = (i.real == j.real && i.imag == j.imag);
653 }
654 else {
655 goto Unimplemented;
656 }
657
658 if (equal == (op == Py_EQ))
659 res = Py_True;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 else
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000661 res = Py_False;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 Py_INCREF(res);
664 return res;
Mark Dickinsoncc6a9822010-05-21 14:55:26 +0000665
666Unimplemented:
Brian Curtindfc80e32011-08-10 20:28:54 -0500667 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossumbe4cbb12001-01-18 01:12:39 +0000668}
669
670static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000671complex_int(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyErr_SetString(PyExc_TypeError,
674 "can't convert complex to int");
675 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000676}
677
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000678static PyObject *
Fred Drake4288c802000-07-09 04:36:04 +0000679complex_float(PyObject *v)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 PyErr_SetString(PyExc_TypeError,
682 "can't convert complex to float");
683 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000684}
685
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530687complex_conjugate(PyObject *self, PyObject *Py_UNUSED(ignored))
Guido van Rossumf9fca921996-01-12 00:47:05 +0000688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 Py_complex c;
690 c = ((PyComplexObject *)self)->cval;
691 c.imag = -c.imag;
692 return PyComplex_FromCComplex(c);
Guido van Rossumf9fca921996-01-12 00:47:05 +0000693}
694
Guido van Rossum46334cd2007-08-01 17:43:15 +0000695PyDoc_STRVAR(complex_conjugate_doc,
696"complex.conjugate() -> complex\n"
697"\n"
Ezio Melotti488d2442013-10-06 00:39:18 +0300698"Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
Guido van Rossum46334cd2007-08-01 17:43:15 +0000699
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000700static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530701complex_getnewargs(PyComplexObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 Py_complex c = v->cval;
704 return Py_BuildValue("(dd)", c.real, c.imag);
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000705}
706
Eric Smith58a42242009-04-30 01:00:33 +0000707PyDoc_STRVAR(complex__format__doc,
708"complex.__format__() -> str\n"
709"\n"
Ezio Melotti488d2442013-10-06 00:39:18 +0300710"Convert to a string according to format_spec.");
Eric Smith58a42242009-04-30 01:00:33 +0000711
712static PyObject *
713complex__format__(PyObject* self, PyObject* args)
714{
715 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +0200716 _PyUnicodeWriter writer;
717 int ret;
Eric Smith58a42242009-04-30 01:00:33 +0000718
719 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
Victor Stinnerd3f08822012-05-29 12:57:52 +0200720 return NULL;
721
Victor Stinner8f674cc2013-04-17 23:02:17 +0200722 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +0200723 ret = _PyComplex_FormatAdvancedWriter(
724 &writer,
725 self,
726 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
727 if (ret == -1) {
728 _PyUnicodeWriter_Dealloc(&writer);
729 return NULL;
730 }
731 return _PyUnicodeWriter_Finish(&writer);
Eric Smith58a42242009-04-30 01:00:33 +0000732}
733
Guido van Rossumf9fca921996-01-12 00:47:05 +0000734static PyMethodDef complex_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
736 complex_conjugate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
738 {"__format__", (PyCFunction)complex__format__,
739 METH_VARARGS, complex__format__doc},
740 {NULL, NULL} /* sentinel */
Guido van Rossumf9fca921996-01-12 00:47:05 +0000741};
742
Guido van Rossum6f799372001-09-20 20:46:19 +0000743static PyMemberDef complex_members[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
745 "the real part of a complex number"},
746 {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
747 "the imaginary part of a complex number"},
748 {0},
Tim Peters6d6c1a32001-08-02 04:15:00 +0000749};
Guido van Rossumf9fca921996-01-12 00:47:05 +0000750
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000751static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700752complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
Guido van Rossumf9fca921996-01-12 00:47:05 +0000753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 double x=0.0, y=0.0, z;
755 int got_bracket=0;
Brett Cannona721aba2016-09-09 14:57:09 -0700756 const char *start;
757 char *end;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* position on first nonblank */
760 start = s;
761 while (Py_ISSPACE(*s))
762 s++;
763 if (*s == '(') {
764 /* Skip over possible bracket from repr(). */
765 got_bracket = 1;
766 s++;
767 while (Py_ISSPACE(*s))
768 s++;
769 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 /* a valid complex string usually takes one of the three forms:
Mark Dickinson6649fa42009-04-24 13:25:20 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 <float> - real part only
774 <float>j - imaginary part only
775 <float><signed-float>j - real and imaginary parts
Mark Dickinson6649fa42009-04-24 13:25:20 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 where <float> represents any numeric string that's accepted by the
778 float constructor (including 'nan', 'inf', 'infinity', etc.), and
779 <signed-float> is any string of the form <float> whose first
780 character is '+' or '-'.
Mark Dickinson6649fa42009-04-24 13:25:20 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 For backwards compatibility, the extra forms
Mark Dickinson6649fa42009-04-24 13:25:20 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 <float><sign>j
785 <sign>j
786 j
Mark Dickinson6649fa42009-04-24 13:25:20 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 are also accepted, though support for these forms may be removed from
789 a future version of Python.
790 */
Mark Dickinson6649fa42009-04-24 13:25:20 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 /* first look for forms starting with <float> */
793 z = PyOS_string_to_double(s, &end, NULL);
794 if (z == -1.0 && PyErr_Occurred()) {
795 if (PyErr_ExceptionMatches(PyExc_ValueError))
796 PyErr_Clear();
797 else
Brett Cannona721aba2016-09-09 14:57:09 -0700798 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 }
800 if (end != s) {
801 /* all 4 forms starting with <float> land here */
802 s = end;
803 if (*s == '+' || *s == '-') {
804 /* <float><signed-float>j | <float><sign>j */
805 x = z;
806 y = PyOS_string_to_double(s, &end, NULL);
807 if (y == -1.0 && PyErr_Occurred()) {
808 if (PyErr_ExceptionMatches(PyExc_ValueError))
809 PyErr_Clear();
810 else
Brett Cannona721aba2016-09-09 14:57:09 -0700811 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
813 if (end != s)
814 /* <float><signed-float>j */
815 s = end;
816 else {
817 /* <float><sign>j */
818 y = *s == '+' ? 1.0 : -1.0;
819 s++;
820 }
821 if (!(*s == 'j' || *s == 'J'))
822 goto parse_error;
823 s++;
824 }
825 else if (*s == 'j' || *s == 'J') {
826 /* <float>j */
827 s++;
828 y = z;
829 }
830 else
831 /* <float> */
832 x = z;
833 }
834 else {
835 /* not starting with <float>; must be <sign>j or j */
836 if (*s == '+' || *s == '-') {
837 /* <sign>j */
838 y = *s == '+' ? 1.0 : -1.0;
839 s++;
840 }
841 else
842 /* j */
843 y = 1.0;
844 if (!(*s == 'j' || *s == 'J'))
845 goto parse_error;
846 s++;
847 }
Mark Dickinsonad476da2009-04-23 19:14:16 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 /* trailing whitespace and closing bracket */
850 while (Py_ISSPACE(*s))
851 s++;
852 if (got_bracket) {
853 /* if there was an opening parenthesis, then the corresponding
854 closing parenthesis should be right here */
855 if (*s != ')')
856 goto parse_error;
857 s++;
858 while (Py_ISSPACE(*s))
859 s++;
860 }
Mark Dickinson6649fa42009-04-24 13:25:20 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 /* we should now be at the end of the string */
863 if (s-start != len)
864 goto parse_error;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000865
Brett Cannona721aba2016-09-09 14:57:09 -0700866 return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
Mark Dickinsonad476da2009-04-23 19:14:16 +0000867
Mark Dickinson6649fa42009-04-24 13:25:20 +0000868 parse_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyErr_SetString(PyExc_ValueError,
870 "complex() arg is a malformed string");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 return NULL;
Guido van Rossumf9fca921996-01-12 00:47:05 +0000872}
873
Tim Peters6d6c1a32001-08-02 04:15:00 +0000874static PyObject *
Brett Cannona721aba2016-09-09 14:57:09 -0700875complex_subtype_from_string(PyTypeObject *type, PyObject *v)
876{
877 const char *s;
878 PyObject *s_buffer = NULL, *result = NULL;
879 Py_ssize_t len;
880
881 if (PyUnicode_Check(v)) {
882 s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
883 if (s_buffer == NULL) {
884 return NULL;
885 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200886 assert(PyUnicode_IS_ASCII(s_buffer));
887 /* Simply get a pointer to existing ASCII characters. */
Brett Cannona721aba2016-09-09 14:57:09 -0700888 s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +0200889 assert(s != NULL);
Brett Cannona721aba2016-09-09 14:57:09 -0700890 }
891 else {
892 PyErr_Format(PyExc_TypeError,
893 "complex() argument must be a string or a number, not '%.200s'",
894 Py_TYPE(v)->tp_name);
895 return NULL;
896 }
897
898 result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
899 complex_from_string_inner);
Brett Cannona721aba2016-09-09 14:57:09 -0700900 Py_DECREF(s_buffer);
901 return result;
902}
903
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200904/*[clinic input]
905@classmethod
906complex.__new__ as complex_new
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300907 real as r: object(c_default="_PyLong_Zero") = 0
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200908 imag as i: object(c_default="NULL") = 0
909
910Create a complex number from a real part and an optional imaginary part.
911
912This is equivalent to (real + imag*1j) where imag defaults to 0.
913[clinic start generated code]*/
914
Brett Cannona721aba2016-09-09 14:57:09 -0700915static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200916complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
Serhiy Storchakabae68812017-04-05 12:00:42 +0300917/*[clinic end generated code: output=b6c7dd577b537dc1 input=6f6b0bedba29bcb5]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +0000918{
Serhiy Storchaka18b250f2017-03-19 08:51:07 +0200919 PyObject *tmp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyNumberMethods *nbr, *nbi = NULL;
921 Py_complex cr, ci;
922 int own_r = 0;
923 int cr_is_complex = 0;
924 int ci_is_complex = 0;
Raymond Hettinger604cd6a2002-08-29 14:22:51 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* Special-case for a single argument when type(arg) is complex. */
927 if (PyComplex_CheckExact(r) && i == NULL &&
928 type == &PyComplex_Type) {
929 /* Note that we can't know whether it's safe to return
930 a complex *subclass* instance as-is, hence the restriction
931 to exact complexes here. If either the input or the
932 output is a complex subclass, it will be handled below
933 as a non-orthogonal vector. */
934 Py_INCREF(r);
935 return r;
936 }
937 if (PyUnicode_Check(r)) {
938 if (i != NULL) {
939 PyErr_SetString(PyExc_TypeError,
940 "complex() can't take second arg"
941 " if first is a string");
942 return NULL;
943 }
944 return complex_subtype_from_string(type, r);
945 }
946 if (i != NULL && PyUnicode_Check(i)) {
947 PyErr_SetString(PyExc_TypeError,
948 "complex() second arg can't be a string");
949 return NULL;
950 }
Tim Peters2400fa42001-09-12 19:12:49 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 tmp = try_complex_special_method(r);
953 if (tmp) {
954 r = tmp;
955 own_r = 1;
956 }
957 else if (PyErr_Occurred()) {
958 return NULL;
959 }
Benjamin Petersonaea44282010-01-04 01:10:28 +0000960
Victor Stinner58ac7002020-02-07 03:04:21 +0100961 nbr = Py_TYPE(r)->tp_as_number;
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300962 if (nbr == NULL || (nbr->nb_float == NULL && nbr->nb_index == NULL)) {
Ezio Melottia5b95992013-11-07 19:18:34 +0200963 PyErr_Format(PyExc_TypeError,
Mark Dickinson613f8e52016-09-24 15:26:36 +0100964 "complex() first argument must be a string or a number, "
965 "not '%.200s'",
966 Py_TYPE(r)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 if (own_r) {
968 Py_DECREF(r);
969 }
970 return NULL;
971 }
Mark Dickinson613f8e52016-09-24 15:26:36 +0100972 if (i != NULL) {
Victor Stinner58ac7002020-02-07 03:04:21 +0100973 nbi = Py_TYPE(i)->tp_as_number;
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300974 if (nbi == NULL || (nbi->nb_float == NULL && nbi->nb_index == NULL)) {
Mark Dickinson613f8e52016-09-24 15:26:36 +0100975 PyErr_Format(PyExc_TypeError,
976 "complex() second argument must be a number, "
977 "not '%.200s'",
978 Py_TYPE(i)->tp_name);
979 if (own_r) {
980 Py_DECREF(r);
981 }
982 return NULL;
983 }
984 }
Guido van Rossumd8faa362007-04-27 19:54:29 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* If we get this far, then the "real" and "imag" parts should
987 both be treated as numbers, and the constructor should return a
988 complex number equal to (real + imag*1j).
Guido van Rossumd8faa362007-04-27 19:54:29 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 Note that we do NOT assume the input to already be in canonical
991 form; the "real" and "imag" parts might themselves be complex
992 numbers, which slightly complicates the code below. */
993 if (PyComplex_Check(r)) {
994 /* Note that if r is of a complex subtype, we're only
995 retaining its real & imag parts here, and the return
996 value is (properly) of the builtin complex type. */
997 cr = ((PyComplexObject*)r)->cval;
998 cr_is_complex = 1;
999 if (own_r) {
1000 Py_DECREF(r);
1001 }
1002 }
1003 else {
1004 /* The "real" part really is entirely real, and contributes
1005 nothing in the imaginary direction.
1006 Just treat it as a double. */
1007 tmp = PyNumber_Float(r);
1008 if (own_r) {
1009 /* r was a newly created complex number, rather
1010 than the original "real" argument. */
1011 Py_DECREF(r);
1012 }
1013 if (tmp == NULL)
1014 return NULL;
Serhiy Storchaka671079e2017-03-24 21:28:43 +02001015 assert(PyFloat_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 cr.real = PyFloat_AsDouble(tmp);
Mark Dickinson112ec382017-02-20 20:28:15 +00001017 cr.imag = 0.0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 Py_DECREF(tmp);
1019 }
1020 if (i == NULL) {
Mark Dickinson112ec382017-02-20 20:28:15 +00001021 ci.real = cr.imag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 }
1023 else if (PyComplex_Check(i)) {
1024 ci = ((PyComplexObject*)i)->cval;
1025 ci_is_complex = 1;
1026 } else {
1027 /* The "imag" part really is entirely imaginary, and
1028 contributes nothing in the real direction.
1029 Just treat it as a double. */
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001030 tmp = PyNumber_Float(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (tmp == NULL)
1032 return NULL;
1033 ci.real = PyFloat_AsDouble(tmp);
1034 Py_DECREF(tmp);
1035 }
1036 /* If the input was in canonical form, then the "real" and "imag"
1037 parts are real numbers, so that ci.imag and cr.imag are zero.
1038 We need this correction in case they were not real numbers. */
Christian Heimes69a79632007-11-28 10:04:30 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 if (ci_is_complex) {
1041 cr.real -= ci.imag;
1042 }
Mark Dickinson112ec382017-02-20 20:28:15 +00001043 if (cr_is_complex && i != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 ci.real += cr.imag;
1045 }
1046 return complex_subtype_from_doubles(type, cr.real, ci.real);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001047}
1048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001049static PyNumberMethods complex_as_number = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 (binaryfunc)complex_add, /* nb_add */
1051 (binaryfunc)complex_sub, /* nb_subtract */
1052 (binaryfunc)complex_mul, /* nb_multiply */
1053 (binaryfunc)complex_remainder, /* nb_remainder */
1054 (binaryfunc)complex_divmod, /* nb_divmod */
1055 (ternaryfunc)complex_pow, /* nb_power */
1056 (unaryfunc)complex_neg, /* nb_negative */
1057 (unaryfunc)complex_pos, /* nb_positive */
1058 (unaryfunc)complex_abs, /* nb_absolute */
1059 (inquiry)complex_bool, /* nb_bool */
1060 0, /* nb_invert */
1061 0, /* nb_lshift */
1062 0, /* nb_rshift */
1063 0, /* nb_and */
1064 0, /* nb_xor */
1065 0, /* nb_or */
1066 complex_int, /* nb_int */
1067 0, /* nb_reserved */
1068 complex_float, /* nb_float */
1069 0, /* nb_inplace_add */
1070 0, /* nb_inplace_subtract */
1071 0, /* nb_inplace_multiply*/
1072 0, /* nb_inplace_remainder */
1073 0, /* nb_inplace_power */
1074 0, /* nb_inplace_lshift */
1075 0, /* nb_inplace_rshift */
1076 0, /* nb_inplace_and */
1077 0, /* nb_inplace_xor */
1078 0, /* nb_inplace_or */
1079 (binaryfunc)complex_int_div, /* nb_floor_divide */
1080 (binaryfunc)complex_div, /* nb_true_divide */
1081 0, /* nb_inplace_floor_divide */
1082 0, /* nb_inplace_true_divide */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001083};
1084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085PyTypeObject PyComplex_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1087 "complex",
1088 sizeof(PyComplexObject),
1089 0,
Inada Naoki7d408692019-05-29 17:23:27 +09001090 0, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001091 0, /* tp_vectorcall_offset */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 0, /* tp_getattr */
1093 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +02001094 0, /* tp_as_async */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 (reprfunc)complex_repr, /* tp_repr */
1096 &complex_as_number, /* tp_as_number */
1097 0, /* tp_as_sequence */
1098 0, /* tp_as_mapping */
1099 (hashfunc)complex_hash, /* tp_hash */
1100 0, /* tp_call */
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001101 0, /* tp_str */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyObject_GenericGetAttr, /* tp_getattro */
1103 0, /* tp_setattro */
1104 0, /* tp_as_buffer */
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02001105 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1106 complex_new__doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 0, /* tp_traverse */
1108 0, /* tp_clear */
1109 complex_richcompare, /* tp_richcompare */
1110 0, /* tp_weaklistoffset */
1111 0, /* tp_iter */
1112 0, /* tp_iternext */
1113 complex_methods, /* tp_methods */
1114 complex_members, /* tp_members */
1115 0, /* tp_getset */
1116 0, /* tp_base */
1117 0, /* tp_dict */
1118 0, /* tp_descr_get */
1119 0, /* tp_descr_set */
1120 0, /* tp_dictoffset */
1121 0, /* tp_init */
1122 PyType_GenericAlloc, /* tp_alloc */
1123 complex_new, /* tp_new */
1124 PyObject_Del, /* tp_free */
Guido van Rossumf9fca921996-01-12 00:47:05 +00001125};