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.

1100 lines
31 KiB

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