Branch data Line data Source code
1 : :
2 : : /* Complex object implementation */
3 : :
4 : : /* Borrows heavily from floatobject.c */
5 : :
6 : : /* Submitted by Jim Hugunin */
7 : :
8 : : #include "Python.h"
9 : : #include "pycore_call.h" // _PyObject_CallNoArgs()
10 : : #include "pycore_long.h" // _PyLong_GetZero()
11 : : #include "pycore_object.h" // _PyObject_Init()
12 : : #include "pycore_pymath.h" // _Py_ADJUST_ERANGE2()
13 : : #include "structmember.h" // PyMemberDef
14 : :
15 : :
16 : : /*[clinic input]
17 : : class complex "PyComplexObject *" "&PyComplex_Type"
18 : : [clinic start generated code]*/
19 : : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=819e057d2d10f5ec]*/
20 : :
21 : : #include "clinic/complexobject.c.h"
22 : :
23 : : /* elementary operations on complex numbers */
24 : :
25 : : static Py_complex c_1 = {1., 0.};
26 : :
27 : : Py_complex
28 : 2 : _Py_c_sum(Py_complex a, Py_complex b)
29 : : {
30 : : Py_complex r;
31 : 2 : r.real = a.real + b.real;
32 : 2 : r.imag = a.imag + b.imag;
33 : 2 : return r;
34 : : }
35 : :
36 : : Py_complex
37 : 0 : _Py_c_diff(Py_complex a, Py_complex b)
38 : : {
39 : : Py_complex r;
40 : 0 : r.real = a.real - b.real;
41 : 0 : r.imag = a.imag - b.imag;
42 : 0 : return r;
43 : : }
44 : :
45 : : Py_complex
46 : 0 : _Py_c_neg(Py_complex a)
47 : : {
48 : : Py_complex r;
49 : 0 : r.real = -a.real;
50 : 0 : r.imag = -a.imag;
51 : 0 : return r;
52 : : }
53 : :
54 : : Py_complex
55 : 0 : _Py_c_prod(Py_complex a, Py_complex b)
56 : : {
57 : : Py_complex r;
58 : 0 : r.real = a.real*b.real - a.imag*b.imag;
59 : 0 : r.imag = a.real*b.imag + a.imag*b.real;
60 : 0 : return r;
61 : : }
62 : :
63 : : /* Avoid bad optimization on Windows ARM64 until the compiler is fixed */
64 : : #ifdef _M_ARM64
65 : : #pragma optimize("", off)
66 : : #endif
67 : : Py_complex
68 : 0 : _Py_c_quot(Py_complex a, Py_complex b)
69 : : {
70 : : /******************************************************************
71 : : This was the original algorithm. It's grossly prone to spurious
72 : : overflow and underflow errors. It also merrily divides by 0 despite
73 : : checking for that(!). The code still serves a doc purpose here, as
74 : : the algorithm following is a simple by-cases transformation of this
75 : : one:
76 : :
77 : : Py_complex r;
78 : : double d = b.real*b.real + b.imag*b.imag;
79 : : if (d == 0.)
80 : : errno = EDOM;
81 : : r.real = (a.real*b.real + a.imag*b.imag)/d;
82 : : r.imag = (a.imag*b.real - a.real*b.imag)/d;
83 : : return r;
84 : : ******************************************************************/
85 : :
86 : : /* This algorithm is better, and is pretty obvious: first divide the
87 : : * numerators and denominator by whichever of {b.real, b.imag} has
88 : : * larger magnitude. The earliest reference I found was to CACM
89 : : * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
90 : : * University). As usual, though, we're still ignoring all IEEE
91 : : * endcases.
92 : : */
93 : : Py_complex r; /* the result */
94 [ # # ]: 0 : const double abs_breal = b.real < 0 ? -b.real : b.real;
95 [ # # ]: 0 : const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
96 : :
97 [ # # ]: 0 : if (abs_breal >= abs_bimag) {
98 : : /* divide tops and bottom by b.real */
99 [ # # ]: 0 : if (abs_breal == 0.0) {
100 : 0 : errno = EDOM;
101 : 0 : r.real = r.imag = 0.0;
102 : : }
103 : : else {
104 : 0 : const double ratio = b.imag / b.real;
105 : 0 : const double denom = b.real + b.imag * ratio;
106 : 0 : r.real = (a.real + a.imag * ratio) / denom;
107 : 0 : r.imag = (a.imag - a.real * ratio) / denom;
108 : : }
109 : : }
110 [ # # ]: 0 : else if (abs_bimag >= abs_breal) {
111 : : /* divide tops and bottom by b.imag */
112 : 0 : const double ratio = b.real / b.imag;
113 : 0 : const double denom = b.real * ratio + b.imag;
114 : : assert(b.imag != 0.0);
115 : 0 : r.real = (a.real * ratio + a.imag) / denom;
116 : 0 : r.imag = (a.imag * ratio - a.real) / denom;
117 : : }
118 : : else {
119 : : /* At least one of b.real or b.imag is a NaN */
120 : 0 : r.real = r.imag = Py_NAN;
121 : : }
122 : 0 : return r;
123 : : }
124 : : #ifdef _M_ARM64
125 : : #pragma optimize("", on)
126 : : #endif
127 : :
128 : : Py_complex
129 : 0 : _Py_c_pow(Py_complex a, Py_complex b)
130 : : {
131 : : Py_complex r;
132 : : double vabs,len,at,phase;
133 [ # # # # ]: 0 : if (b.real == 0. && b.imag == 0.) {
134 : 0 : r.real = 1.;
135 : 0 : r.imag = 0.;
136 : : }
137 [ # # # # ]: 0 : else if (a.real == 0. && a.imag == 0.) {
138 [ # # # # ]: 0 : if (b.imag != 0. || b.real < 0.)
139 : 0 : errno = EDOM;
140 : 0 : r.real = 0.;
141 : 0 : r.imag = 0.;
142 : : }
143 : : else {
144 : 0 : vabs = hypot(a.real,a.imag);
145 : 0 : len = pow(vabs,b.real);
146 : 0 : at = atan2(a.imag, a.real);
147 : 0 : phase = at*b.real;
148 [ # # ]: 0 : if (b.imag != 0.0) {
149 : 0 : len /= exp(at*b.imag);
150 : 0 : phase += b.imag*log(vabs);
151 : : }
152 : 0 : r.real = len*cos(phase);
153 : 0 : r.imag = len*sin(phase);
154 : : }
155 : 0 : return r;
156 : : }
157 : :
158 : : static Py_complex
159 : 0 : c_powu(Py_complex x, long n)
160 : : {
161 : : Py_complex r, p;
162 : 0 : long mask = 1;
163 : 0 : r = c_1;
164 : 0 : p = x;
165 [ # # # # ]: 0 : while (mask > 0 && n >= mask) {
166 [ # # ]: 0 : if (n & mask)
167 : 0 : r = _Py_c_prod(r,p);
168 : 0 : mask <<= 1;
169 : 0 : p = _Py_c_prod(p,p);
170 : : }
171 : 0 : return r;
172 : : }
173 : :
174 : : static Py_complex
175 : 0 : c_powi(Py_complex x, long n)
176 : : {
177 [ # # ]: 0 : if (n > 0)
178 : 0 : return c_powu(x,n);
179 : : else
180 : 0 : return _Py_c_quot(c_1, c_powu(x,-n));
181 : :
182 : : }
183 : :
184 : : double
185 : 0 : _Py_c_abs(Py_complex z)
186 : : {
187 : : /* sets errno = ERANGE on overflow; otherwise errno = 0 */
188 : : double result;
189 : :
190 [ # # # # ]: 0 : if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
191 : : /* C99 rules: if either the real or the imaginary part is an
192 : : infinity, return infinity, even if the other part is a
193 : : NaN. */
194 [ # # # # ]: 0 : if (Py_IS_INFINITY(z.real)) {
195 : 0 : result = fabs(z.real);
196 : 0 : errno = 0;
197 : 0 : return result;
198 : : }
199 [ # # # # ]: 0 : if (Py_IS_INFINITY(z.imag)) {
200 : 0 : result = fabs(z.imag);
201 : 0 : errno = 0;
202 : 0 : return result;
203 : : }
204 : : /* either the real or imaginary part is a NaN,
205 : : and neither is infinite. Result should be NaN. */
206 : 0 : return Py_NAN;
207 : : }
208 : 0 : result = hypot(z.real, z.imag);
209 [ # # ]: 0 : if (!Py_IS_FINITE(result))
210 : 0 : errno = ERANGE;
211 : : else
212 : 0 : errno = 0;
213 : 0 : return result;
214 : : }
215 : :
216 : : static PyObject *
217 : 0 : complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
218 : : {
219 : : PyObject *op;
220 : :
221 : 0 : op = type->tp_alloc(type, 0);
222 [ # # ]: 0 : if (op != NULL)
223 : 0 : ((PyComplexObject *)op)->cval = cval;
224 : 0 : return op;
225 : : }
226 : :
227 : : PyObject *
228 : 10 : PyComplex_FromCComplex(Py_complex cval)
229 : : {
230 : : /* Inline PyObject_New */
231 : 10 : PyComplexObject *op = PyObject_Malloc(sizeof(PyComplexObject));
232 [ - + ]: 10 : if (op == NULL) {
233 : 0 : return PyErr_NoMemory();
234 : : }
235 : 10 : _PyObject_Init((PyObject*)op, &PyComplex_Type);
236 : 10 : op->cval = cval;
237 : 10 : return (PyObject *) op;
238 : : }
239 : :
240 : : static PyObject *
241 : 0 : complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
242 : : {
243 : : Py_complex c;
244 : 0 : c.real = real;
245 : 0 : c.imag = imag;
246 : 0 : return complex_subtype_from_c_complex(type, c);
247 : : }
248 : :
249 : : PyObject *
250 : 0 : PyComplex_FromDoubles(double real, double imag)
251 : : {
252 : : Py_complex c;
253 : 0 : c.real = real;
254 : 0 : c.imag = imag;
255 : 0 : return PyComplex_FromCComplex(c);
256 : : }
257 : :
258 : : double
259 : 3 : PyComplex_RealAsDouble(PyObject *op)
260 : : {
261 [ + - ]: 3 : if (PyComplex_Check(op)) {
262 : 3 : return ((PyComplexObject *)op)->cval.real;
263 : : }
264 : : else {
265 : 0 : return PyFloat_AsDouble(op);
266 : : }
267 : : }
268 : :
269 : : double
270 : 3 : PyComplex_ImagAsDouble(PyObject *op)
271 : : {
272 [ + - ]: 3 : if (PyComplex_Check(op)) {
273 : 3 : return ((PyComplexObject *)op)->cval.imag;
274 : : }
275 : : else {
276 : 0 : return 0.0;
277 : : }
278 : : }
279 : :
280 : : static PyObject *
281 : 0 : try_complex_special_method(PyObject *op)
282 : : {
283 : : PyObject *f;
284 : :
285 : 0 : f = _PyObject_LookupSpecial(op, &_Py_ID(__complex__));
286 [ # # ]: 0 : if (f) {
287 : 0 : PyObject *res = _PyObject_CallNoArgs(f);
288 : 0 : Py_DECREF(f);
289 [ # # # # ]: 0 : if (!res || PyComplex_CheckExact(res)) {
290 : 0 : return res;
291 : : }
292 [ # # ]: 0 : if (!PyComplex_Check(res)) {
293 : 0 : PyErr_Format(PyExc_TypeError,
294 : : "__complex__ returned non-complex (type %.200s)",
295 : 0 : Py_TYPE(res)->tp_name);
296 : 0 : Py_DECREF(res);
297 : 0 : return NULL;
298 : : }
299 : : /* Issue #29894: warn if 'res' not of exact type complex. */
300 [ # # ]: 0 : if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
301 : : "__complex__ returned non-complex (type %.200s). "
302 : : "The ability to return an instance of a strict subclass of complex "
303 : : "is deprecated, and may be removed in a future version of Python.",
304 : 0 : Py_TYPE(res)->tp_name)) {
305 : 0 : Py_DECREF(res);
306 : 0 : return NULL;
307 : : }
308 : 0 : return res;
309 : : }
310 : 0 : return NULL;
311 : : }
312 : :
313 : : Py_complex
314 : 6 : PyComplex_AsCComplex(PyObject *op)
315 : : {
316 : : Py_complex cv;
317 : 6 : PyObject *newop = NULL;
318 : :
319 : : assert(op);
320 : : /* If op is already of type PyComplex_Type, return its value */
321 [ + - ]: 6 : if (PyComplex_Check(op)) {
322 : 6 : return ((PyComplexObject *)op)->cval;
323 : : }
324 : : /* If not, use op's __complex__ method, if it exists */
325 : :
326 : : /* return -1 on failure */
327 : 0 : cv.real = -1.;
328 : 0 : cv.imag = 0.;
329 : :
330 : 0 : newop = try_complex_special_method(op);
331 : :
332 [ # # ]: 0 : if (newop) {
333 : 0 : cv = ((PyComplexObject *)newop)->cval;
334 : 0 : Py_DECREF(newop);
335 : 0 : return cv;
336 : : }
337 [ # # ]: 0 : else if (PyErr_Occurred()) {
338 : 0 : return cv;
339 : : }
340 : : /* If neither of the above works, interpret op as a float giving the
341 : : real part of the result, and fill in the imaginary part as 0. */
342 : : else {
343 : : /* PyFloat_AsDouble will return -1 on failure */
344 : 0 : cv.real = PyFloat_AsDouble(op);
345 : 0 : return cv;
346 : : }
347 : : }
348 : :
349 : : static PyObject *
350 : 0 : complex_repr(PyComplexObject *v)
351 : : {
352 : 0 : int precision = 0;
353 : 0 : char format_code = 'r';
354 : 0 : PyObject *result = NULL;
355 : :
356 : : /* If these are non-NULL, they'll need to be freed. */
357 : 0 : char *pre = NULL;
358 : 0 : char *im = NULL;
359 : :
360 : : /* These do not need to be freed. re is either an alias
361 : : for pre or a pointer to a constant. lead and tail
362 : : are pointers to constants. */
363 : 0 : const char *re = NULL;
364 : 0 : const char *lead = "";
365 : 0 : const char *tail = "";
366 : :
367 [ # # # # ]: 0 : if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
368 : : /* Real part is +0: just output the imaginary part and do not
369 : : include parens. */
370 : 0 : re = "";
371 : 0 : im = PyOS_double_to_string(v->cval.imag, format_code,
372 : : precision, 0, NULL);
373 [ # # ]: 0 : if (!im) {
374 : 0 : PyErr_NoMemory();
375 : 0 : goto done;
376 : : }
377 : : } else {
378 : : /* Format imaginary part with sign, real part without. Include
379 : : parens in the result. */
380 : 0 : pre = PyOS_double_to_string(v->cval.real, format_code,
381 : : precision, 0, NULL);
382 [ # # ]: 0 : if (!pre) {
383 : 0 : PyErr_NoMemory();
384 : 0 : goto done;
385 : : }
386 : 0 : re = pre;
387 : :
388 : 0 : im = PyOS_double_to_string(v->cval.imag, format_code,
389 : : precision, Py_DTSF_SIGN, NULL);
390 [ # # ]: 0 : if (!im) {
391 : 0 : PyErr_NoMemory();
392 : 0 : goto done;
393 : : }
394 : 0 : lead = "(";
395 : 0 : tail = ")";
396 : : }
397 : 0 : result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail);
398 : 0 : done:
399 : 0 : PyMem_Free(im);
400 : 0 : PyMem_Free(pre);
401 : :
402 : 0 : return result;
403 : : }
404 : :
405 : : static Py_hash_t
406 : 45 : complex_hash(PyComplexObject *v)
407 : : {
408 : : Py_uhash_t hashreal, hashimag, combined;
409 : 45 : hashreal = (Py_uhash_t)_Py_HashDouble((PyObject *) v, v->cval.real);
410 [ - + ]: 45 : if (hashreal == (Py_uhash_t)-1)
411 : 0 : return -1;
412 : 45 : hashimag = (Py_uhash_t)_Py_HashDouble((PyObject *)v, v->cval.imag);
413 [ - + ]: 45 : if (hashimag == (Py_uhash_t)-1)
414 : 0 : return -1;
415 : : /* Note: if the imaginary part is 0, hashimag is 0 now,
416 : : * so the following returns hashreal unchanged. This is
417 : : * important because numbers of different types that
418 : : * compare equal must have the same hash value, so that
419 : : * hash(x + 0*j) must equal hash(x).
420 : : */
421 : 45 : combined = hashreal + _PyHASH_IMAG * hashimag;
422 [ - + ]: 45 : if (combined == (Py_uhash_t)-1)
423 : 0 : combined = (Py_uhash_t)-2;
424 : 45 : return (Py_hash_t)combined;
425 : : }
426 : :
427 : : /* This macro may return! */
428 : : #define TO_COMPLEX(obj, c) \
429 : : if (PyComplex_Check(obj)) \
430 : : c = ((PyComplexObject *)(obj))->cval; \
431 : : else if (to_complex(&(obj), &(c)) < 0) \
432 : : return (obj)
433 : :
434 : : static int
435 : 2 : to_complex(PyObject **pobj, Py_complex *pc)
436 : : {
437 : 2 : PyObject *obj = *pobj;
438 : :
439 : 2 : pc->real = pc->imag = 0.0;
440 [ + + ]: 2 : if (PyLong_Check(obj)) {
441 : 1 : pc->real = PyLong_AsDouble(obj);
442 [ - + - - ]: 1 : if (pc->real == -1.0 && PyErr_Occurred()) {
443 : 0 : *pobj = NULL;
444 : 0 : return -1;
445 : : }
446 : 1 : return 0;
447 : : }
448 [ + - ]: 1 : if (PyFloat_Check(obj)) {
449 : 1 : pc->real = PyFloat_AsDouble(obj);
450 : 1 : return 0;
451 : : }
452 : 0 : *pobj = Py_NewRef(Py_NotImplemented);
453 : 0 : return -1;
454 : : }
455 : :
456 : :
457 : : static PyObject *
458 : 2 : complex_add(PyObject *v, PyObject *w)
459 : : {
460 : : Py_complex result;
461 : : Py_complex a, b;
462 [ - + - + ]: 2 : TO_COMPLEX(v, a);
463 [ + - - - ]: 2 : TO_COMPLEX(w, b);
464 : 2 : result = _Py_c_sum(a, b);
465 : 2 : return PyComplex_FromCComplex(result);
466 : : }
467 : :
468 : : static PyObject *
469 : 0 : complex_sub(PyObject *v, PyObject *w)
470 : : {
471 : : Py_complex result;
472 : : Py_complex a, b;
473 [ # # # # ]: 0 : TO_COMPLEX(v, a);
474 [ # # # # ]: 0 : TO_COMPLEX(w, b);
475 : 0 : result = _Py_c_diff(a, b);
476 : 0 : return PyComplex_FromCComplex(result);
477 : : }
478 : :
479 : : static PyObject *
480 : 0 : complex_mul(PyObject *v, PyObject *w)
481 : : {
482 : : Py_complex result;
483 : : Py_complex a, b;
484 [ # # # # ]: 0 : TO_COMPLEX(v, a);
485 [ # # # # ]: 0 : TO_COMPLEX(w, b);
486 : 0 : result = _Py_c_prod(a, b);
487 : 0 : return PyComplex_FromCComplex(result);
488 : : }
489 : :
490 : : static PyObject *
491 : 0 : complex_div(PyObject *v, PyObject *w)
492 : : {
493 : : Py_complex quot;
494 : : Py_complex a, b;
495 [ # # # # ]: 0 : TO_COMPLEX(v, a);
496 [ # # # # ]: 0 : TO_COMPLEX(w, b);
497 : 0 : errno = 0;
498 : 0 : quot = _Py_c_quot(a, b);
499 [ # # ]: 0 : if (errno == EDOM) {
500 : 0 : PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
501 : 0 : return NULL;
502 : : }
503 : 0 : return PyComplex_FromCComplex(quot);
504 : : }
505 : :
506 : : static PyObject *
507 : 0 : complex_pow(PyObject *v, PyObject *w, PyObject *z)
508 : : {
509 : : Py_complex p;
510 : : Py_complex a, b;
511 [ # # # # ]: 0 : TO_COMPLEX(v, a);
512 [ # # # # ]: 0 : TO_COMPLEX(w, b);
513 : :
514 [ # # ]: 0 : if (z != Py_None) {
515 : 0 : PyErr_SetString(PyExc_ValueError, "complex modulo");
516 : 0 : return NULL;
517 : : }
518 : 0 : errno = 0;
519 : : // Check whether the exponent has a small integer value, and if so use
520 : : // a faster and more accurate algorithm.
521 [ # # # # : 0 : if (b.imag == 0.0 && b.real == floor(b.real) && fabs(b.real) <= 100.0) {
# # ]
522 : 0 : p = c_powi(a, (long)b.real);
523 : : }
524 : : else {
525 : 0 : p = _Py_c_pow(a, b);
526 : : }
527 : :
528 : 0 : _Py_ADJUST_ERANGE2(p.real, p.imag);
529 [ # # ]: 0 : if (errno == EDOM) {
530 : 0 : PyErr_SetString(PyExc_ZeroDivisionError,
531 : : "0.0 to a negative or complex power");
532 : 0 : return NULL;
533 : : }
534 [ # # ]: 0 : else if (errno == ERANGE) {
535 : 0 : PyErr_SetString(PyExc_OverflowError,
536 : : "complex exponentiation");
537 : 0 : return NULL;
538 : : }
539 : 0 : return PyComplex_FromCComplex(p);
540 : : }
541 : :
542 : : static PyObject *
543 : 0 : complex_neg(PyComplexObject *v)
544 : : {
545 : : Py_complex neg;
546 : 0 : neg.real = -v->cval.real;
547 : 0 : neg.imag = -v->cval.imag;
548 : 0 : return PyComplex_FromCComplex(neg);
549 : : }
550 : :
551 : : static PyObject *
552 : 0 : complex_pos(PyComplexObject *v)
553 : : {
554 [ # # ]: 0 : if (PyComplex_CheckExact(v)) {
555 : 0 : return Py_NewRef(v);
556 : : }
557 : : else
558 : 0 : return PyComplex_FromCComplex(v->cval);
559 : : }
560 : :
561 : : static PyObject *
562 : 0 : complex_abs(PyComplexObject *v)
563 : : {
564 : : double result;
565 : :
566 : 0 : result = _Py_c_abs(v->cval);
567 : :
568 [ # # ]: 0 : if (errno == ERANGE) {
569 : 0 : PyErr_SetString(PyExc_OverflowError,
570 : : "absolute value too large");
571 : 0 : return NULL;
572 : : }
573 : 0 : return PyFloat_FromDouble(result);
574 : : }
575 : :
576 : : static int
577 : 0 : complex_bool(PyComplexObject *v)
578 : : {
579 [ # # # # ]: 0 : return v->cval.real != 0.0 || v->cval.imag != 0.0;
580 : : }
581 : :
582 : : static PyObject *
583 : 0 : complex_richcompare(PyObject *v, PyObject *w, int op)
584 : : {
585 : : PyObject *res;
586 : : Py_complex i;
587 : : int equal;
588 : :
589 [ # # # # ]: 0 : if (op != Py_EQ && op != Py_NE) {
590 : 0 : goto Unimplemented;
591 : : }
592 : :
593 : : assert(PyComplex_Check(v));
594 [ # # # # ]: 0 : TO_COMPLEX(v, i);
595 : :
596 [ # # ]: 0 : if (PyLong_Check(w)) {
597 : : /* Check for 0.0 imaginary part first to avoid the rich
598 : : * comparison when possible.
599 : : */
600 [ # # ]: 0 : if (i.imag == 0.0) {
601 : : PyObject *j, *sub_res;
602 : 0 : j = PyFloat_FromDouble(i.real);
603 [ # # ]: 0 : if (j == NULL)
604 : 0 : return NULL;
605 : :
606 : 0 : sub_res = PyObject_RichCompare(j, w, op);
607 : 0 : Py_DECREF(j);
608 : 0 : return sub_res;
609 : : }
610 : : else {
611 : 0 : equal = 0;
612 : : }
613 : : }
614 [ # # ]: 0 : else if (PyFloat_Check(w)) {
615 [ # # # # ]: 0 : equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
616 : : }
617 [ # # ]: 0 : else if (PyComplex_Check(w)) {
618 : : Py_complex j;
619 : :
620 [ # # # # ]: 0 : TO_COMPLEX(w, j);
621 [ # # # # ]: 0 : equal = (i.real == j.real && i.imag == j.imag);
622 : : }
623 : : else {
624 : 0 : goto Unimplemented;
625 : : }
626 : :
627 [ # # ]: 0 : if (equal == (op == Py_EQ))
628 : 0 : res = Py_True;
629 : : else
630 : 0 : res = Py_False;
631 : :
632 : 0 : return Py_NewRef(res);
633 : :
634 : 0 : Unimplemented:
635 : 0 : Py_RETURN_NOTIMPLEMENTED;
636 : : }
637 : :
638 : : /*[clinic input]
639 : : complex.conjugate
640 : :
641 : : Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
642 : : [clinic start generated code]*/
643 : :
644 : : static PyObject *
645 : 0 : complex_conjugate_impl(PyComplexObject *self)
646 : : /*[clinic end generated code: output=5059ef162edfc68e input=5fea33e9747ec2c4]*/
647 : : {
648 : 0 : Py_complex c = self->cval;
649 : 0 : c.imag = -c.imag;
650 : 0 : return PyComplex_FromCComplex(c);
651 : : }
652 : :
653 : : /*[clinic input]
654 : : complex.__getnewargs__
655 : :
656 : : [clinic start generated code]*/
657 : :
658 : : static PyObject *
659 : 0 : complex___getnewargs___impl(PyComplexObject *self)
660 : : /*[clinic end generated code: output=689b8206e8728934 input=539543e0a50533d7]*/
661 : : {
662 : 0 : Py_complex c = self->cval;
663 : 0 : return Py_BuildValue("(dd)", c.real, c.imag);
664 : : }
665 : :
666 : :
667 : : /*[clinic input]
668 : : complex.__format__
669 : :
670 : : format_spec: unicode
671 : : /
672 : :
673 : : Convert to a string according to format_spec.
674 : : [clinic start generated code]*/
675 : :
676 : : static PyObject *
677 : 0 : complex___format___impl(PyComplexObject *self, PyObject *format_spec)
678 : : /*[clinic end generated code: output=bfcb60df24cafea0 input=014ef5488acbe1d5]*/
679 : : {
680 : : _PyUnicodeWriter writer;
681 : : int ret;
682 : 0 : _PyUnicodeWriter_Init(&writer);
683 : 0 : ret = _PyComplex_FormatAdvancedWriter(
684 : : &writer,
685 : : (PyObject *)self,
686 : : format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
687 [ # # ]: 0 : if (ret == -1) {
688 : 0 : _PyUnicodeWriter_Dealloc(&writer);
689 : 0 : return NULL;
690 : : }
691 : 0 : return _PyUnicodeWriter_Finish(&writer);
692 : : }
693 : :
694 : : /*[clinic input]
695 : : complex.__complex__
696 : :
697 : : Convert this value to exact type complex.
698 : : [clinic start generated code]*/
699 : :
700 : : static PyObject *
701 : 0 : complex___complex___impl(PyComplexObject *self)
702 : : /*[clinic end generated code: output=e6b35ba3d275dc9c input=3589ada9d27db854]*/
703 : : {
704 [ # # ]: 0 : if (PyComplex_CheckExact(self)) {
705 : 0 : return Py_NewRef(self);
706 : : }
707 : : else {
708 : 0 : return PyComplex_FromCComplex(self->cval);
709 : : }
710 : : }
711 : :
712 : :
713 : : static PyMethodDef complex_methods[] = {
714 : : COMPLEX_CONJUGATE_METHODDEF
715 : : COMPLEX___COMPLEX___METHODDEF
716 : : COMPLEX___GETNEWARGS___METHODDEF
717 : : COMPLEX___FORMAT___METHODDEF
718 : : {NULL, NULL} /* sentinel */
719 : : };
720 : :
721 : : static PyMemberDef complex_members[] = {
722 : : {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
723 : : "the real part of a complex number"},
724 : : {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
725 : : "the imaginary part of a complex number"},
726 : : {0},
727 : : };
728 : :
729 : : static PyObject *
730 : 0 : complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
731 : : {
732 : 0 : double x=0.0, y=0.0, z;
733 : 0 : int got_bracket=0;
734 : : const char *start;
735 : : char *end;
736 : :
737 : : /* position on first nonblank */
738 : 0 : start = s;
739 [ # # ]: 0 : while (Py_ISSPACE(*s))
740 : 0 : s++;
741 [ # # ]: 0 : if (*s == '(') {
742 : : /* Skip over possible bracket from repr(). */
743 : 0 : got_bracket = 1;
744 : 0 : s++;
745 [ # # ]: 0 : while (Py_ISSPACE(*s))
746 : 0 : s++;
747 : : }
748 : :
749 : : /* a valid complex string usually takes one of the three forms:
750 : :
751 : : <float> - real part only
752 : : <float>j - imaginary part only
753 : : <float><signed-float>j - real and imaginary parts
754 : :
755 : : where <float> represents any numeric string that's accepted by the
756 : : float constructor (including 'nan', 'inf', 'infinity', etc.), and
757 : : <signed-float> is any string of the form <float> whose first
758 : : character is '+' or '-'.
759 : :
760 : : For backwards compatibility, the extra forms
761 : :
762 : : <float><sign>j
763 : : <sign>j
764 : : j
765 : :
766 : : are also accepted, though support for these forms may be removed from
767 : : a future version of Python.
768 : : */
769 : :
770 : : /* first look for forms starting with <float> */
771 : 0 : z = PyOS_string_to_double(s, &end, NULL);
772 [ # # # # ]: 0 : if (z == -1.0 && PyErr_Occurred()) {
773 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_ValueError))
774 : 0 : PyErr_Clear();
775 : : else
776 : 0 : return NULL;
777 : : }
778 [ # # ]: 0 : if (end != s) {
779 : : /* all 4 forms starting with <float> land here */
780 : 0 : s = end;
781 [ # # # # ]: 0 : if (*s == '+' || *s == '-') {
782 : : /* <float><signed-float>j | <float><sign>j */
783 : 0 : x = z;
784 : 0 : y = PyOS_string_to_double(s, &end, NULL);
785 [ # # # # ]: 0 : if (y == -1.0 && PyErr_Occurred()) {
786 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_ValueError))
787 : 0 : PyErr_Clear();
788 : : else
789 : 0 : return NULL;
790 : : }
791 [ # # ]: 0 : if (end != s)
792 : : /* <float><signed-float>j */
793 : 0 : s = end;
794 : : else {
795 : : /* <float><sign>j */
796 [ # # ]: 0 : y = *s == '+' ? 1.0 : -1.0;
797 : 0 : s++;
798 : : }
799 [ # # # # ]: 0 : if (!(*s == 'j' || *s == 'J'))
800 : 0 : goto parse_error;
801 : 0 : s++;
802 : : }
803 [ # # # # ]: 0 : else if (*s == 'j' || *s == 'J') {
804 : : /* <float>j */
805 : 0 : s++;
806 : 0 : y = z;
807 : : }
808 : : else
809 : : /* <float> */
810 : 0 : x = z;
811 : : }
812 : : else {
813 : : /* not starting with <float>; must be <sign>j or j */
814 [ # # # # ]: 0 : if (*s == '+' || *s == '-') {
815 : : /* <sign>j */
816 [ # # ]: 0 : y = *s == '+' ? 1.0 : -1.0;
817 : 0 : s++;
818 : : }
819 : : else
820 : : /* j */
821 : 0 : y = 1.0;
822 [ # # # # ]: 0 : if (!(*s == 'j' || *s == 'J'))
823 : 0 : goto parse_error;
824 : 0 : s++;
825 : : }
826 : :
827 : : /* trailing whitespace and closing bracket */
828 [ # # ]: 0 : while (Py_ISSPACE(*s))
829 : 0 : s++;
830 [ # # ]: 0 : if (got_bracket) {
831 : : /* if there was an opening parenthesis, then the corresponding
832 : : closing parenthesis should be right here */
833 [ # # ]: 0 : if (*s != ')')
834 : 0 : goto parse_error;
835 : 0 : s++;
836 [ # # ]: 0 : while (Py_ISSPACE(*s))
837 : 0 : s++;
838 : : }
839 : :
840 : : /* we should now be at the end of the string */
841 [ # # ]: 0 : if (s-start != len)
842 : 0 : goto parse_error;
843 : :
844 : 0 : return complex_subtype_from_doubles(_PyType_CAST(type), x, y);
845 : :
846 : 0 : parse_error:
847 : 0 : PyErr_SetString(PyExc_ValueError,
848 : : "complex() arg is a malformed string");
849 : 0 : return NULL;
850 : : }
851 : :
852 : : static PyObject *
853 : 0 : complex_subtype_from_string(PyTypeObject *type, PyObject *v)
854 : : {
855 : : const char *s;
856 : 0 : PyObject *s_buffer = NULL, *result = NULL;
857 : : Py_ssize_t len;
858 : :
859 [ # # ]: 0 : if (PyUnicode_Check(v)) {
860 : 0 : s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
861 [ # # ]: 0 : if (s_buffer == NULL) {
862 : 0 : return NULL;
863 : : }
864 : : assert(PyUnicode_IS_ASCII(s_buffer));
865 : : /* Simply get a pointer to existing ASCII characters. */
866 : 0 : s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
867 : : assert(s != NULL);
868 : : }
869 : : else {
870 : 0 : PyErr_Format(PyExc_TypeError,
871 : : "complex() argument must be a string or a number, not '%.200s'",
872 : 0 : Py_TYPE(v)->tp_name);
873 : 0 : return NULL;
874 : : }
875 : :
876 : 0 : result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
877 : : complex_from_string_inner);
878 : 0 : Py_DECREF(s_buffer);
879 : 0 : return result;
880 : : }
881 : :
882 : : /*[clinic input]
883 : : @classmethod
884 : : complex.__new__ as complex_new
885 : : real as r: object(c_default="NULL") = 0
886 : : imag as i: object(c_default="NULL") = 0
887 : :
888 : : Create a complex number from a real part and an optional imaginary part.
889 : :
890 : : This is equivalent to (real + imag*1j) where imag defaults to 0.
891 : : [clinic start generated code]*/
892 : :
893 : : static PyObject *
894 : 0 : complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
895 : : /*[clinic end generated code: output=b6c7dd577b537dc1 input=f4c667f2596d4fd1]*/
896 : : {
897 : : PyObject *tmp;
898 : 0 : PyNumberMethods *nbr, *nbi = NULL;
899 : : Py_complex cr, ci;
900 : 0 : int own_r = 0;
901 : 0 : int cr_is_complex = 0;
902 : 0 : int ci_is_complex = 0;
903 : :
904 [ # # ]: 0 : if (r == NULL) {
905 : 0 : r = _PyLong_GetZero();
906 : : }
907 : :
908 : : /* Special-case for a single argument when type(arg) is complex. */
909 [ # # # # : 0 : if (PyComplex_CheckExact(r) && i == NULL &&
# # ]
910 : : type == &PyComplex_Type) {
911 : : /* Note that we can't know whether it's safe to return
912 : : a complex *subclass* instance as-is, hence the restriction
913 : : to exact complexes here. If either the input or the
914 : : output is a complex subclass, it will be handled below
915 : : as a non-orthogonal vector. */
916 : 0 : return Py_NewRef(r);
917 : : }
918 [ # # ]: 0 : if (PyUnicode_Check(r)) {
919 [ # # ]: 0 : if (i != NULL) {
920 : 0 : PyErr_SetString(PyExc_TypeError,
921 : : "complex() can't take second arg"
922 : : " if first is a string");
923 : 0 : return NULL;
924 : : }
925 : 0 : return complex_subtype_from_string(type, r);
926 : : }
927 [ # # # # ]: 0 : if (i != NULL && PyUnicode_Check(i)) {
928 : 0 : PyErr_SetString(PyExc_TypeError,
929 : : "complex() second arg can't be a string");
930 : 0 : return NULL;
931 : : }
932 : :
933 : 0 : tmp = try_complex_special_method(r);
934 [ # # ]: 0 : if (tmp) {
935 : 0 : r = tmp;
936 : 0 : own_r = 1;
937 : : }
938 [ # # ]: 0 : else if (PyErr_Occurred()) {
939 : 0 : return NULL;
940 : : }
941 : :
942 : 0 : nbr = Py_TYPE(r)->tp_as_number;
943 [ # # ]: 0 : if (nbr == NULL ||
944 [ # # # # : 0 : (nbr->nb_float == NULL && nbr->nb_index == NULL && !PyComplex_Check(r)))
# # ]
945 : : {
946 : 0 : PyErr_Format(PyExc_TypeError,
947 : : "complex() first argument must be a string or a number, "
948 : : "not '%.200s'",
949 : 0 : Py_TYPE(r)->tp_name);
950 [ # # ]: 0 : if (own_r) {
951 : 0 : Py_DECREF(r);
952 : : }
953 : 0 : return NULL;
954 : : }
955 [ # # ]: 0 : if (i != NULL) {
956 : 0 : nbi = Py_TYPE(i)->tp_as_number;
957 [ # # ]: 0 : if (nbi == NULL ||
958 [ # # # # : 0 : (nbi->nb_float == NULL && nbi->nb_index == NULL && !PyComplex_Check(i)))
# # ]
959 : : {
960 : 0 : PyErr_Format(PyExc_TypeError,
961 : : "complex() second argument must be a number, "
962 : : "not '%.200s'",
963 : 0 : Py_TYPE(i)->tp_name);
964 [ # # ]: 0 : if (own_r) {
965 : 0 : Py_DECREF(r);
966 : : }
967 : 0 : return NULL;
968 : : }
969 : : }
970 : :
971 : : /* If we get this far, then the "real" and "imag" parts should
972 : : both be treated as numbers, and the constructor should return a
973 : : complex number equal to (real + imag*1j).
974 : :
975 : : Note that we do NOT assume the input to already be in canonical
976 : : form; the "real" and "imag" parts might themselves be complex
977 : : numbers, which slightly complicates the code below. */
978 [ # # ]: 0 : if (PyComplex_Check(r)) {
979 : : /* Note that if r is of a complex subtype, we're only
980 : : retaining its real & imag parts here, and the return
981 : : value is (properly) of the builtin complex type. */
982 : 0 : cr = ((PyComplexObject*)r)->cval;
983 : 0 : cr_is_complex = 1;
984 [ # # ]: 0 : if (own_r) {
985 : 0 : Py_DECREF(r);
986 : : }
987 : : }
988 : : else {
989 : : /* The "real" part really is entirely real, and contributes
990 : : nothing in the imaginary direction.
991 : : Just treat it as a double. */
992 : 0 : tmp = PyNumber_Float(r);
993 [ # # ]: 0 : if (own_r) {
994 : : /* r was a newly created complex number, rather
995 : : than the original "real" argument. */
996 : 0 : Py_DECREF(r);
997 : : }
998 [ # # ]: 0 : if (tmp == NULL)
999 : 0 : return NULL;
1000 : : assert(PyFloat_Check(tmp));
1001 : 0 : cr.real = PyFloat_AsDouble(tmp);
1002 : 0 : cr.imag = 0.0;
1003 : 0 : Py_DECREF(tmp);
1004 : : }
1005 [ # # ]: 0 : if (i == NULL) {
1006 : 0 : ci.real = cr.imag;
1007 : : }
1008 [ # # ]: 0 : else if (PyComplex_Check(i)) {
1009 : 0 : ci = ((PyComplexObject*)i)->cval;
1010 : 0 : ci_is_complex = 1;
1011 : : } else {
1012 : : /* The "imag" part really is entirely imaginary, and
1013 : : contributes nothing in the real direction.
1014 : : Just treat it as a double. */
1015 : 0 : tmp = PyNumber_Float(i);
1016 [ # # ]: 0 : if (tmp == NULL)
1017 : 0 : return NULL;
1018 : 0 : ci.real = PyFloat_AsDouble(tmp);
1019 : 0 : Py_DECREF(tmp);
1020 : : }
1021 : : /* If the input was in canonical form, then the "real" and "imag"
1022 : : parts are real numbers, so that ci.imag and cr.imag are zero.
1023 : : We need this correction in case they were not real numbers. */
1024 : :
1025 [ # # ]: 0 : if (ci_is_complex) {
1026 : 0 : cr.real -= ci.imag;
1027 : : }
1028 [ # # # # ]: 0 : if (cr_is_complex && i != NULL) {
1029 : 0 : ci.real += cr.imag;
1030 : : }
1031 : 0 : return complex_subtype_from_doubles(type, cr.real, ci.real);
1032 : : }
1033 : :
1034 : : static PyNumberMethods complex_as_number = {
1035 : : (binaryfunc)complex_add, /* nb_add */
1036 : : (binaryfunc)complex_sub, /* nb_subtract */
1037 : : (binaryfunc)complex_mul, /* nb_multiply */
1038 : : 0, /* nb_remainder */
1039 : : 0, /* nb_divmod */
1040 : : (ternaryfunc)complex_pow, /* nb_power */
1041 : : (unaryfunc)complex_neg, /* nb_negative */
1042 : : (unaryfunc)complex_pos, /* nb_positive */
1043 : : (unaryfunc)complex_abs, /* nb_absolute */
1044 : : (inquiry)complex_bool, /* nb_bool */
1045 : : 0, /* nb_invert */
1046 : : 0, /* nb_lshift */
1047 : : 0, /* nb_rshift */
1048 : : 0, /* nb_and */
1049 : : 0, /* nb_xor */
1050 : : 0, /* nb_or */
1051 : : 0, /* nb_int */
1052 : : 0, /* nb_reserved */
1053 : : 0, /* nb_float */
1054 : : 0, /* nb_inplace_add */
1055 : : 0, /* nb_inplace_subtract */
1056 : : 0, /* nb_inplace_multiply*/
1057 : : 0, /* nb_inplace_remainder */
1058 : : 0, /* nb_inplace_power */
1059 : : 0, /* nb_inplace_lshift */
1060 : : 0, /* nb_inplace_rshift */
1061 : : 0, /* nb_inplace_and */
1062 : : 0, /* nb_inplace_xor */
1063 : : 0, /* nb_inplace_or */
1064 : : 0, /* nb_floor_divide */
1065 : : (binaryfunc)complex_div, /* nb_true_divide */
1066 : : 0, /* nb_inplace_floor_divide */
1067 : : 0, /* nb_inplace_true_divide */
1068 : : };
1069 : :
1070 : : PyTypeObject PyComplex_Type = {
1071 : : PyVarObject_HEAD_INIT(&PyType_Type, 0)
1072 : : "complex",
1073 : : sizeof(PyComplexObject),
1074 : : 0,
1075 : : 0, /* tp_dealloc */
1076 : : 0, /* tp_vectorcall_offset */
1077 : : 0, /* tp_getattr */
1078 : : 0, /* tp_setattr */
1079 : : 0, /* tp_as_async */
1080 : : (reprfunc)complex_repr, /* tp_repr */
1081 : : &complex_as_number, /* tp_as_number */
1082 : : 0, /* tp_as_sequence */
1083 : : 0, /* tp_as_mapping */
1084 : : (hashfunc)complex_hash, /* tp_hash */
1085 : : 0, /* tp_call */
1086 : : 0, /* tp_str */
1087 : : PyObject_GenericGetAttr, /* tp_getattro */
1088 : : 0, /* tp_setattro */
1089 : : 0, /* tp_as_buffer */
1090 : : Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1091 : : complex_new__doc__, /* tp_doc */
1092 : : 0, /* tp_traverse */
1093 : : 0, /* tp_clear */
1094 : : complex_richcompare, /* tp_richcompare */
1095 : : 0, /* tp_weaklistoffset */
1096 : : 0, /* tp_iter */
1097 : : 0, /* tp_iternext */
1098 : : complex_methods, /* tp_methods */
1099 : : complex_members, /* tp_members */
1100 : : 0, /* tp_getset */
1101 : : 0, /* tp_base */
1102 : : 0, /* tp_dict */
1103 : : 0, /* tp_descr_get */
1104 : : 0, /* tp_descr_set */
1105 : : 0, /* tp_dictoffset */
1106 : : 0, /* tp_init */
1107 : : PyType_GenericAlloc, /* tp_alloc */
1108 : : complex_new, /* tp_new */
1109 : : PyObject_Del, /* tp_free */
1110 : : };
|