You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1108 lines
31 KiB

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