Python-2.7.3/Objects/complexobject.c

No issues found

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