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