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.

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