+++ /dev/null
-\r
-/* Complex object implementation */\r
-\r
-/* Borrows heavily from floatobject.c */\r
-\r
-/* Submitted by Jim Hugunin */\r
-\r
-#include "Python.h"\r
-#include "structmember.h"\r
-\r
-#ifndef WITHOUT_COMPLEX\r
-\r
-/* Precisions used by repr() and str(), respectively.\r
-\r
- The repr() precision (17 significant decimal digits) is the minimal number\r
- that is guaranteed to have enough precision so that if the number is read\r
- back in the exact same binary value is recreated. This is true for IEEE\r
- floating point by design, and also happens to work for all other modern\r
- hardware.\r
-\r
- The str() precision is chosen so that in most cases, the rounding noise\r
- created by various operations is suppressed, while giving plenty of\r
- precision for practical use.\r
-*/\r
-\r
-#define PREC_REPR 17\r
-#define PREC_STR 12\r
-\r
-/* elementary operations on complex numbers */\r
-\r
-static Py_complex c_1 = {1., 0.};\r
-\r
-Py_complex\r
-c_sum(Py_complex a, Py_complex b)\r
-{\r
- Py_complex r;\r
- r.real = a.real + b.real;\r
- r.imag = a.imag + b.imag;\r
- return r;\r
-}\r
-\r
-Py_complex\r
-c_diff(Py_complex a, Py_complex b)\r
-{\r
- Py_complex r;\r
- r.real = a.real - b.real;\r
- r.imag = a.imag - b.imag;\r
- return r;\r
-}\r
-\r
-Py_complex\r
-c_neg(Py_complex a)\r
-{\r
- Py_complex r;\r
- r.real = -a.real;\r
- r.imag = -a.imag;\r
- return r;\r
-}\r
-\r
-Py_complex\r
-c_prod(Py_complex a, Py_complex b)\r
-{\r
- Py_complex r;\r
- r.real = a.real*b.real - a.imag*b.imag;\r
- r.imag = a.real*b.imag + a.imag*b.real;\r
- return r;\r
-}\r
-\r
-Py_complex\r
-c_quot(Py_complex a, Py_complex b)\r
-{\r
- /******************************************************************\r
- This was the original algorithm. It's grossly prone to spurious\r
- overflow and underflow errors. It also merrily divides by 0 despite\r
- checking for that(!). The code still serves a doc purpose here, as\r
- the algorithm following is a simple by-cases transformation of this\r
- one:\r
-\r
- Py_complex r;\r
- double d = b.real*b.real + b.imag*b.imag;\r
- if (d == 0.)\r
- errno = EDOM;\r
- r.real = (a.real*b.real + a.imag*b.imag)/d;\r
- r.imag = (a.imag*b.real - a.real*b.imag)/d;\r
- return r;\r
- ******************************************************************/\r
-\r
- /* This algorithm is better, and is pretty obvious: first divide the\r
- * numerators and denominator by whichever of {b.real, b.imag} has\r
- * larger magnitude. The earliest reference I found was to CACM\r
- * Algorithm 116 (Complex Division, Robert L. Smith, Stanford\r
- * University). As usual, though, we're still ignoring all IEEE\r
- * endcases.\r
- */\r
- Py_complex r; /* the result */\r
- const double abs_breal = b.real < 0 ? -b.real : b.real;\r
- const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;\r
-\r
- if (abs_breal >= abs_bimag) {\r
- /* divide tops and bottom by b.real */\r
- if (abs_breal == 0.0) {\r
- errno = EDOM;\r
- r.real = r.imag = 0.0;\r
- }\r
- else {\r
- const double ratio = b.imag / b.real;\r
- const double denom = b.real + b.imag * ratio;\r
- r.real = (a.real + a.imag * ratio) / denom;\r
- r.imag = (a.imag - a.real * ratio) / denom;\r
- }\r
- }\r
- else if (abs_bimag >= abs_breal) {\r
- /* divide tops and bottom by b.imag */\r
- const double ratio = b.real / b.imag;\r
- const double denom = b.real * ratio + b.imag;\r
- assert(b.imag != 0.0);\r
- r.real = (a.real * ratio + a.imag) / denom;\r
- r.imag = (a.imag * ratio - a.real) / denom;\r
- }\r
- else {\r
- /* At least one of b.real or b.imag is a NaN */\r
- r.real = r.imag = Py_NAN;\r
- }\r
- return r;\r
-}\r
-\r
-Py_complex\r
-c_pow(Py_complex a, Py_complex b)\r
-{\r
- Py_complex r;\r
- double vabs,len,at,phase;\r
- if (b.real == 0. && b.imag == 0.) {\r
- r.real = 1.;\r
- r.imag = 0.;\r
- }\r
- else if (a.real == 0. && a.imag == 0.) {\r
- if (b.imag != 0. || b.real < 0.)\r
- errno = EDOM;\r
- r.real = 0.;\r
- r.imag = 0.;\r
- }\r
- else {\r
- vabs = hypot(a.real,a.imag);\r
- len = pow(vabs,b.real);\r
- at = atan2(a.imag, a.real);\r
- phase = at*b.real;\r
- if (b.imag != 0.0) {\r
- len /= exp(at*b.imag);\r
- phase += b.imag*log(vabs);\r
- }\r
- r.real = len*cos(phase);\r
- r.imag = len*sin(phase);\r
- }\r
- return r;\r
-}\r
-\r
-static Py_complex\r
-c_powu(Py_complex x, long n)\r
-{\r
- Py_complex r, p;\r
- long mask = 1;\r
- r = c_1;\r
- p = x;\r
- while (mask > 0 && n >= mask) {\r
- if (n & mask)\r
- r = c_prod(r,p);\r
- mask <<= 1;\r
- p = c_prod(p,p);\r
- }\r
- return r;\r
-}\r
-\r
-static Py_complex\r
-c_powi(Py_complex x, long n)\r
-{\r
- Py_complex cn;\r
-\r
- if (n > 100 || n < -100) {\r
- cn.real = (double) n;\r
- cn.imag = 0.;\r
- return c_pow(x,cn);\r
- }\r
- else if (n > 0)\r
- return c_powu(x,n);\r
- else\r
- return c_quot(c_1,c_powu(x,-n));\r
-\r
-}\r
-\r
-double\r
-c_abs(Py_complex z)\r
-{\r
- /* sets errno = ERANGE on overflow; otherwise errno = 0 */\r
- double result;\r
-\r
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {\r
- /* C99 rules: if either the real or the imaginary part is an\r
- infinity, return infinity, even if the other part is a\r
- NaN. */\r
- if (Py_IS_INFINITY(z.real)) {\r
- result = fabs(z.real);\r
- errno = 0;\r
- return result;\r
- }\r
- if (Py_IS_INFINITY(z.imag)) {\r
- result = fabs(z.imag);\r
- errno = 0;\r
- return result;\r
- }\r
- /* either the real or imaginary part is a NaN,\r
- and neither is infinite. Result should be NaN. */\r
- return Py_NAN;\r
- }\r
- result = hypot(z.real, z.imag);\r
- if (!Py_IS_FINITE(result))\r
- errno = ERANGE;\r
- else\r
- errno = 0;\r
- return result;\r
-}\r
-\r
-static PyObject *\r
-complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)\r
-{\r
- PyObject *op;\r
-\r
- op = type->tp_alloc(type, 0);\r
- if (op != NULL)\r
- ((PyComplexObject *)op)->cval = cval;\r
- return op;\r
-}\r
-\r
-PyObject *\r
-PyComplex_FromCComplex(Py_complex cval)\r
-{\r
- register PyComplexObject *op;\r
-\r
- /* Inline PyObject_New */\r
- op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));\r
- if (op == NULL)\r
- return PyErr_NoMemory();\r
- PyObject_INIT(op, &PyComplex_Type);\r
- op->cval = cval;\r
- return (PyObject *) op;\r
-}\r
-\r
-static PyObject *\r
-complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)\r
-{\r
- Py_complex c;\r
- c.real = real;\r
- c.imag = imag;\r
- return complex_subtype_from_c_complex(type, c);\r
-}\r
-\r
-PyObject *\r
-PyComplex_FromDoubles(double real, double imag)\r
-{\r
- Py_complex c;\r
- c.real = real;\r
- c.imag = imag;\r
- return PyComplex_FromCComplex(c);\r
-}\r
-\r
-double\r
-PyComplex_RealAsDouble(PyObject *op)\r
-{\r
- if (PyComplex_Check(op)) {\r
- return ((PyComplexObject *)op)->cval.real;\r
- }\r
- else {\r
- return PyFloat_AsDouble(op);\r
- }\r
-}\r
-\r
-double\r
-PyComplex_ImagAsDouble(PyObject *op)\r
-{\r
- if (PyComplex_Check(op)) {\r
- return ((PyComplexObject *)op)->cval.imag;\r
- }\r
- else {\r
- return 0.0;\r
- }\r
-}\r
-\r
-static PyObject *\r
-try_complex_special_method(PyObject *op) {\r
- PyObject *f;\r
- static PyObject *complexstr;\r
-\r
- if (complexstr == NULL) {\r
- complexstr = PyString_InternFromString("__complex__");\r
- if (complexstr == NULL)\r
- return NULL;\r
- }\r
- if (PyInstance_Check(op)) {\r
- f = PyObject_GetAttr(op, complexstr);\r
- if (f == NULL) {\r
- if (PyErr_ExceptionMatches(PyExc_AttributeError))\r
- PyErr_Clear();\r
- else\r
- return NULL;\r
- }\r
- }\r
- else {\r
- f = _PyObject_LookupSpecial(op, "__complex__", &complexstr);\r
- if (f == NULL && PyErr_Occurred())\r
- return NULL;\r
- }\r
- if (f != NULL) {\r
- PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);\r
- Py_DECREF(f);\r
- return res;\r
- }\r
- return NULL;\r
-}\r
-\r
-Py_complex\r
-PyComplex_AsCComplex(PyObject *op)\r
-{\r
- Py_complex cv;\r
- PyObject *newop = NULL;\r
-\r
- assert(op);\r
- /* If op is already of type PyComplex_Type, return its value */\r
- if (PyComplex_Check(op)) {\r
- return ((PyComplexObject *)op)->cval;\r
- }\r
- /* If not, use op's __complex__ method, if it exists */\r
-\r
- /* return -1 on failure */\r
- cv.real = -1.;\r
- cv.imag = 0.;\r
-\r
- newop = try_complex_special_method(op);\r
-\r
- if (newop) {\r
- if (!PyComplex_Check(newop)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "__complex__ should return a complex object");\r
- Py_DECREF(newop);\r
- return cv;\r
- }\r
- cv = ((PyComplexObject *)newop)->cval;\r
- Py_DECREF(newop);\r
- return cv;\r
- }\r
- else if (PyErr_Occurred()) {\r
- return cv;\r
- }\r
- /* If neither of the above works, interpret op as a float giving the\r
- real part of the result, and fill in the imaginary part as 0. */\r
- else {\r
- /* PyFloat_AsDouble will return -1 on failure */\r
- cv.real = PyFloat_AsDouble(op);\r
- return cv;\r
- }\r
-}\r
-\r
-static void\r
-complex_dealloc(PyObject *op)\r
-{\r
- op->ob_type->tp_free(op);\r
-}\r
-\r
-\r
-static PyObject *\r
-complex_format(PyComplexObject *v, int precision, char format_code)\r
-{\r
- PyObject *result = NULL;\r
- Py_ssize_t len;\r
-\r
- /* If these are non-NULL, they'll need to be freed. */\r
- char *pre = NULL;\r
- char *im = NULL;\r
- char *buf = NULL;\r
-\r
- /* These do not need to be freed. re is either an alias\r
- for pre or a pointer to a constant. lead and tail\r
- are pointers to constants. */\r
- char *re = NULL;\r
- char *lead = "";\r
- char *tail = "";\r
-\r
- if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {\r
- re = "";\r
- im = PyOS_double_to_string(v->cval.imag, format_code,\r
- precision, 0, NULL);\r
- if (!im) {\r
- PyErr_NoMemory();\r
- goto done;\r
- }\r
- } else {\r
- /* Format imaginary part with sign, real part without */\r
- pre = PyOS_double_to_string(v->cval.real, format_code,\r
- precision, 0, NULL);\r
- if (!pre) {\r
- PyErr_NoMemory();\r
- goto done;\r
- }\r
- re = pre;\r
-\r
- im = PyOS_double_to_string(v->cval.imag, format_code,\r
- precision, Py_DTSF_SIGN, NULL);\r
- if (!im) {\r
- PyErr_NoMemory();\r
- goto done;\r
- }\r
- lead = "(";\r
- tail = ")";\r
- }\r
- /* Alloc the final buffer. Add one for the "j" in the format string,\r
- and one for the trailing zero. */\r
- len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;\r
- buf = PyMem_Malloc(len);\r
- if (!buf) {\r
- PyErr_NoMemory();\r
- goto done;\r
- }\r
- PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);\r
- result = PyString_FromString(buf);\r
- done:\r
- PyMem_Free(im);\r
- PyMem_Free(pre);\r
- PyMem_Free(buf);\r
-\r
- return result;\r
-}\r
-\r
-static int\r
-complex_print(PyComplexObject *v, FILE *fp, int flags)\r
-{\r
- PyObject *formatv;\r
- char *buf;\r
- if (flags & Py_PRINT_RAW)\r
- formatv = complex_format(v, PyFloat_STR_PRECISION, 'g');\r
- else\r
- formatv = complex_format(v, 0, 'r');\r
- if (formatv == NULL)\r
- return -1;\r
- buf = PyString_AS_STRING(formatv);\r
- Py_BEGIN_ALLOW_THREADS\r
- fputs(buf, fp);\r
- Py_END_ALLOW_THREADS\r
- Py_DECREF(formatv);\r
- return 0;\r
-}\r
-\r
-static PyObject *\r
-complex_repr(PyComplexObject *v)\r
-{\r
- return complex_format(v, 0, 'r');\r
-}\r
-\r
-static PyObject *\r
-complex_str(PyComplexObject *v)\r
-{\r
- return complex_format(v, PyFloat_STR_PRECISION, 'g');\r
-}\r
-\r
-static long\r
-complex_hash(PyComplexObject *v)\r
-{\r
- long hashreal, hashimag, combined;\r
- hashreal = _Py_HashDouble(v->cval.real);\r
- if (hashreal == -1)\r
- return -1;\r
- hashimag = _Py_HashDouble(v->cval.imag);\r
- if (hashimag == -1)\r
- return -1;\r
- /* Note: if the imaginary part is 0, hashimag is 0 now,\r
- * so the following returns hashreal unchanged. This is\r
- * important because numbers of different types that\r
- * compare equal must have the same hash value, so that\r
- * hash(x + 0*j) must equal hash(x).\r
- */\r
- combined = hashreal + 1000003 * hashimag;\r
- if (combined == -1)\r
- combined = -2;\r
- return combined;\r
-}\r
-\r
-/* This macro may return! */\r
-#define TO_COMPLEX(obj, c) \\r
- if (PyComplex_Check(obj)) \\r
- c = ((PyComplexObject *)(obj))->cval; \\r
- else if (to_complex(&(obj), &(c)) < 0) \\r
- return (obj)\r
-\r
-static int\r
-to_complex(PyObject **pobj, Py_complex *pc)\r
-{\r
- PyObject *obj = *pobj;\r
-\r
- pc->real = pc->imag = 0.0;\r
- if (PyInt_Check(obj)) {\r
- pc->real = PyInt_AS_LONG(obj);\r
- return 0;\r
- }\r
- if (PyLong_Check(obj)) {\r
- pc->real = PyLong_AsDouble(obj);\r
- if (pc->real == -1.0 && PyErr_Occurred()) {\r
- *pobj = NULL;\r
- return -1;\r
- }\r
- return 0;\r
- }\r
- if (PyFloat_Check(obj)) {\r
- pc->real = PyFloat_AsDouble(obj);\r
- return 0;\r
- }\r
- Py_INCREF(Py_NotImplemented);\r
- *pobj = Py_NotImplemented;\r
- return -1;\r
-}\r
-\r
-\r
-static PyObject *\r
-complex_add(PyObject *v, PyObject *w)\r
-{\r
- Py_complex result;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);\r
- PyFPE_START_PROTECT("complex_add", return 0)\r
- result = c_sum(a, b);\r
- PyFPE_END_PROTECT(result)\r
- return PyComplex_FromCComplex(result);\r
-}\r
-\r
-static PyObject *\r
-complex_sub(PyObject *v, PyObject *w)\r
-{\r
- Py_complex result;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);;\r
- PyFPE_START_PROTECT("complex_sub", return 0)\r
- result = c_diff(a, b);\r
- PyFPE_END_PROTECT(result)\r
- return PyComplex_FromCComplex(result);\r
-}\r
-\r
-static PyObject *\r
-complex_mul(PyObject *v, PyObject *w)\r
-{\r
- Py_complex result;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);\r
- PyFPE_START_PROTECT("complex_mul", return 0)\r
- result = c_prod(a, b);\r
- PyFPE_END_PROTECT(result)\r
- return PyComplex_FromCComplex(result);\r
-}\r
-\r
-static PyObject *\r
-complex_div(PyObject *v, PyObject *w)\r
-{\r
- Py_complex quot;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);\r
- PyFPE_START_PROTECT("complex_div", return 0)\r
- errno = 0;\r
- quot = c_quot(a, b);\r
- PyFPE_END_PROTECT(quot)\r
- if (errno == EDOM) {\r
- PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");\r
- return NULL;\r
- }\r
- return PyComplex_FromCComplex(quot);\r
-}\r
-\r
-static PyObject *\r
-complex_classic_div(PyObject *v, PyObject *w)\r
-{\r
- Py_complex quot;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);\r
- if (Py_DivisionWarningFlag >= 2 &&\r
- PyErr_Warn(PyExc_DeprecationWarning,\r
- "classic complex division") < 0)\r
- return NULL;\r
-\r
- PyFPE_START_PROTECT("complex_classic_div", return 0)\r
- errno = 0;\r
- quot = c_quot(a, b);\r
- PyFPE_END_PROTECT(quot)\r
- if (errno == EDOM) {\r
- PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");\r
- return NULL;\r
- }\r
- return PyComplex_FromCComplex(quot);\r
-}\r
-\r
-static PyObject *\r
-complex_remainder(PyObject *v, PyObject *w)\r
-{\r
- Py_complex div, mod;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);\r
- if (PyErr_Warn(PyExc_DeprecationWarning,\r
- "complex divmod(), // and % are deprecated") < 0)\r
- return NULL;\r
-\r
- errno = 0;\r
- div = c_quot(a, b); /* The raw divisor value. */\r
- if (errno == EDOM) {\r
- PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");\r
- return NULL;\r
- }\r
- div.real = floor(div.real); /* Use the floor of the real part. */\r
- div.imag = 0.0;\r
- mod = c_diff(a, c_prod(b, div));\r
-\r
- return PyComplex_FromCComplex(mod);\r
-}\r
-\r
-\r
-static PyObject *\r
-complex_divmod(PyObject *v, PyObject *w)\r
-{\r
- Py_complex div, mod;\r
- PyObject *d, *m, *z;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);\r
- if (PyErr_Warn(PyExc_DeprecationWarning,\r
- "complex divmod(), // and % are deprecated") < 0)\r
- return NULL;\r
-\r
- errno = 0;\r
- div = c_quot(a, b); /* The raw divisor value. */\r
- if (errno == EDOM) {\r
- PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");\r
- return NULL;\r
- }\r
- div.real = floor(div.real); /* Use the floor of the real part. */\r
- div.imag = 0.0;\r
- mod = c_diff(a, c_prod(b, div));\r
- d = PyComplex_FromCComplex(div);\r
- m = PyComplex_FromCComplex(mod);\r
- z = PyTuple_Pack(2, d, m);\r
- Py_XDECREF(d);\r
- Py_XDECREF(m);\r
- return z;\r
-}\r
-\r
-static PyObject *\r
-complex_pow(PyObject *v, PyObject *w, PyObject *z)\r
-{\r
- Py_complex p;\r
- Py_complex exponent;\r
- long int_exponent;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);\r
- if (z!=Py_None) {\r
- PyErr_SetString(PyExc_ValueError, "complex modulo");\r
- return NULL;\r
- }\r
- PyFPE_START_PROTECT("complex_pow", return 0)\r
- errno = 0;\r
- exponent = b;\r
- int_exponent = (long)exponent.real;\r
- if (exponent.imag == 0. && exponent.real == int_exponent)\r
- p = c_powi(a,int_exponent);\r
- else\r
- p = c_pow(a,exponent);\r
-\r
- PyFPE_END_PROTECT(p)\r
- Py_ADJUST_ERANGE2(p.real, p.imag);\r
- if (errno == EDOM) {\r
- PyErr_SetString(PyExc_ZeroDivisionError,\r
- "0.0 to a negative or complex power");\r
- return NULL;\r
- }\r
- else if (errno == ERANGE) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "complex exponentiation");\r
- return NULL;\r
- }\r
- return PyComplex_FromCComplex(p);\r
-}\r
-\r
-static PyObject *\r
-complex_int_div(PyObject *v, PyObject *w)\r
-{\r
- PyObject *t, *r;\r
- Py_complex a, b;\r
- TO_COMPLEX(v, a);\r
- TO_COMPLEX(w, b);\r
- if (PyErr_Warn(PyExc_DeprecationWarning,\r
- "complex divmod(), // and % are deprecated") < 0)\r
- return NULL;\r
-\r
- t = complex_divmod(v, w);\r
- if (t != NULL) {\r
- r = PyTuple_GET_ITEM(t, 0);\r
- Py_INCREF(r);\r
- Py_DECREF(t);\r
- return r;\r
- }\r
- return NULL;\r
-}\r
-\r
-static PyObject *\r
-complex_neg(PyComplexObject *v)\r
-{\r
- Py_complex neg;\r
- neg.real = -v->cval.real;\r
- neg.imag = -v->cval.imag;\r
- return PyComplex_FromCComplex(neg);\r
-}\r
-\r
-static PyObject *\r
-complex_pos(PyComplexObject *v)\r
-{\r
- if (PyComplex_CheckExact(v)) {\r
- Py_INCREF(v);\r
- return (PyObject *)v;\r
- }\r
- else\r
- return PyComplex_FromCComplex(v->cval);\r
-}\r
-\r
-static PyObject *\r
-complex_abs(PyComplexObject *v)\r
-{\r
- double result;\r
-\r
- PyFPE_START_PROTECT("complex_abs", return 0)\r
- result = c_abs(v->cval);\r
- PyFPE_END_PROTECT(result)\r
-\r
- if (errno == ERANGE) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "absolute value too large");\r
- return NULL;\r
- }\r
- return PyFloat_FromDouble(result);\r
-}\r
-\r
-static int\r
-complex_nonzero(PyComplexObject *v)\r
-{\r
- return v->cval.real != 0.0 || v->cval.imag != 0.0;\r
-}\r
-\r
-static int\r
-complex_coerce(PyObject **pv, PyObject **pw)\r
-{\r
- Py_complex cval;\r
- cval.imag = 0.;\r
- if (PyInt_Check(*pw)) {\r
- cval.real = (double)PyInt_AsLong(*pw);\r
- *pw = PyComplex_FromCComplex(cval);\r
- Py_INCREF(*pv);\r
- return 0;\r
- }\r
- else if (PyLong_Check(*pw)) {\r
- cval.real = PyLong_AsDouble(*pw);\r
- if (cval.real == -1.0 && PyErr_Occurred())\r
- return -1;\r
- *pw = PyComplex_FromCComplex(cval);\r
- Py_INCREF(*pv);\r
- return 0;\r
- }\r
- else if (PyFloat_Check(*pw)) {\r
- cval.real = PyFloat_AsDouble(*pw);\r
- *pw = PyComplex_FromCComplex(cval);\r
- Py_INCREF(*pv);\r
- return 0;\r
- }\r
- else if (PyComplex_Check(*pw)) {\r
- Py_INCREF(*pv);\r
- Py_INCREF(*pw);\r
- return 0;\r
- }\r
- return 1; /* Can't do it */\r
-}\r
-\r
-static PyObject *\r
-complex_richcompare(PyObject *v, PyObject *w, int op)\r
-{\r
- PyObject *res;\r
- Py_complex i;\r
- int equal;\r
-\r
- if (op != Py_EQ && op != Py_NE) {\r
- /* for backwards compatibility, comparisons with non-numbers return\r
- * NotImplemented. Only comparisons with core numeric types raise\r
- * TypeError.\r
- */\r
- if (PyInt_Check(w) || PyLong_Check(w) ||\r
- PyFloat_Check(w) || PyComplex_Check(w)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "no ordering relation is defined "\r
- "for complex numbers");\r
- return NULL;\r
- }\r
- goto Unimplemented;\r
- }\r
-\r
- assert(PyComplex_Check(v));\r
- TO_COMPLEX(v, i);\r
-\r
- if (PyInt_Check(w) || PyLong_Check(w)) {\r
- /* Check for 0.0 imaginary part first to avoid the rich\r
- * comparison when possible.\r
- */\r
- if (i.imag == 0.0) {\r
- PyObject *j, *sub_res;\r
- j = PyFloat_FromDouble(i.real);\r
- if (j == NULL)\r
- return NULL;\r
-\r
- sub_res = PyObject_RichCompare(j, w, op);\r
- Py_DECREF(j);\r
- return sub_res;\r
- }\r
- else {\r
- equal = 0;\r
- }\r
- }\r
- else if (PyFloat_Check(w)) {\r
- equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);\r
- }\r
- else if (PyComplex_Check(w)) {\r
- Py_complex j;\r
-\r
- TO_COMPLEX(w, j);\r
- equal = (i.real == j.real && i.imag == j.imag);\r
- }\r
- else {\r
- goto Unimplemented;\r
- }\r
-\r
- if (equal == (op == Py_EQ))\r
- res = Py_True;\r
- else\r
- res = Py_False;\r
-\r
- Py_INCREF(res);\r
- return res;\r
-\r
- Unimplemented:\r
- Py_INCREF(Py_NotImplemented);\r
- return Py_NotImplemented;\r
-}\r
-\r
-static PyObject *\r
-complex_int(PyObject *v)\r
-{\r
- PyErr_SetString(PyExc_TypeError,\r
- "can't convert complex to int");\r
- return NULL;\r
-}\r
-\r
-static PyObject *\r
-complex_long(PyObject *v)\r
-{\r
- PyErr_SetString(PyExc_TypeError,\r
- "can't convert complex to long");\r
- return NULL;\r
-}\r
-\r
-static PyObject *\r
-complex_float(PyObject *v)\r
-{\r
- PyErr_SetString(PyExc_TypeError,\r
- "can't convert complex to float");\r
- return NULL;\r
-}\r
-\r
-static PyObject *\r
-complex_conjugate(PyObject *self)\r
-{\r
- Py_complex c;\r
- c = ((PyComplexObject *)self)->cval;\r
- c.imag = -c.imag;\r
- return PyComplex_FromCComplex(c);\r
-}\r
-\r
-PyDoc_STRVAR(complex_conjugate_doc,\r
-"complex.conjugate() -> complex\n"\r
-"\n"\r
-"Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");\r
-\r
-static PyObject *\r
-complex_getnewargs(PyComplexObject *v)\r
-{\r
- Py_complex c = v->cval;\r
- return Py_BuildValue("(dd)", c.real, c.imag);\r
-}\r
-\r
-PyDoc_STRVAR(complex__format__doc,\r
-"complex.__format__() -> str\n"\r
-"\n"\r
-"Convert to a string according to format_spec.");\r
-\r
-static PyObject *\r
-complex__format__(PyObject* self, PyObject* args)\r
-{\r
- PyObject *format_spec;\r
-\r
- if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))\r
- return NULL;\r
- if (PyBytes_Check(format_spec))\r
- return _PyComplex_FormatAdvanced(self,\r
- PyBytes_AS_STRING(format_spec),\r
- PyBytes_GET_SIZE(format_spec));\r
- if (PyUnicode_Check(format_spec)) {\r
- /* Convert format_spec to a str */\r
- PyObject *result;\r
- PyObject *str_spec = PyObject_Str(format_spec);\r
-\r
- if (str_spec == NULL)\r
- return NULL;\r
-\r
- result = _PyComplex_FormatAdvanced(self,\r
- PyBytes_AS_STRING(str_spec),\r
- PyBytes_GET_SIZE(str_spec));\r
-\r
- Py_DECREF(str_spec);\r
- return result;\r
- }\r
- PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");\r
- return NULL;\r
-}\r
-\r
-#if 0\r
-static PyObject *\r
-complex_is_finite(PyObject *self)\r
-{\r
- Py_complex c;\r
- c = ((PyComplexObject *)self)->cval;\r
- return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&\r
- Py_IS_FINITE(c.imag)));\r
-}\r
-\r
-PyDoc_STRVAR(complex_is_finite_doc,\r
-"complex.is_finite() -> bool\n"\r
-"\n"\r
-"Returns True if the real and the imaginary part is finite.");\r
-#endif\r
-\r
-static PyMethodDef complex_methods[] = {\r
- {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,\r
- complex_conjugate_doc},\r
-#if 0\r
- {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,\r
- complex_is_finite_doc},\r
-#endif\r
- {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},\r
- {"__format__", (PyCFunction)complex__format__,\r
- METH_VARARGS, complex__format__doc},\r
- {NULL, NULL} /* sentinel */\r
-};\r
-\r
-static PyMemberDef complex_members[] = {\r
- {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,\r
- "the real part of a complex number"},\r
- {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,\r
- "the imaginary part of a complex number"},\r
- {0},\r
-};\r
-\r
-static PyObject *\r
-complex_subtype_from_string(PyTypeObject *type, PyObject *v)\r
-{\r
- const char *s, *start;\r
- char *end;\r
- double x=0.0, y=0.0, z;\r
- int got_bracket=0;\r
-#ifdef Py_USING_UNICODE\r
- char *s_buffer = NULL;\r
-#endif\r
- Py_ssize_t len;\r
-\r
- if (PyString_Check(v)) {\r
- s = PyString_AS_STRING(v);\r
- len = PyString_GET_SIZE(v);\r
- }\r
-#ifdef Py_USING_UNICODE\r
- else if (PyUnicode_Check(v)) {\r
- s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);\r
- if (s_buffer == NULL)\r
- return PyErr_NoMemory();\r
- if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),\r
- PyUnicode_GET_SIZE(v),\r
- s_buffer,\r
- NULL))\r
- goto error;\r
- s = s_buffer;\r
- len = strlen(s);\r
- }\r
-#endif\r
- else if (PyObject_AsCharBuffer(v, &s, &len)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "complex() arg is not a string");\r
- return NULL;\r
- }\r
-\r
- /* position on first nonblank */\r
- start = s;\r
- while (Py_ISSPACE(*s))\r
- s++;\r
- if (*s == '(') {\r
- /* Skip over possible bracket from repr(). */\r
- got_bracket = 1;\r
- s++;\r
- while (Py_ISSPACE(*s))\r
- s++;\r
- }\r
-\r
- /* a valid complex string usually takes one of the three forms:\r
-\r
- <float> - real part only\r
- <float>j - imaginary part only\r
- <float><signed-float>j - real and imaginary parts\r
-\r
- where <float> represents any numeric string that's accepted by the\r
- float constructor (including 'nan', 'inf', 'infinity', etc.), and\r
- <signed-float> is any string of the form <float> whose first\r
- character is '+' or '-'.\r
-\r
- For backwards compatibility, the extra forms\r
-\r
- <float><sign>j\r
- <sign>j\r
- j\r
-\r
- are also accepted, though support for these forms may be removed from\r
- a future version of Python.\r
- */\r
-\r
- /* first look for forms starting with <float> */\r
- z = PyOS_string_to_double(s, &end, NULL);\r
- if (z == -1.0 && PyErr_Occurred()) {\r
- if (PyErr_ExceptionMatches(PyExc_ValueError))\r
- PyErr_Clear();\r
- else\r
- goto error;\r
- }\r
- if (end != s) {\r
- /* all 4 forms starting with <float> land here */\r
- s = end;\r
- if (*s == '+' || *s == '-') {\r
- /* <float><signed-float>j | <float><sign>j */\r
- x = z;\r
- y = PyOS_string_to_double(s, &end, NULL);\r
- if (y == -1.0 && PyErr_Occurred()) {\r
- if (PyErr_ExceptionMatches(PyExc_ValueError))\r
- PyErr_Clear();\r
- else\r
- goto error;\r
- }\r
- if (end != s)\r
- /* <float><signed-float>j */\r
- s = end;\r
- else {\r
- /* <float><sign>j */\r
- y = *s == '+' ? 1.0 : -1.0;\r
- s++;\r
- }\r
- if (!(*s == 'j' || *s == 'J'))\r
- goto parse_error;\r
- s++;\r
- }\r
- else if (*s == 'j' || *s == 'J') {\r
- /* <float>j */\r
- s++;\r
- y = z;\r
- }\r
- else\r
- /* <float> */\r
- x = z;\r
- }\r
- else {\r
- /* not starting with <float>; must be <sign>j or j */\r
- if (*s == '+' || *s == '-') {\r
- /* <sign>j */\r
- y = *s == '+' ? 1.0 : -1.0;\r
- s++;\r
- }\r
- else\r
- /* j */\r
- y = 1.0;\r
- if (!(*s == 'j' || *s == 'J'))\r
- goto parse_error;\r
- s++;\r
- }\r
-\r
- /* trailing whitespace and closing bracket */\r
- while (Py_ISSPACE(*s))\r
- s++;\r
- if (got_bracket) {\r
- /* if there was an opening parenthesis, then the corresponding\r
- closing parenthesis should be right here */\r
- if (*s != ')')\r
- goto parse_error;\r
- s++;\r
- while (Py_ISSPACE(*s))\r
- s++;\r
- }\r
-\r
- /* we should now be at the end of the string */\r
- if (s-start != len)\r
- goto parse_error;\r
-\r
-\r
-#ifdef Py_USING_UNICODE\r
- if (s_buffer)\r
- PyMem_FREE(s_buffer);\r
-#endif\r
- return complex_subtype_from_doubles(type, x, y);\r
-\r
- parse_error:\r
- PyErr_SetString(PyExc_ValueError,\r
- "complex() arg is a malformed string");\r
- error:\r
-#ifdef Py_USING_UNICODE\r
- if (s_buffer)\r
- PyMem_FREE(s_buffer);\r
-#endif\r
- return NULL;\r
-}\r
-\r
-static PyObject *\r
-complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
-{\r
- PyObject *r, *i, *tmp;\r
- PyNumberMethods *nbr, *nbi = NULL;\r
- Py_complex cr, ci;\r
- int own_r = 0;\r
- int cr_is_complex = 0;\r
- int ci_is_complex = 0;\r
- static char *kwlist[] = {"real", "imag", 0};\r
-\r
- r = Py_False;\r
- i = NULL;\r
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,\r
- &r, &i))\r
- return NULL;\r
-\r
- /* Special-case for a single argument when type(arg) is complex. */\r
- if (PyComplex_CheckExact(r) && i == NULL &&\r
- type == &PyComplex_Type) {\r
- /* Note that we can't know whether it's safe to return\r
- a complex *subclass* instance as-is, hence the restriction\r
- to exact complexes here. If either the input or the\r
- output is a complex subclass, it will be handled below\r
- as a non-orthogonal vector. */\r
- Py_INCREF(r);\r
- return r;\r
- }\r
- if (PyString_Check(r) || PyUnicode_Check(r)) {\r
- if (i != NULL) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "complex() can't take second arg"\r
- " if first is a string");\r
- return NULL;\r
- }\r
- return complex_subtype_from_string(type, r);\r
- }\r
- if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "complex() second arg can't be a string");\r
- return NULL;\r
- }\r
-\r
- tmp = try_complex_special_method(r);\r
- if (tmp) {\r
- r = tmp;\r
- own_r = 1;\r
- }\r
- else if (PyErr_Occurred()) {\r
- return NULL;\r
- }\r
-\r
- nbr = r->ob_type->tp_as_number;\r
- if (i != NULL)\r
- nbi = i->ob_type->tp_as_number;\r
- if (nbr == NULL || nbr->nb_float == NULL ||\r
- ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "complex() argument must be a string or a number");\r
- if (own_r) {\r
- Py_DECREF(r);\r
- }\r
- return NULL;\r
- }\r
-\r
- /* If we get this far, then the "real" and "imag" parts should\r
- both be treated as numbers, and the constructor should return a\r
- complex number equal to (real + imag*1j).\r
-\r
- Note that we do NOT assume the input to already be in canonical\r
- form; the "real" and "imag" parts might themselves be complex\r
- numbers, which slightly complicates the code below. */\r
- if (PyComplex_Check(r)) {\r
- /* Note that if r is of a complex subtype, we're only\r
- retaining its real & imag parts here, and the return\r
- value is (properly) of the builtin complex type. */\r
- cr = ((PyComplexObject*)r)->cval;\r
- cr_is_complex = 1;\r
- if (own_r) {\r
- Py_DECREF(r);\r
- }\r
- }\r
- else {\r
- /* The "real" part really is entirely real, and contributes\r
- nothing in the imaginary direction.\r
- Just treat it as a double. */\r
- tmp = PyNumber_Float(r);\r
- if (own_r) {\r
- /* r was a newly created complex number, rather\r
- than the original "real" argument. */\r
- Py_DECREF(r);\r
- }\r
- if (tmp == NULL)\r
- return NULL;\r
- if (!PyFloat_Check(tmp)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "float(r) didn't return a float");\r
- Py_DECREF(tmp);\r
- return NULL;\r
- }\r
- cr.real = PyFloat_AsDouble(tmp);\r
- cr.imag = 0.0; /* Shut up compiler warning */\r
- Py_DECREF(tmp);\r
- }\r
- if (i == NULL) {\r
- ci.real = 0.0;\r
- }\r
- else if (PyComplex_Check(i)) {\r
- ci = ((PyComplexObject*)i)->cval;\r
- ci_is_complex = 1;\r
- } else {\r
- /* The "imag" part really is entirely imaginary, and\r
- contributes nothing in the real direction.\r
- Just treat it as a double. */\r
- tmp = (*nbi->nb_float)(i);\r
- if (tmp == NULL)\r
- return NULL;\r
- ci.real = PyFloat_AsDouble(tmp);\r
- Py_DECREF(tmp);\r
- }\r
- /* If the input was in canonical form, then the "real" and "imag"\r
- parts are real numbers, so that ci.imag and cr.imag are zero.\r
- We need this correction in case they were not real numbers. */\r
-\r
- if (ci_is_complex) {\r
- cr.real -= ci.imag;\r
- }\r
- if (cr_is_complex) {\r
- ci.real += cr.imag;\r
- }\r
- return complex_subtype_from_doubles(type, cr.real, ci.real);\r
-}\r
-\r
-PyDoc_STRVAR(complex_doc,\r
-"complex(real[, imag]) -> complex number\n"\r
-"\n"\r
-"Create a complex number from a real part and an optional imaginary part.\n"\r
-"This is equivalent to (real + imag*1j) where imag defaults to 0.");\r
-\r
-static PyNumberMethods complex_as_number = {\r
- (binaryfunc)complex_add, /* nb_add */\r
- (binaryfunc)complex_sub, /* nb_subtract */\r
- (binaryfunc)complex_mul, /* nb_multiply */\r
- (binaryfunc)complex_classic_div, /* nb_divide */\r
- (binaryfunc)complex_remainder, /* nb_remainder */\r
- (binaryfunc)complex_divmod, /* nb_divmod */\r
- (ternaryfunc)complex_pow, /* nb_power */\r
- (unaryfunc)complex_neg, /* nb_negative */\r
- (unaryfunc)complex_pos, /* nb_positive */\r
- (unaryfunc)complex_abs, /* nb_absolute */\r
- (inquiry)complex_nonzero, /* nb_nonzero */\r
- 0, /* nb_invert */\r
- 0, /* nb_lshift */\r
- 0, /* nb_rshift */\r
- 0, /* nb_and */\r
- 0, /* nb_xor */\r
- 0, /* nb_or */\r
- complex_coerce, /* nb_coerce */\r
- complex_int, /* nb_int */\r
- complex_long, /* nb_long */\r
- complex_float, /* nb_float */\r
- 0, /* nb_oct */\r
- 0, /* nb_hex */\r
- 0, /* nb_inplace_add */\r
- 0, /* nb_inplace_subtract */\r
- 0, /* nb_inplace_multiply*/\r
- 0, /* nb_inplace_divide */\r
- 0, /* nb_inplace_remainder */\r
- 0, /* nb_inplace_power */\r
- 0, /* nb_inplace_lshift */\r
- 0, /* nb_inplace_rshift */\r
- 0, /* nb_inplace_and */\r
- 0, /* nb_inplace_xor */\r
- 0, /* nb_inplace_or */\r
- (binaryfunc)complex_int_div, /* nb_floor_divide */\r
- (binaryfunc)complex_div, /* nb_true_divide */\r
- 0, /* nb_inplace_floor_divide */\r
- 0, /* nb_inplace_true_divide */\r
-};\r
-\r
-PyTypeObject PyComplex_Type = {\r
- PyVarObject_HEAD_INIT(&PyType_Type, 0)\r
- "complex",\r
- sizeof(PyComplexObject),\r
- 0,\r
- complex_dealloc, /* tp_dealloc */\r
- (printfunc)complex_print, /* tp_print */\r
- 0, /* tp_getattr */\r
- 0, /* tp_setattr */\r
- 0, /* tp_compare */\r
- (reprfunc)complex_repr, /* tp_repr */\r
- &complex_as_number, /* tp_as_number */\r
- 0, /* tp_as_sequence */\r
- 0, /* tp_as_mapping */\r
- (hashfunc)complex_hash, /* tp_hash */\r
- 0, /* tp_call */\r
- (reprfunc)complex_str, /* tp_str */\r
- PyObject_GenericGetAttr, /* tp_getattro */\r
- 0, /* tp_setattro */\r
- 0, /* tp_as_buffer */\r
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r
- Py_TPFLAGS_BASETYPE, /* tp_flags */\r
- complex_doc, /* tp_doc */\r
- 0, /* tp_traverse */\r
- 0, /* tp_clear */\r
- complex_richcompare, /* tp_richcompare */\r
- 0, /* tp_weaklistoffset */\r
- 0, /* tp_iter */\r
- 0, /* tp_iternext */\r
- complex_methods, /* tp_methods */\r
- complex_members, /* tp_members */\r
- 0, /* tp_getset */\r
- 0, /* tp_base */\r
- 0, /* tp_dict */\r
- 0, /* tp_descr_get */\r
- 0, /* tp_descr_set */\r
- 0, /* tp_dictoffset */\r
- 0, /* tp_init */\r
- PyType_GenericAlloc, /* tp_alloc */\r
- complex_new, /* tp_new */\r
- PyObject_Del, /* tp_free */\r
-};\r
-\r
-#endif\r