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