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.

1157 lines
32 KiB

  1. /* Complex object implementation */
  2. /* Borrows heavily from floatobject.c */
  3. /* Submitted by Jim Hugunin */
  4. #include "Python.h"
  5. #include "structmember.h"
  6. /*[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. res->ob_type->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. res->ob_type->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. PyFPE_START_PROTECT("complex_add", return 0)
  420. result = _Py_c_sum(a, b);
  421. PyFPE_END_PROTECT(result)
  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. PyFPE_START_PROTECT("complex_sub", return 0)
  432. result = _Py_c_diff(a, b);
  433. PyFPE_END_PROTECT(result)
  434. return PyComplex_FromCComplex(result);
  435. }
  436. static PyObject *
  437. complex_mul(PyObject *v, PyObject *w)
  438. {
  439. Py_complex result;
  440. Py_complex a, b;
  441. TO_COMPLEX(v, a);
  442. TO_COMPLEX(w, b);
  443. PyFPE_START_PROTECT("complex_mul", return 0)
  444. result = _Py_c_prod(a, b);
  445. PyFPE_END_PROTECT(result)
  446. return PyComplex_FromCComplex(result);
  447. }
  448. static PyObject *
  449. complex_div(PyObject *v, PyObject *w)
  450. {
  451. Py_complex quot;
  452. Py_complex a, b;
  453. TO_COMPLEX(v, a);
  454. TO_COMPLEX(w, b);
  455. PyFPE_START_PROTECT("complex_div", return 0)
  456. errno = 0;
  457. quot = _Py_c_quot(a, b);
  458. PyFPE_END_PROTECT(quot)
  459. if (errno == EDOM) {
  460. PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
  461. return NULL;
  462. }
  463. return PyComplex_FromCComplex(quot);
  464. }
  465. static PyObject *
  466. complex_remainder(PyObject *v, PyObject *w)
  467. {
  468. PyErr_SetString(PyExc_TypeError,
  469. "can't mod complex numbers.");
  470. return NULL;
  471. }
  472. static PyObject *
  473. complex_divmod(PyObject *v, PyObject *w)
  474. {
  475. PyErr_SetString(PyExc_TypeError,
  476. "can't take floor or mod of complex number.");
  477. return NULL;
  478. }
  479. static PyObject *
  480. complex_pow(PyObject *v, PyObject *w, PyObject *z)
  481. {
  482. Py_complex p;
  483. Py_complex exponent;
  484. long int_exponent;
  485. Py_complex a, b;
  486. TO_COMPLEX(v, a);
  487. TO_COMPLEX(w, b);
  488. if (z != Py_None) {
  489. PyErr_SetString(PyExc_ValueError, "complex modulo");
  490. return NULL;
  491. }
  492. PyFPE_START_PROTECT("complex_pow", return 0)
  493. errno = 0;
  494. exponent = b;
  495. int_exponent = (long)exponent.real;
  496. if (exponent.imag == 0. && exponent.real == int_exponent)
  497. p = c_powi(a, int_exponent);
  498. else
  499. p = _Py_c_pow(a, exponent);
  500. PyFPE_END_PROTECT(p)
  501. Py_ADJUST_ERANGE2(p.real, p.imag);
  502. if (errno == EDOM) {
  503. PyErr_SetString(PyExc_ZeroDivisionError,
  504. "0.0 to a negative or complex power");
  505. return NULL;
  506. }
  507. else if (errno == ERANGE) {
  508. PyErr_SetString(PyExc_OverflowError,
  509. "complex exponentiation");
  510. return NULL;
  511. }
  512. return PyComplex_FromCComplex(p);
  513. }
  514. static PyObject *
  515. complex_int_div(PyObject *v, PyObject *w)
  516. {
  517. PyErr_SetString(PyExc_TypeError,
  518. "can't take floor of complex number.");
  519. return NULL;
  520. }
  521. static PyObject *
  522. complex_neg(PyComplexObject *v)
  523. {
  524. Py_complex neg;
  525. neg.real = -v->cval.real;
  526. neg.imag = -v->cval.imag;
  527. return PyComplex_FromCComplex(neg);
  528. }
  529. static PyObject *
  530. complex_pos(PyComplexObject *v)
  531. {
  532. if (PyComplex_CheckExact(v)) {
  533. Py_INCREF(v);
  534. return (PyObject *)v;
  535. }
  536. else
  537. return PyComplex_FromCComplex(v->cval);
  538. }
  539. static PyObject *
  540. complex_abs(PyComplexObject *v)
  541. {
  542. double result;
  543. PyFPE_START_PROTECT("complex_abs", return 0)
  544. result = _Py_c_abs(v->cval);
  545. PyFPE_END_PROTECT(result)
  546. if (errno == ERANGE) {
  547. PyErr_SetString(PyExc_OverflowError,
  548. "absolute value too large");
  549. return NULL;
  550. }
  551. return PyFloat_FromDouble(result);
  552. }
  553. static int
  554. complex_bool(PyComplexObject *v)
  555. {
  556. return v->cval.real != 0.0 || v->cval.imag != 0.0;
  557. }
  558. static PyObject *
  559. complex_richcompare(PyObject *v, PyObject *w, int op)
  560. {
  561. PyObject *res;
  562. Py_complex i;
  563. int equal;
  564. if (op != Py_EQ && op != Py_NE) {
  565. goto Unimplemented;
  566. }
  567. assert(PyComplex_Check(v));
  568. TO_COMPLEX(v, i);
  569. if (PyLong_Check(w)) {
  570. /* Check for 0.0 imaginary part first to avoid the rich
  571. * comparison when possible.
  572. */
  573. if (i.imag == 0.0) {
  574. PyObject *j, *sub_res;
  575. j = PyFloat_FromDouble(i.real);
  576. if (j == NULL)
  577. return NULL;
  578. sub_res = PyObject_RichCompare(j, w, op);
  579. Py_DECREF(j);
  580. return sub_res;
  581. }
  582. else {
  583. equal = 0;
  584. }
  585. }
  586. else if (PyFloat_Check(w)) {
  587. equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
  588. }
  589. else if (PyComplex_Check(w)) {
  590. Py_complex j;
  591. TO_COMPLEX(w, j);
  592. equal = (i.real == j.real && i.imag == j.imag);
  593. }
  594. else {
  595. goto Unimplemented;
  596. }
  597. if (equal == (op == Py_EQ))
  598. res = Py_True;
  599. else
  600. res = Py_False;
  601. Py_INCREF(res);
  602. return res;
  603. Unimplemented:
  604. Py_RETURN_NOTIMPLEMENTED;
  605. }
  606. static PyObject *
  607. complex_int(PyObject *v)
  608. {
  609. PyErr_SetString(PyExc_TypeError,
  610. "can't convert complex to int");
  611. return NULL;
  612. }
  613. static PyObject *
  614. complex_float(PyObject *v)
  615. {
  616. PyErr_SetString(PyExc_TypeError,
  617. "can't convert complex to float");
  618. return NULL;
  619. }
  620. static PyObject *
  621. complex_conjugate(PyObject *self, PyObject *Py_UNUSED(ignored))
  622. {
  623. Py_complex c;
  624. c = ((PyComplexObject *)self)->cval;
  625. c.imag = -c.imag;
  626. return PyComplex_FromCComplex(c);
  627. }
  628. PyDoc_STRVAR(complex_conjugate_doc,
  629. "complex.conjugate() -> complex\n"
  630. "\n"
  631. "Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.");
  632. static PyObject *
  633. complex_getnewargs(PyComplexObject *v, PyObject *Py_UNUSED(ignored))
  634. {
  635. Py_complex c = v->cval;
  636. return Py_BuildValue("(dd)", c.real, c.imag);
  637. }
  638. PyDoc_STRVAR(complex__format__doc,
  639. "complex.__format__() -> str\n"
  640. "\n"
  641. "Convert to a string according to format_spec.");
  642. static PyObject *
  643. complex__format__(PyObject* self, PyObject* args)
  644. {
  645. PyObject *format_spec;
  646. _PyUnicodeWriter writer;
  647. int ret;
  648. if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
  649. return NULL;
  650. _PyUnicodeWriter_Init(&writer);
  651. ret = _PyComplex_FormatAdvancedWriter(
  652. &writer,
  653. self,
  654. format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
  655. if (ret == -1) {
  656. _PyUnicodeWriter_Dealloc(&writer);
  657. return NULL;
  658. }
  659. return _PyUnicodeWriter_Finish(&writer);
  660. }
  661. #if 0
  662. static PyObject *
  663. complex_is_finite(PyObject *self)
  664. {
  665. Py_complex c;
  666. c = ((PyComplexObject *)self)->cval;
  667. return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
  668. Py_IS_FINITE(c.imag)));
  669. }
  670. PyDoc_STRVAR(complex_is_finite_doc,
  671. "complex.is_finite() -> bool\n"
  672. "\n"
  673. "Returns True if the real and the imaginary part is finite.");
  674. #endif
  675. static PyMethodDef complex_methods[] = {
  676. {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
  677. complex_conjugate_doc},
  678. #if 0
  679. {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
  680. complex_is_finite_doc},
  681. #endif
  682. {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
  683. {"__format__", (PyCFunction)complex__format__,
  684. METH_VARARGS, complex__format__doc},
  685. {NULL, NULL} /* sentinel */
  686. };
  687. static PyMemberDef complex_members[] = {
  688. {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
  689. "the real part of a complex number"},
  690. {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
  691. "the imaginary part of a complex number"},
  692. {0},
  693. };
  694. static PyObject *
  695. complex_from_string_inner(const char *s, Py_ssize_t len, void *type)
  696. {
  697. double x=0.0, y=0.0, z;
  698. int got_bracket=0;
  699. const char *start;
  700. char *end;
  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. return NULL;
  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. return NULL;
  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. return complex_subtype_from_doubles((PyTypeObject *)type, x, y);
  799. parse_error:
  800. PyErr_SetString(PyExc_ValueError,
  801. "complex() arg is a malformed string");
  802. return NULL;
  803. }
  804. static PyObject *
  805. complex_subtype_from_string(PyTypeObject *type, PyObject *v)
  806. {
  807. const char *s;
  808. PyObject *s_buffer = NULL, *result = NULL;
  809. Py_ssize_t len;
  810. if (PyUnicode_Check(v)) {
  811. s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v);
  812. if (s_buffer == NULL) {
  813. return NULL;
  814. }
  815. assert(PyUnicode_IS_ASCII(s_buffer));
  816. /* Simply get a pointer to existing ASCII characters. */
  817. s = PyUnicode_AsUTF8AndSize(s_buffer, &len);
  818. assert(s != NULL);
  819. }
  820. else {
  821. PyErr_Format(PyExc_TypeError,
  822. "complex() argument must be a string or a number, not '%.200s'",
  823. Py_TYPE(v)->tp_name);
  824. return NULL;
  825. }
  826. result = _Py_string_to_number_with_underscores(s, len, "complex", v, type,
  827. complex_from_string_inner);
  828. Py_DECREF(s_buffer);
  829. return result;
  830. }
  831. /*[clinic input]
  832. @classmethod
  833. complex.__new__ as complex_new
  834. real as r: object(c_default="_PyLong_Zero") = 0
  835. imag as i: object(c_default="NULL") = 0
  836. Create a complex number from a real part and an optional imaginary part.
  837. This is equivalent to (real + imag*1j) where imag defaults to 0.
  838. [clinic start generated code]*/
  839. static PyObject *
  840. complex_new_impl(PyTypeObject *type, PyObject *r, PyObject *i)
  841. /*[clinic end generated code: output=b6c7dd577b537dc1 input=6f6b0bedba29bcb5]*/
  842. {
  843. PyObject *tmp;
  844. PyNumberMethods *nbr, *nbi = NULL;
  845. Py_complex cr, ci;
  846. int own_r = 0;
  847. int cr_is_complex = 0;
  848. int ci_is_complex = 0;
  849. /* Special-case for a single argument when type(arg) is complex. */
  850. if (PyComplex_CheckExact(r) && i == NULL &&
  851. type == &PyComplex_Type) {
  852. /* Note that we can't know whether it's safe to return
  853. a complex *subclass* instance as-is, hence the restriction
  854. to exact complexes here. If either the input or the
  855. output is a complex subclass, it will be handled below
  856. as a non-orthogonal vector. */
  857. Py_INCREF(r);
  858. return r;
  859. }
  860. if (PyUnicode_Check(r)) {
  861. if (i != NULL) {
  862. PyErr_SetString(PyExc_TypeError,
  863. "complex() can't take second arg"
  864. " if first is a string");
  865. return NULL;
  866. }
  867. return complex_subtype_from_string(type, r);
  868. }
  869. if (i != NULL && PyUnicode_Check(i)) {
  870. PyErr_SetString(PyExc_TypeError,
  871. "complex() second arg can't be a string");
  872. return NULL;
  873. }
  874. tmp = try_complex_special_method(r);
  875. if (tmp) {
  876. r = tmp;
  877. own_r = 1;
  878. }
  879. else if (PyErr_Occurred()) {
  880. return NULL;
  881. }
  882. nbr = r->ob_type->tp_as_number;
  883. if (nbr == NULL || (nbr->nb_float == NULL && nbr->nb_index == NULL)) {
  884. PyErr_Format(PyExc_TypeError,
  885. "complex() first argument must be a string or a number, "
  886. "not '%.200s'",
  887. Py_TYPE(r)->tp_name);
  888. if (own_r) {
  889. Py_DECREF(r);
  890. }
  891. return NULL;
  892. }
  893. if (i != NULL) {
  894. nbi = i->ob_type->tp_as_number;
  895. if (nbi == NULL || (nbi->nb_float == NULL && nbi->nb_index == NULL)) {
  896. PyErr_Format(PyExc_TypeError,
  897. "complex() second argument must be a number, "
  898. "not '%.200s'",
  899. Py_TYPE(i)->tp_name);
  900. if (own_r) {
  901. Py_DECREF(r);
  902. }
  903. return NULL;
  904. }
  905. }
  906. /* If we get this far, then the "real" and "imag" parts should
  907. both be treated as numbers, and the constructor should return a
  908. complex number equal to (real + imag*1j).
  909. Note that we do NOT assume the input to already be in canonical
  910. form; the "real" and "imag" parts might themselves be complex
  911. numbers, which slightly complicates the code below. */
  912. if (PyComplex_Check(r)) {
  913. /* Note that if r is of a complex subtype, we're only
  914. retaining its real & imag parts here, and the return
  915. value is (properly) of the builtin complex type. */
  916. cr = ((PyComplexObject*)r)->cval;
  917. cr_is_complex = 1;
  918. if (own_r) {
  919. Py_DECREF(r);
  920. }
  921. }
  922. else {
  923. /* The "real" part really is entirely real, and contributes
  924. nothing in the imaginary direction.
  925. Just treat it as a double. */
  926. tmp = PyNumber_Float(r);
  927. if (own_r) {
  928. /* r was a newly created complex number, rather
  929. than the original "real" argument. */
  930. Py_DECREF(r);
  931. }
  932. if (tmp == NULL)
  933. return NULL;
  934. assert(PyFloat_Check(tmp));
  935. cr.real = PyFloat_AsDouble(tmp);
  936. cr.imag = 0.0;
  937. Py_DECREF(tmp);
  938. }
  939. if (i == NULL) {
  940. ci.real = cr.imag;
  941. }
  942. else if (PyComplex_Check(i)) {
  943. ci = ((PyComplexObject*)i)->cval;
  944. ci_is_complex = 1;
  945. } else {
  946. /* The "imag" part really is entirely imaginary, and
  947. contributes nothing in the real direction.
  948. Just treat it as a double. */
  949. tmp = PyNumber_Float(i);
  950. if (tmp == NULL)
  951. return NULL;
  952. ci.real = PyFloat_AsDouble(tmp);
  953. Py_DECREF(tmp);
  954. }
  955. /* If the input was in canonical form, then the "real" and "imag"
  956. parts are real numbers, so that ci.imag and cr.imag are zero.
  957. We need this correction in case they were not real numbers. */
  958. if (ci_is_complex) {
  959. cr.real -= ci.imag;
  960. }
  961. if (cr_is_complex && i != NULL) {
  962. ci.real += cr.imag;
  963. }
  964. return complex_subtype_from_doubles(type, cr.real, ci.real);
  965. }
  966. static PyNumberMethods complex_as_number = {
  967. (binaryfunc)complex_add, /* nb_add */
  968. (binaryfunc)complex_sub, /* nb_subtract */
  969. (binaryfunc)complex_mul, /* nb_multiply */
  970. (binaryfunc)complex_remainder, /* nb_remainder */
  971. (binaryfunc)complex_divmod, /* nb_divmod */
  972. (ternaryfunc)complex_pow, /* nb_power */
  973. (unaryfunc)complex_neg, /* nb_negative */
  974. (unaryfunc)complex_pos, /* nb_positive */
  975. (unaryfunc)complex_abs, /* nb_absolute */
  976. (inquiry)complex_bool, /* nb_bool */
  977. 0, /* nb_invert */
  978. 0, /* nb_lshift */
  979. 0, /* nb_rshift */
  980. 0, /* nb_and */
  981. 0, /* nb_xor */
  982. 0, /* nb_or */
  983. complex_int, /* nb_int */
  984. 0, /* nb_reserved */
  985. complex_float, /* nb_float */
  986. 0, /* nb_inplace_add */
  987. 0, /* nb_inplace_subtract */
  988. 0, /* nb_inplace_multiply*/
  989. 0, /* nb_inplace_remainder */
  990. 0, /* nb_inplace_power */
  991. 0, /* nb_inplace_lshift */
  992. 0, /* nb_inplace_rshift */
  993. 0, /* nb_inplace_and */
  994. 0, /* nb_inplace_xor */
  995. 0, /* nb_inplace_or */
  996. (binaryfunc)complex_int_div, /* nb_floor_divide */
  997. (binaryfunc)complex_div, /* nb_true_divide */
  998. 0, /* nb_inplace_floor_divide */
  999. 0, /* nb_inplace_true_divide */
  1000. };
  1001. PyTypeObject PyComplex_Type = {
  1002. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1003. "complex",
  1004. sizeof(PyComplexObject),
  1005. 0,
  1006. 0, /* tp_dealloc */
  1007. 0, /* tp_vectorcall_offset */
  1008. 0, /* tp_getattr */
  1009. 0, /* tp_setattr */
  1010. 0, /* tp_as_async */
  1011. (reprfunc)complex_repr, /* tp_repr */
  1012. &complex_as_number, /* tp_as_number */
  1013. 0, /* tp_as_sequence */
  1014. 0, /* tp_as_mapping */
  1015. (hashfunc)complex_hash, /* tp_hash */
  1016. 0, /* tp_call */
  1017. 0, /* tp_str */
  1018. PyObject_GenericGetAttr, /* tp_getattro */
  1019. 0, /* tp_setattro */
  1020. 0, /* tp_as_buffer */
  1021. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  1022. complex_new__doc__, /* tp_doc */
  1023. 0, /* tp_traverse */
  1024. 0, /* tp_clear */
  1025. complex_richcompare, /* tp_richcompare */
  1026. 0, /* tp_weaklistoffset */
  1027. 0, /* tp_iter */
  1028. 0, /* tp_iternext */
  1029. complex_methods, /* tp_methods */
  1030. complex_members, /* tp_members */
  1031. 0, /* tp_getset */
  1032. 0, /* tp_base */
  1033. 0, /* tp_dict */
  1034. 0, /* tp_descr_get */
  1035. 0, /* tp_descr_set */
  1036. 0, /* tp_dictoffset */
  1037. 0, /* tp_init */
  1038. PyType_GenericAlloc, /* tp_alloc */
  1039. complex_new, /* tp_new */
  1040. PyObject_Del, /* tp_free */
  1041. };