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