/Objects/complexobject.c

http://unladen-swallow.googlecode.com/ · C · 1273 lines · 1054 code · 120 blank · 99 comment · 245 complexity · 878e77cf5dc6790c95a85581092f9459 MD5 · raw file

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