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.

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