ยปCore Development>Code coverage>Objects/complexobject.c

Python code coverage for Objects/complexobject.c

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